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.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. from io import BytesIO
  19. import cv2
  20. from PIL import Image
  21. import numpy as np
  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. path_dict = {'leaf': TEMPLATE_LEAF_PATH,
  30. 'window': TEMPLATE_WINDOW_PATH,
  31. 'person': TEMPLATE_PERSON_PATH,
  32. 'background': TEMPLATE_BACKGROUND_PATH}
  33. methods_dict = {'Contrast': Contrast,
  34. 'GaussianBlur': GaussianBlur,
  35. 'SaltAndPepperNoise': SaltAndPepperNoise,
  36. 'Translate': Translate,
  37. 'Scale': Scale,
  38. 'Shear': Shear,
  39. 'Rotate': Rotate,
  40. 'MotionBlur': MotionBlur,
  41. 'GradientBlur': GradientBlur,
  42. 'GradientLuminance': GradientLuminance,
  43. 'Perlin': Perlin,
  44. 'BackShadow': BackShadow,
  45. 'NaturalNoise': NaturalNoise,
  46. 'Curve': Curve,
  47. 'BackgroundWord': BackgroundWord,
  48. 'Perspective': Perspective}
  49. def check_inputs(img, perturb_config, methods_number, outputs_number):
  50. """Check inputs."""
  51. if not np.any(img):
  52. raise ValueError("img cannot be empty.")
  53. img = Image.open(BytesIO(img))
  54. img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
  55. config = json.loads(perturb_config)
  56. if not config:
  57. raise ValueError("perturb_config cannot be empty.")
  58. for item in config:
  59. if item['method'] not in methods_dict.keys():
  60. raise ValueError("{} is not a valid method.".format(item['method']))
  61. if item['method'] == 'BackShadow':
  62. item['params']['template_path'] = path_dict[item['params']['back_type']]
  63. del item['params']['back_type']
  64. methods_number = int(methods_number)
  65. if methods_number < 1:
  66. raise ValueError("methods_number must more than 0.")
  67. outputs_number = int(outputs_number)
  68. if outputs_number < 1:
  69. raise ValueError("outputs_number must more than 0.")
  70. return img, config, methods_number, outputs_number
  71. def perturb(img, perturb_config, methods_number, outputs_number):
  72. img, config, methods_number, outputs_number = check_inputs(img, perturb_config, methods_number, outputs_number)
  73. res_img_bytes = b''
  74. file_names = []
  75. file_length = []
  76. for _ in range(outputs_number):
  77. file_name = ''
  78. dst = copy.deepcopy(img)
  79. for _ in range(methods_number):
  80. item = np.random.choice(config)
  81. method_name = item['method']
  82. method = methods_dict[method_name]
  83. params = item['params']
  84. dst = method(**params)(img)
  85. file_name = file_name + method_name + '_'
  86. for key in params:
  87. if key == 'template_path':
  88. file_name += 'back_type_'
  89. file_name += params[key].split('/')[-1]
  90. file_name += '_'
  91. continue
  92. file_name += key
  93. file_name += '_'
  94. file_name += str(params[key])
  95. file_name += '_'
  96. file_name += '#'
  97. file_name += '.png'
  98. file_names.append(file_name)
  99. res_img = cv2.imencode('.png', dst)[1].tobytes()
  100. res_img_bytes += res_img
  101. file_length.append(len(res_img))
  102. return res_img_bytes, ';'.join(file_names), file_length
  103. model = register.declare_model(model_file="tensor_add.mindir", model_format="MindIR", with_batch_dim=False)
  104. @register.register_method(output_names=["results", "file_names", "file_length"])
  105. def natural_perturbation(img, perturb_config, methods_number, outputs_number):
  106. """method natural_perturbation data flow definition, only preprocessing and call model"""
  107. res = register.add_stage(perturb, img, perturb_config, methods_number, outputs_number, outputs_count=3)
  108. return res

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