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.

parse_summary.py 7.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. """Parse summary file."""
  16. import argparse
  17. import os
  18. import datetime
  19. from mindinsight.utils.command import BaseCommand
  20. from mindinsight.utils.exceptions import UnknownError
  21. from mindinsight.datavisual.common.log import parse_summary_logger
  22. from mindinsight.datavisual.data_access.file_handler import FileHandler
  23. from mindinsight.datavisual.data_transform.ms_data_loader import _SummaryParser
  24. from mindinsight.datavisual.data_transform.summary_parser.event_parser import EventParser
  25. class DirAction(argparse.Action):
  26. """File directory action class definition."""
  27. @staticmethod
  28. def check_path(file_path):
  29. """
  30. Check argument for file path.
  31. Args:
  32. file_path (str): File path.
  33. """
  34. if file_path.startswith('~'):
  35. file_path = os.path.realpath(os.path.expanduser(file_path))
  36. if not file_path.startswith('/'):
  37. file_path = os.path.realpath(FileHandler.join(os.getcwd(), file_path))
  38. return os.path.realpath(file_path)
  39. def __call__(self, parser_in, namespace, values, option_string=None):
  40. """
  41. Inherited __call__ method from argparse.Action.
  42. Args:
  43. parser_in (ArgumentParser): Passed-in argument parser.
  44. namespace (Namespace): Namespace object to hold arguments.
  45. values (object): Argument values with type depending on argument definition.
  46. option_string (str): Optional string for specific argument name. Default: None.
  47. """
  48. summary_dir = self.check_path(values)
  49. setattr(namespace, self.dest, summary_dir)
  50. class OutputDirAction(argparse.Action):
  51. """File directory action class definition."""
  52. def __call__(self, parser_in, namespace, values, option_string=None):
  53. """
  54. Inherited __call__ method from argparse.Action.
  55. Args:
  56. parser_in (ArgumentParser): Passed-in argument parser.
  57. namespace (Namespace): Namespace object to hold arguments.
  58. values (object): Argument values with type depending on argument definition.
  59. option_string (str): Optional string for specific argument name. Default: None.
  60. """
  61. output = DirAction.check_path(values)
  62. setattr(namespace, self.dest, output)
  63. class Command(BaseCommand):
  64. """Start mindinsight service."""
  65. name = 'parse_summary'
  66. description = 'Parse summary file'
  67. def add_arguments(self, parser):
  68. """
  69. Add arguments to parser.
  70. Args:
  71. parser (ArgumentParser): Specify parser to which arguments are added.
  72. """
  73. parser.add_argument(
  74. '--summary-dir',
  75. type=str,
  76. action=DirAction,
  77. default=os.path.realpath(os.getcwd()),
  78. help="""
  79. Optional, specify path for summary file directory.
  80. Default directory is the current working directory.
  81. """)
  82. parser.add_argument(
  83. '--output',
  84. type=str,
  85. action=OutputDirAction,
  86. default=os.path.realpath(os.getcwd()),
  87. help="""
  88. Optional, specify path for converted file directory. Default output
  89. directory is `output` folder in the current working directory.
  90. """)
  91. def run(self, args):
  92. """
  93. Execute for start command.
  94. Args:
  95. args (Namespace): Parsed arguments to hold customized parameters.
  96. """
  97. try:
  98. date_time = datetime.datetime.now().strftime('output_%Y%m%d_%H%M%S_%f')
  99. output_path = os.path.join(args.output, date_time)
  100. summary_dir = args.summary_dir
  101. if not self._check_dirpath(summary_dir):
  102. return
  103. summary_parser = _SummaryParser(summary_dir)
  104. summary_files = summary_parser.filter_files(os.listdir(summary_dir))
  105. if not summary_files:
  106. parse_summary_logger.error('Path %s has no summary file.', summary_dir)
  107. return
  108. summary_files = summary_parser.sort_files(summary_files)
  109. filename = summary_files[-1]
  110. summary_file = FileHandler.join(summary_dir, filename)
  111. if not (self._check_filepath(summary_file) and self._check_create_filepath(
  112. output_path) and self._check_create_filepath(FileHandler.join(output_path, 'image'))):
  113. return
  114. eventparser = EventParser(summary_file, output_path)
  115. eventparser.parse()
  116. except Exception as ex:
  117. parse_summary_logger.error("Parse summary file failed, detail: %r.", str(ex))
  118. raise UnknownError(str(ex))
  119. @staticmethod
  120. def _check_filepath(filepath):
  121. """
  122. Check file path existence, accessible and available
  123. Args:
  124. filepath (str): File path.
  125. """
  126. if not os.path.isfile(filepath):
  127. parse_summary_logger.error('Summary file %s is not a valid file.', filepath)
  128. return False
  129. if not os.access(filepath, os.R_OK):
  130. parse_summary_logger.error('Path %s is not accessible, please check the file-authority.', filepath)
  131. return False
  132. return True
  133. @staticmethod
  134. def _check_dirpath(filepath):
  135. """
  136. Check file path existence, accessible and available
  137. Args:
  138. filepath (str): File path.
  139. """
  140. if os.path.exists(filepath):
  141. if not os.path.isdir(filepath):
  142. parse_summary_logger.error('Summary directory %s is not a valid directory.', filepath)
  143. return False
  144. if not os.access(filepath, os.R_OK | os.X_OK):
  145. parse_summary_logger.error('Path %s is not accessible, please check the file-authority.', filepath)
  146. return False
  147. return True
  148. parse_summary_logger.error('Summary directory %s not exists.', filepath)
  149. return False
  150. @staticmethod
  151. def _check_create_filepath(filepath):
  152. """
  153. Check file path existence, accessible and available, if not exist create the file
  154. Args:
  155. filepath (str): File path.
  156. """
  157. permissions = os.R_OK | os.W_OK | os.X_OK
  158. os.umask(permissions << 3 | permissions)
  159. if os.path.exists(filepath):
  160. parse_summary_logger.error('Path %s has already existed, please choose a new output path.', filepath)
  161. return False
  162. mode = permissions << 6
  163. os.makedirs(filepath, mode=mode)
  164. return True