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.

explainer_api.py 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. # Copyright 2020-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. """Explainer restful api."""
  16. import json
  17. import os
  18. import urllib.parse
  19. from flask import Blueprint
  20. from flask import jsonify
  21. from flask import request
  22. from mindinsight.conf import settings
  23. from mindinsight.datavisual.common.validation import Validation
  24. from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  25. from mindinsight.datavisual.utils.tools import get_train_id
  26. from mindinsight.explainer.encapsulator.datafile_encap import DatafileEncap
  27. from mindinsight.explainer.encapsulator.evaluation_encap import EvaluationEncap
  28. from mindinsight.explainer.encapsulator.explain_job_encap import ExplainJobEncap
  29. from mindinsight.explainer.encapsulator.hierarchical_occlusion_encap import HierarchicalOcclusionEncap
  30. from mindinsight.explainer.encapsulator.saliency_encap import SaliencyEncap
  31. from mindinsight.explainer.manager.explain_manager import EXPLAIN_MANAGER
  32. from mindinsight.utils.exceptions import ParamMissError
  33. from mindinsight.utils.exceptions import ParamTypeError
  34. from mindinsight.utils.exceptions import ParamValueError
  35. URL_PREFIX = settings.URL_PATH_PREFIX + settings.API_PREFIX
  36. BLUEPRINT = Blueprint("explainer", __name__, url_prefix=URL_PREFIX)
  37. def _validate_type(param, name, expected_types):
  38. """
  39. Common function to validate type.
  40. Args:
  41. param (object): Parameter to be validated.
  42. name (str): Name of the parameter.
  43. expected_types (type, tuple[type]): Expected type(s) of param.
  44. Raises:
  45. ParamTypeError: When param is not an instance of expected_types.
  46. """
  47. if not isinstance(param, expected_types):
  48. raise ParamTypeError(name, expected_types)
  49. def _validate_value(param, name, expected_values):
  50. """
  51. Common function to validate values of param.
  52. Args:
  53. param (object): Parameter to be validated.
  54. name (str): Name of the parameter.
  55. expected_values (tuple) : Expected values of param.
  56. Raises:
  57. ParamValueError: When param is not in expected_values.
  58. """
  59. if param not in expected_values:
  60. raise ParamValueError(f"Valid options for {name} are {expected_values}, but got {param}.")
  61. def _image_url_formatter(train_id, image_path, image_type):
  62. """
  63. Returns image url.
  64. Args:
  65. train_id (str): Id that specifies explain job.
  66. image_path (str): Local path or unique string that specifies the image for query.
  67. image_type (str): Image query type.
  68. Returns:
  69. str, url string for image query.
  70. """
  71. data = {
  72. "train_id": train_id,
  73. "path": image_path,
  74. "type": image_type
  75. }
  76. return f"{URL_PREFIX}/explainer/image?{urllib.parse.urlencode(data)}"
  77. def _read_post_request(post_request):
  78. """
  79. Extract the body of post request.
  80. Args:
  81. post_request (object): The post request.
  82. Returns:
  83. dict, the deserialized body of request.
  84. """
  85. body = post_request.stream.read()
  86. try:
  87. body = json.loads(body if body else "{}")
  88. except json.decoder.JSONDecodeError:
  89. raise ParamValueError("Json data parse failed.")
  90. return body
  91. def _get_query_sample_parameters(data):
  92. """
  93. Get parameter for query.
  94. Args:
  95. data (dict): Dict that contains request info.
  96. Returns:
  97. dict, key-value pairs to call backend query functions.
  98. Raises:
  99. ParamMissError: If train_id info is not in the request.
  100. ParamTypeError: If certain key is not in the expected type in the request.
  101. ParamValueError: If certain key does not have the expected value in the request.
  102. """
  103. train_id = data.get("train_id")
  104. if train_id is None:
  105. raise ParamMissError('train_id')
  106. labels = data.get("labels")
  107. if labels is not None:
  108. _validate_type(labels, "labels", list)
  109. if labels:
  110. for item in labels:
  111. _validate_type(item, "element of labels", str)
  112. limit = data.get("limit", 10)
  113. limit = Validation.check_limit(limit, min_value=1, max_value=100)
  114. offset = data.get("offset", 0)
  115. offset = Validation.check_offset(offset=offset)
  116. sorted_name = data.get("sorted_name", "")
  117. _validate_value(sorted_name, "sorted_name", ('', 'confidence', 'uncertainty'))
  118. sorted_type = data.get("sorted_type", "descending")
  119. _validate_value(sorted_type, "sorted_type", ("ascending", "descending"))
  120. prediction_types = data.get("prediction_types")
  121. if prediction_types is not None:
  122. _validate_type(prediction_types, "element of labels", list)
  123. if prediction_types:
  124. for item in prediction_types:
  125. _validate_value(item, "element of prediction_types", ('TP', 'FN', 'FP'))
  126. query_kwarg = {"train_id": train_id,
  127. "labels": labels,
  128. "limit": limit,
  129. "offset": offset,
  130. "sorted_name": sorted_name,
  131. "sorted_type": sorted_type,
  132. "prediction_types": prediction_types}
  133. return query_kwarg
  134. @BLUEPRINT.route("/explainer/explain-jobs", methods=["GET"])
  135. def query_explain_jobs():
  136. """
  137. Query explain jobs.
  138. Returns:
  139. Response, contains dict that stores base directory, total number of jobs and their detailed job metadata.
  140. Raises:
  141. ParamMissError: If train_id info is not in the request.
  142. ParamTypeError: If one of (offset, limit) is not integer in the request.
  143. ParamValueError: If one of (offset, limit) does not have the expected value in the request.
  144. """
  145. offset = request.args.get("offset", default=0)
  146. limit = request.args.get("limit", default=10)
  147. offset = Validation.check_offset(offset=offset)
  148. limit = Validation.check_limit(limit, min_value=1, max_value=SummaryWatcher.MAX_SUMMARY_DIR_COUNT)
  149. encapsulator = ExplainJobEncap(EXPLAIN_MANAGER)
  150. total, jobs = encapsulator.query_explain_jobs(offset, limit)
  151. return jsonify({
  152. 'name': os.path.basename(os.path.realpath(settings.SUMMARY_BASE_DIR)),
  153. 'total': total,
  154. 'explain_jobs': jobs,
  155. })
  156. @BLUEPRINT.route("/explainer/explain-job", methods=["GET"])
  157. def query_explain_job():
  158. """
  159. Query explain job meta-data.
  160. Returns:
  161. Response, contains dict that stores metadata of the requested job.
  162. Raises:
  163. ParamMissError: If train_id info is not in the request.
  164. """
  165. train_id = get_train_id(request)
  166. if train_id is None:
  167. raise ParamMissError("train_id")
  168. encapsulator = ExplainJobEncap(EXPLAIN_MANAGER)
  169. metadata = encapsulator.query_meta(train_id)
  170. return jsonify(metadata)
  171. @BLUEPRINT.route("/explainer/saliency", methods=["POST"])
  172. def query_saliency():
  173. """
  174. Query saliency map related results.
  175. Returns:
  176. Response, contains dict that stores number of samples and the detailed sample info.
  177. Raises:
  178. ParamTypeError: If certain key is not in the expected type in the request.
  179. ParamValueError: If certain key does not have the expected value in the request.
  180. """
  181. data = _read_post_request(request)
  182. query_kwarg = _get_query_sample_parameters(data)
  183. explainers = data.get("explainers")
  184. if explainers is not None and not isinstance(explainers, list):
  185. raise ParamTypeError("explainers", (list, None))
  186. if explainers:
  187. for item in explainers:
  188. if not isinstance(item, str):
  189. raise ParamTypeError("element of explainers", str)
  190. query_kwarg["explainers"] = explainers
  191. encapsulator = SaliencyEncap(
  192. _image_url_formatter,
  193. EXPLAIN_MANAGER)
  194. count, samples = encapsulator.query_saliency_maps(**query_kwarg)
  195. return jsonify({
  196. "count": count,
  197. "samples": samples
  198. })
  199. @BLUEPRINT.route("/explainer/hoc", methods=["POST"])
  200. def query_hoc():
  201. """
  202. Query hierarchical occlusion related results.
  203. Returns:
  204. Response, contains dict that stores number of samples and the detailed sample info.
  205. Raises:
  206. ParamTypeError: If certain key is not in the expected type in the request.
  207. ParamValueError: If certain key does not have the expected value in the request.
  208. """
  209. data = _read_post_request(request)
  210. query_kwargs = _get_query_sample_parameters(data)
  211. filter_empty = data.get("drop_empty", True)
  212. if not isinstance(filter_empty, bool):
  213. raise ParamTypeError("drop_empty", bool)
  214. query_kwargs["drop_empty"] = filter_empty
  215. encapsulator = HierarchicalOcclusionEncap(
  216. _image_url_formatter,
  217. EXPLAIN_MANAGER)
  218. count, samples = encapsulator.query_hierarchical_occlusion(**query_kwargs)
  219. return jsonify({
  220. "count": count,
  221. "samples": samples
  222. })
  223. @BLUEPRINT.route("/explainer/evaluation", methods=["GET"])
  224. def query_evaluation():
  225. """
  226. Query saliency explainer evaluation scores.
  227. Returns:
  228. Response, contains dict that stores evaluation scores.
  229. Raises:
  230. ParamMissError: If train_id info is not in the request.
  231. """
  232. train_id = get_train_id(request)
  233. if train_id is None:
  234. raise ParamMissError("train_id")
  235. encapsulator = EvaluationEncap(EXPLAIN_MANAGER)
  236. scores = encapsulator.query_explainer_scores(train_id)
  237. return jsonify({
  238. "explainer_scores": scores,
  239. })
  240. @BLUEPRINT.route("/explainer/image", methods=["GET"])
  241. def query_image():
  242. """
  243. Query image.
  244. Returns:
  245. bytes, image binary content for UI to demonstrate.
  246. """
  247. train_id = get_train_id(request)
  248. if train_id is None:
  249. raise ParamMissError("train_id")
  250. image_path = request.args.get("path")
  251. if image_path is None:
  252. raise ParamMissError("path")
  253. image_type = request.args.get("type")
  254. if image_type is None:
  255. raise ParamMissError("type")
  256. if image_type not in ("original", "overlay", "outcome"):
  257. raise ParamValueError(f"type:{image_type}, valid options: 'original' 'overlay' 'outcome'")
  258. encapsulator = DatafileEncap(EXPLAIN_MANAGER)
  259. image = encapsulator.query_image_binary(train_id, image_path, image_type)
  260. return image
  261. def init_module(app):
  262. """
  263. Init module entry.
  264. Args:
  265. app (flask.app): The application obj.
  266. """
  267. app.register_blueprint(BLUEPRINT)