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"""Summary reader.""" 16import struct 17 18import mindspore.train.summary_pb2 as summary_pb2 19 20_HEADER_SIZE = 8 21_HEADER_CRC_SIZE = 4 22_DATA_CRC_SIZE = 4 23 24 25class _EndOfSummaryFileException(Exception): 26 """Indicates the summary file is exhausted.""" 27 28 29class SummaryReader: 30 """ 31 Basic summary read function. 32 33 Args: 34 canonical_file_path (str): The canonical summary file path. 35 ignore_version_event (bool): Whether ignore the version event at the beginning of summary file. 36 """ 37 38 def __init__(self, canonical_file_path, ignore_version_event=True): 39 self._file_path = canonical_file_path 40 self._ignore_version_event = ignore_version_event 41 self._file_handler = None 42 43 def __enter__(self): 44 self._file_handler = open(self._file_path, "rb") 45 if self._ignore_version_event: 46 self.read_event() 47 return self 48 49 def __exit__(self, *unused_args): 50 self._file_handler.close() 51 return False 52 53 def read_event(self): 54 """Read next event.""" 55 file_handler = self._file_handler 56 header = file_handler.read(_HEADER_SIZE) 57 if not header: 58 return None 59 data_len = struct.unpack('Q', header)[0] 60 # Ignore crc check. 61 file_handler.read(_HEADER_CRC_SIZE) 62 63 event_str = file_handler.read(data_len) 64 # Ignore crc check. 65 file_handler.read(_DATA_CRC_SIZE) 66 summary_event = summary_pb2.Event.FromString(event_str) 67 68 return summary_event 69