You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

servable_config.py 5.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Copyright 2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """perturbation servable config"""
  16. import json
  17. import copy
  18. import random
  19. from io import BytesIO
  20. import cv2
  21. from PIL import Image
  22. from mindspore_serving.server import register
  23. from mindarmour.natural_robustness.natural_noise import *
  24. # Path of template images
  25. TEMPLATE_LEAF_PATH = '/root/mindarmour/example/adv/test_data/template/leaf'
  26. TEMPLATE_WINDOW_PATH = '/root/mindarmour/example/adv/test_data/template/window'
  27. TEMPLATE_PERSON_PATH = '/root/mindarmour/example/adv/test_data/template/person'
  28. TEMPLATE_BACKGROUND_PATH = '/root/mindarmour/example/adv/test_data//template/dirt_background'
  29. CHARACTERS = [chr(i) for i in range(65, 91)]+[chr(j) for j in range(97, 123)]
  30. path_dict = {'leaf': TEMPLATE_LEAF_PATH,
  31. 'window': TEMPLATE_WINDOW_PATH,
  32. 'person': TEMPLATE_PERSON_PATH,
  33. 'background': TEMPLATE_BACKGROUND_PATH}
  34. methods_dict = {'Contrast': Contrast,
  35. 'GaussianBlur': GaussianBlur,
  36. 'SaltAndPepperNoise': SaltAndPepperNoise,
  37. 'Translate': Translate,
  38. 'Scale': Scale,
  39. 'Shear': Shear,
  40. 'Rotate': Rotate,
  41. 'MotionBlur': MotionBlur,
  42. 'GradientBlur': GradientBlur,
  43. 'GradientLuminance': GradientLuminance,
  44. 'Perlin': Perlin,
  45. 'BackShadow': BackShadow,
  46. 'NaturalNoise': NaturalNoise,
  47. 'Curve': Curve,
  48. 'BackgroundWord': BackgroundWord,
  49. 'Perspective': Perspective}
  50. def check_inputs(img, perturb_config, methods_number, outputs_number):
  51. """Check inputs."""
  52. if not np.any(img):
  53. raise ValueError("img cannot be empty.")
  54. img = Image.open(BytesIO(img))
  55. img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
  56. config = json.loads(perturb_config)
  57. if not config:
  58. raise ValueError("perturb_config cannot be empty.")
  59. for item in config:
  60. if item['method'] not in methods_dict.keys():
  61. raise ValueError("{} is not a valid method.".format(item['method']))
  62. if item['method'] == 'BackShadow':
  63. item['params']['template_path'] = path_dict[item['params']['back_type']]
  64. del item['params']['back_type']
  65. methods_number = int(methods_number)
  66. if methods_number < 1:
  67. raise ValueError("methods_number must more than 0.")
  68. outputs_number = int(outputs_number)
  69. if outputs_number < 1:
  70. raise ValueError("outputs_number must more than 0.")
  71. return img, config, methods_number, outputs_number
  72. def perturb(img, perturb_config, methods_number, outputs_number):
  73. """Perturb given image."""
  74. img, config, methods_number, outputs_number = check_inputs(img, perturb_config, methods_number, outputs_number)
  75. res_img_bytes = b''
  76. file_names = []
  77. file_length = []
  78. names_dict = {}
  79. for _ in range(outputs_number):
  80. dst = copy.deepcopy(img)
  81. used_methods = []
  82. for _ in range(methods_number):
  83. item = np.random.choice(config)
  84. method_name = item['method']
  85. method = methods_dict[method_name]
  86. params = item['params']
  87. dst = method(**params)(img)
  88. if method_name == 'BackShadow':
  89. method_params = copy.deepcopy(params)
  90. method_params['back_type'] = method_params['template_path'].split('/')[-1]
  91. del method_params['template_path']
  92. else:
  93. method_params = params
  94. used_methods.append([method_name, method_params])
  95. name = ''.join(random.sample(CHARACTERS, 20))
  96. name += '.png'
  97. file_names.append(name)
  98. names_dict[name] = used_methods
  99. res_img = cv2.imencode('.png', dst)[1].tobytes()
  100. res_img_bytes += res_img
  101. file_length.append(len(res_img))
  102. names_dict = json.dumps(names_dict)
  103. return res_img_bytes, ';'.join(file_names), file_length, names_dict
  104. model = register.declare_model(model_file="tensor_add.mindir", model_format="MindIR", with_batch_dim=False)
  105. @register.register_method(output_names=["results", "file_names", "file_length", "names_dict"])
  106. def natural_perturbation(img, perturb_config, methods_number, outputs_number):
  107. """method natural_perturbation data flow definition, only preprocessing and call model"""
  108. res = register.add_stage(perturb, img, perturb_config, methods_number, outputs_number, outputs_count=4)
  109. return res

MindArmour关注AI的安全和隐私问题。致力于增强模型的安全可信、保护用户的数据隐私。主要包含3个模块:对抗样本鲁棒性模块、Fuzz Testing模块、隐私保护与评估模块。 对抗样本鲁棒性模块 对抗样本鲁棒性模块用于评估模型对于对抗样本的鲁棒性,并提供模型增强方法用于增强模型抗对抗样本攻击的能力,提升模型鲁棒性。对抗样本鲁棒性模块包含了4个子模块:对抗样本的生成、对抗样本的检测、模型防御、攻防评估。