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.

explain_job_encap.py 4.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. """Explain job list encapsulator."""
  16. import copy
  17. from datetime import datetime
  18. from mindinsight.utils.exceptions import ParamValueError
  19. from mindinsight.explainer.encapsulator.explain_data_encap import ExplainDataEncap
  20. class ExplainJobEncap(ExplainDataEncap):
  21. """Explain job list encapsulator."""
  22. DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
  23. DEFAULT_MIN_CONFIDENCE = 0.5
  24. def query_explain_jobs(self, offset, limit):
  25. """
  26. Query explain job list.
  27. Args:
  28. offset (int): Page offset.
  29. limit (int): Max. no. of items to be returned.
  30. Returns:
  31. Tuple[int, List[Dict]], total no. of jobs and job list.
  32. """
  33. total, dir_infos = self.job_manager.get_job_list(offset=offset, limit=limit)
  34. job_infos = [self._dir_2_info(dir_info) for dir_info in dir_infos]
  35. return total, job_infos
  36. def query_meta(self, train_id):
  37. """
  38. Query explain job meta-data.
  39. Args:
  40. train_id (str): Job ID.
  41. Returns:
  42. Dict, the metadata.
  43. """
  44. job = self.job_manager.get_job(train_id)
  45. if job is None:
  46. return None
  47. return self._job_2_meta(job)
  48. def query_image_binary(self, train_id, image_id, image_type):
  49. """
  50. Query image binary content.
  51. Args:
  52. train_id (str): Job ID.
  53. image_id (str): Image ID.
  54. image_type (str): Image type, 'original' or 'overlay'.
  55. Returns:
  56. bytes, image binary.
  57. """
  58. job = self.job_manager.get_job(train_id)
  59. if job is None:
  60. return None
  61. if image_type == "original":
  62. binary = job.retrieve_image(image_id)
  63. elif image_type == "overlay":
  64. binary = job.retrieve_overlay(image_id)
  65. else:
  66. raise ParamValueError(f"image_type:{image_type}")
  67. return binary
  68. @classmethod
  69. def _dir_2_info(cls, dir_info):
  70. """Convert ExplainJob object to jsonable info object."""
  71. info = dict()
  72. info["train_id"] = dir_info["relative_path"]
  73. info["create_time"] = dir_info["create_time"].strftime(cls.DATETIME_FORMAT)
  74. info["update_time"] = dir_info["update_time"].strftime(cls.DATETIME_FORMAT)
  75. return info
  76. @classmethod
  77. def _job_2_info(cls, job):
  78. """Convert ExplainJob object to jsonable info object."""
  79. info = dict()
  80. info["train_id"] = job.train_id
  81. info["create_time"] = datetime.fromtimestamp(job.create_time)\
  82. .strftime(cls.DATETIME_FORMAT)
  83. info["update_time"] = datetime.fromtimestamp(job.latest_update_time)\
  84. .strftime(cls.DATETIME_FORMAT)
  85. return info
  86. @classmethod
  87. def _job_2_meta(cls, job):
  88. """Convert ExplainJob's meta-data to jsonable info object."""
  89. info = cls._job_2_info(job)
  90. info["sample_count"] = job.sample_count
  91. info["classes"] = copy.deepcopy(job.all_classes)
  92. saliency_info = dict()
  93. if job.min_confidence is None:
  94. saliency_info["min_confidence"] = cls.DEFAULT_MIN_CONFIDENCE
  95. else:
  96. saliency_info["min_confidence"] = job.min_confidence
  97. saliency_info["explainers"] = list(job.explainers)
  98. saliency_info["metrics"] = list(job.metrics)
  99. info["saliency"] = saliency_info
  100. info["uncertainty"] = {"enabled": False}
  101. return info