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.

datafile_encap.py 4.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # Copyright 2020 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. """Datafile encapsulator."""
  16. import os
  17. import io
  18. from PIL import Image
  19. import numpy as np
  20. from mindinsight.utils.exceptions import UnknownError
  21. from mindinsight.utils.exceptions import FileSystemPermissionError
  22. from mindinsight.datavisual.common.exceptions import ImageNotExistError
  23. from mindinsight.explainer.encapsulator.explain_data_encap import ExplainDataEncap
  24. # Max uint8 value. for converting RGB pixels to [0,1] intensity.
  25. _UINT8_MAX = 255
  26. # Color of low saliency.
  27. _SALIENCY_CMAP_LOW = (55, 25, 86, 255)
  28. # Color of high saliency.
  29. _SALIENCY_CMAP_HI = (255, 255, 0, 255)
  30. # Channel modes.
  31. _SINGLE_CHANNEL_MODE = "L"
  32. _RGBA_MODE = "RGBA"
  33. _RGB_MODE = "RGB"
  34. _PNG_FORMAT = "PNG"
  35. def _clean_train_id_b4_join(train_id):
  36. """Clean train_id before joining to a path."""
  37. if train_id.startswith("./") or train_id.startswith(".\\"):
  38. return train_id[2:]
  39. return train_id
  40. class DatafileEncap(ExplainDataEncap):
  41. """Datafile encapsulator."""
  42. def query_image_binary(self, train_id, image_path, image_type):
  43. """
  44. Query image binary content.
  45. Args:
  46. train_id (str): Job ID.
  47. image_path (str): Image path relative to explain job's summary directory.
  48. image_type (str): Image type, 'original' or 'overlay'.
  49. Returns:
  50. bytes, image binary.
  51. """
  52. abs_image_path = os.path.join(self.job_manager.summary_base_dir,
  53. _clean_train_id_b4_join(train_id),
  54. image_path)
  55. if self._is_forbidden(abs_image_path):
  56. raise FileSystemPermissionError("Forbidden.")
  57. try:
  58. if image_type != "overlay":
  59. # no need to convert
  60. with open(abs_image_path, "rb") as fp:
  61. return fp.read()
  62. image = Image.open(abs_image_path)
  63. if image.mode == _RGBA_MODE:
  64. # It is RGBA already, do not convert.
  65. with open(abs_image_path, "rb") as fp:
  66. return fp.read()
  67. except FileNotFoundError:
  68. raise ImageNotExistError(f"train_id:{train_id} path:{image_path} type:{image_type}")
  69. except PermissionError:
  70. raise FileSystemPermissionError(f"train_id:{train_id} path:{image_path} type:{image_type}")
  71. except OSError:
  72. raise UnknownError(f"Invalid image file: train_id:{train_id} path:{image_path} type:{image_type}")
  73. if image.mode == _SINGLE_CHANNEL_MODE:
  74. saliency = np.asarray(image)/_UINT8_MAX
  75. elif image.mode == _RGB_MODE:
  76. saliency = np.asarray(image)
  77. saliency = saliency[:, :, 0]/_UINT8_MAX
  78. else:
  79. raise UnknownError(f"Invalid overlay image mode:{image.mode}.")
  80. saliency_stack = np.empty((saliency.shape[0], saliency.shape[1], 4))
  81. for c in range(3):
  82. saliency_stack[:, :, c] = saliency
  83. rgba = saliency_stack * _SALIENCY_CMAP_HI
  84. rgba += (1-saliency_stack) * _SALIENCY_CMAP_LOW
  85. rgba[:, :, 3] = saliency * _UINT8_MAX
  86. overlay = Image.fromarray(np.uint8(rgba), mode=_RGBA_MODE)
  87. buffer = io.BytesIO()
  88. overlay.save(buffer, format=_PNG_FORMAT)
  89. return buffer.getvalue()
  90. def _is_forbidden(self, path):
  91. """Check if the path is outside summary base dir."""
  92. base_dir = os.path.realpath(self.job_manager.summary_base_dir)
  93. path = os.path.realpath(path)
  94. return not path.startswith(base_dir)