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 4.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. import numpy as np
  22. from PIL import Image
  23. from mindspore_serving.server import register
  24. from mindarmour.natural_robustness.transform.image import Contrast, GaussianBlur, SaltAndPepperNoise, Scale, Shear, \
  25. Translate, Rotate, MotionBlur, GradientBlur, GradientLuminance, NaturalNoise, Curve, Perspective
  26. CHARACTERS = [chr(i) for i in range(65, 91)]+[chr(j) for j in range(97, 123)]
  27. methods_dict = {'Contrast': Contrast,
  28. 'GaussianBlur': GaussianBlur,
  29. 'SaltAndPepperNoise': SaltAndPepperNoise,
  30. 'Translate': Translate,
  31. 'Scale': Scale,
  32. 'Shear': Shear,
  33. 'Rotate': Rotate,
  34. 'MotionBlur': MotionBlur,
  35. 'GradientBlur': GradientBlur,
  36. 'GradientLuminance': GradientLuminance,
  37. 'NaturalNoise': NaturalNoise,
  38. 'Curve': Curve,
  39. 'Perspective': Perspective}
  40. def check_inputs(img, perturb_config, methods_number, outputs_number):
  41. """Check inputs."""
  42. if not np.any(img):
  43. raise ValueError("img cannot be empty.")
  44. img = Image.open(BytesIO(img))
  45. img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
  46. config = json.loads(perturb_config)
  47. if not config:
  48. raise ValueError("perturb_config cannot be empty.")
  49. for item in config:
  50. if item['method'] not in methods_dict.keys():
  51. raise ValueError("{} is not a valid method.".format(item['method']))
  52. methods_number = int(methods_number)
  53. if methods_number < 1:
  54. raise ValueError("methods_number must more than 0.")
  55. outputs_number = int(outputs_number)
  56. if outputs_number < 1:
  57. raise ValueError("outputs_number must more than 0.")
  58. return img, config, methods_number, outputs_number
  59. def perturb(img, perturb_config, methods_number, outputs_number):
  60. """Perturb given image."""
  61. img, config, methods_number, outputs_number = check_inputs(img, perturb_config, methods_number, outputs_number)
  62. res_img_bytes = b''
  63. file_names = []
  64. file_length = []
  65. names_dict = {}
  66. for _ in range(outputs_number):
  67. dst = copy.deepcopy(img)
  68. used_methods = []
  69. for _ in range(methods_number):
  70. item = np.random.choice(config)
  71. method_name = item['method']
  72. method = methods_dict[method_name]
  73. params = item['params']
  74. dst = method(**params)(img)
  75. method_params = params
  76. used_methods.append([method_name, method_params])
  77. name = ''.join(random.sample(CHARACTERS, 20))
  78. name += '.png'
  79. file_names.append(name)
  80. names_dict[name] = used_methods
  81. res_img = cv2.imencode('.png', dst)[1].tobytes()
  82. res_img_bytes += res_img
  83. file_length.append(len(res_img))
  84. names_dict = json.dumps(names_dict)
  85. return res_img_bytes, ';'.join(file_names), file_length, names_dict
  86. @register.register_method(output_names=["results", "file_names", "file_length", "names_dict"])
  87. def natural_perturbation(img, perturb_config, methods_number, outputs_number):
  88. """method natural_perturbation data flow definition, only preprocessing and call model"""
  89. res = register.add_stage(perturb, img, perturb_config, methods_number, outputs_number, outputs_count=4)
  90. return res

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