reader.py 12.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 VisualDL Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =======================================================================
走神的阿圆's avatar
走神的阿圆 已提交
15
import collections
走神的阿圆's avatar
走神的阿圆 已提交
16
from functools import partial  # noqa: F401
17

18
from visualdl.component import components
19 20
from visualdl.io import bfile
from visualdl.proto import record_pb2
21 22
from visualdl.reader.record_reader import RecordReader
from visualdl.server.data_manager import default_data_manager
23 24
from visualdl.utils.string_util import decode_tag
from visualdl.utils.string_util import encode_tag
25 26


27
def is_VDLRecord_file(path, check=False):
28 29 30 31 32 33
    """Determine whether it is a VDL log file according to the file name.

    File name of a VDL log file must contain `vdlrecords`.

    Args:
        path: File name to determine.
34
        check: Check file is valid or not.
35 36 37 38

    Returns:
        True if the file is a VDL log file, otherwise false.
    """
P
Peter Pan 已提交
39
    if "vdlrecords" not in path:
40 41 42 43 44 45 46 47 48
        return False
    if check:
        _reader = RecordReader(filepath=path)
        meta_data = _reader.get_next()
        record = record_pb2.Record()
        record.ParseFromString(meta_data)
        if 'meta_data_tag' != record.values[0].tag:
            return False
    return True
49 50 51 52 53 54 55


class LogReader(object):
    """Log reader to read vdl log, support for frontend api in lib.py.

    """

56
    def __init__(self, logdir='', file_path=''):
57 58 59 60 61
        """Instance of LogReader

        Args:
            logdir: The dir include vdl log files, multiple subfolders allowed.
        """
62 63 64 65 66
        if isinstance(logdir, str):
            self.dir = [logdir]
        else:
            self.dir = logdir

67 68 69 70
        self.reader = None
        self.readers = {}
        self.walks = None
        self._tags = {}
走神的阿圆's avatar
走神的阿圆 已提交
71 72
        self.name2tags = {}
        self.tags2name = {}
73 74 75

        self.file_readers = {}

走神的阿圆's avatar
走神的阿圆 已提交
76
        # {'run': {'scalar': {'tag1': data, 'tag2': data}}}
P
Peter Pan 已提交
77
        self._log_datas = collections.defaultdict(
78 79
            lambda: collections.defaultdict(lambda: collections.defaultdict(
                list)))
走神的阿圆's avatar
走神的阿圆 已提交
80

81
        if file_path:
82 83
            self._log_data = collections.defaultdict(lambda: collections.
                                                     defaultdict(list))
84
            self.get_file_reader(file_path=file_path)
走神的阿圆's avatar
走神的阿圆 已提交
85 86 87 88 89 90 91 92 93 94 95
            remain = self.get_remain()
            self.read_log_data(remain=remain)
            components_name = components.keys()
            for name in components_name:
                exec("self.get_%s=partial(self.get_data, '%s')" % (name, name))
        elif logdir:
            self.data_manager = default_data_manager
            self.load_new_data(update=True)
            self._a_tags = {}

            self._model = ""
走神的阿圆's avatar
走神的阿圆 已提交
96

97 98 99 100 101 102
    @property
    def model(self):
        return self._model

    @model.setter
    def model(self, model_path):
走神的阿圆's avatar
走神的阿圆 已提交
103 104 105
        self._model = model_path
        with bfile.BFile(model_path, 'rb') as bfp:
            if not bfp.isfile(model_path):
106 107 108
                print(
                    "Model path %s should be file path, please check this path."
                    % model_path)
109
            else:
走神的阿圆's avatar
走神的阿圆 已提交
110 111 112
                if bfile.exists(model_path):
                    self._model = model_path
                else:
113 114
                    print("Model path %s is invalid, please check this path." %
                          model_path)
115

116 117 118 119
    @property
    def logdir(self):
        return self.dir

走神的阿圆's avatar
走神的阿圆 已提交
120 121 122 123 124 125
    def parsing_from_proto(self, component, proto_datas):
        data = []
        if 'scalar' == component:
            for item in proto_datas:
                data.append([item.id, item.tag, item.timestamp, item.value])
            return data
C
chenjian 已提交
126 127 128 129 130 131 132
        elif 'scalars' == component:
            for item in proto_datas:
                data.append([
                    item.id, item.tag, item.tag_value.tag, item.timestamp,
                    item.tag_value.value
                ])
            return data
走神的阿圆's avatar
走神的阿圆 已提交
133 134
        return proto_datas

走神的阿圆's avatar
走神的阿圆 已提交
135 136 137 138
    def _get_log_tags(self):
        component_keys = self._log_data.keys()
        log_tags = {}
        for key in component_keys:
走神的阿圆's avatar
走神的阿圆 已提交
139 140 141 142
            _tags = list(self._log_data[key].keys())
            tags = list(map(lambda x: encode_tag(x), _tags))
            log_tags[key] = tags

走神的阿圆's avatar
走神的阿圆 已提交
143 144
        return log_tags

走神的阿圆's avatar
走神的阿圆 已提交
145
    def get_log_data(self, component, run, tag):
146 147 148
        if (run in self._log_datas.keys()
                and component in self._log_datas[run].keys()
                and tag in self._log_datas[run][component].keys()):
走神的阿圆's avatar
走神的阿圆 已提交
149 150 151 152
            return self._log_datas[run][component][tag]
        else:
            file_path = bfile.join(run, self.walks[run])
            reader = self._get_file_reader(file_path=file_path, update=False)
C
chenjian 已提交
153 154
            reader.dir = run
            self.reader = reader
走神的阿圆's avatar
走神的阿圆 已提交
155
            remain = self.get_remain(reader=reader)
156 157
            data = self.read_log_data(
                remain=remain, update=False)[component][tag]
走神的阿圆's avatar
走神的阿圆 已提交
158 159 160 161
            data = self.parsing_from_proto(component, data)
            self._log_datas[run][component][tag] = data
            return data

走神的阿圆's avatar
走神的阿圆 已提交
162 163 164 165
    def get_tags(self):
        return self._get_log_tags()

    def get_data(self, component, tag):
走神的阿圆's avatar
走神的阿圆 已提交
166
        return self._log_data[component][decode_tag(tag)]
走神的阿圆's avatar
走神的阿圆 已提交
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    def parse_from_bin(self, record_bin):
        """Register to self._tags by component type.

        Args:
            record_bin: Binary data from vdl log file.
        """
        record = record_pb2.Record()
        record.ParseFromString(record_bin)
        value = record.values[0]
        tag = decode_tag(value.tag)
        path = bfile.join(self.reader.dir, tag)

        if path not in self._tags.keys():
            value_type = value.WhichOneof("one_value")
            if "value" == value_type:
                component = "scalar"
            elif "image" == value_type:
                component = "image"
            elif "embeddings" == value_type:
                component = "embeddings"
            elif "audio" == value_type:
                component = "audio"
190 191
            elif "histogram" == value_type:
                component = "histogram"
走神的阿圆's avatar
走神的阿圆 已提交
192 193
            elif "pr_curve" == value_type:
                component = "pr_curve"
P
Peter Pan 已提交
194 195
            elif "roc_curve" == value_type:
                component = "roc_curve"
走神的阿圆's avatar
走神的阿圆 已提交
196 197 198
            elif "meta_data" == value_type:
                self.update_meta_data(record)
                component = "meta_data"
走神的阿圆's avatar
走神的阿圆 已提交
199 200
            elif "text" == value_type:
                component = "text"
走神的阿圆's avatar
走神的阿圆 已提交
201 202
            elif "hparam" == value_type:
                component = "hyper_parameters"
C
chenjian 已提交
203 204
            elif "tag_value" == value_type:
                component = "scalars"
205 206 207 208 209 210
            else:
                raise TypeError("Invalid value type `%s`." % value_type)
            self._tags[path] = component

        return self._tags[path], self.reader.dir, tag, value

走神的阿圆's avatar
走神的阿圆 已提交
211 212 213 214 215 216
    def update_meta_data(self, record):
        meta = record.values[0].meta_data
        if meta.display_name:
            self.name2tags[meta.display_name] = self.reader.dir
            self.tags2name[self.reader.dir] = meta.display_name

217 218
    def get_all_walk(self):
        self.walks = {}
219 220 221
        for dir in self.dir:
            for root, dirs, files in bfile.walk(dir):
                self.walks.update({root: files})
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

    def logs(self, update=False):
        """Get logs.

        Every dir(means `run` in vdl) has only one log(meads `actual log file`).

        Returns:
            walks: A dict like {"exp1": "vdlrecords.1587375595.log",
                                "exp2": "vdlrecords.1587375685.log"}
        """
        if self.walks is None or update is True:
            self.get_all_walk()

            walks_temp = {}
            for run, tags in self.walks.items():
                tags_temp = [tag for tag in tags if is_VDLRecord_file(tag)]
                tags_temp.sort(reverse=True)
                if len(tags_temp) > 0:
                    walks_temp.update({run: tags_temp[0]})
            self.walks = walks_temp
        return self.walks

    def get_log_reader(self, dir, log):
        """Get log reader for every vdl log file.

        Get instance of class RecordReader base on BFile. Note that each
        `log` may contain multi `tag`.

        Args:
            dir: Dir name of log.
            log: Vdl log file name.
        """
        if self.walks is None:
            self.logs()
        if self.walks.get(dir, None) != log:
            raise FileNotFoundError("Can't find file %s.", (dir + "/" + log))

        filepath = bfile.join(dir, log)
        if filepath not in self.readers.keys():
走神的阿圆's avatar
走神的阿圆 已提交
261
            self.register_reader(filepath, dir)
262 263 264
        self.reader = self.readers[filepath]
        return self.reader

265
    def get_file_reader(self, file_path):
走神的阿圆's avatar
走神的阿圆 已提交
266 267 268 269 270
        """Get file reader for specified vdl log file.

        Get instance of class RecordReader base on BFile.

        Args:
271
            file_path: Vdl log file path.
走神的阿圆's avatar
走神的阿圆 已提交
272
        """
走神的阿圆's avatar
走神的阿圆 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        return self._get_file_reader(file_path, True)

    def _get_file_reader(self, file_path, update=True):
        if update:
            self.register_reader(file_path)
            self.reader = self.readers[file_path]
            return self.reader
        else:
            reader = RecordReader(filepath=file_path)
            return reader

    def register_reader(self, path, dir=None, update=True):
        if update:
            if path not in list(self.readers.keys()):
                reader = RecordReader(filepath=path, dir=dir)
C
chenjian 已提交
288
                reader.dir = dir
走神的阿圆's avatar
走神的阿圆 已提交
289 290 291
                self.readers[path] = reader
        else:
            pass
292 293 294 295 296 297 298 299 300 301

    def register_readers(self, update=False):
        """Register all readers for all vdl log files.

        Args:
            update: Need update if `update` is True.
        """
        self.logs(update)
        for dir, path in self.walks.items():
            filepath = bfile.join(dir, path)
走神的阿圆's avatar
走神的阿圆 已提交
302
            self.register_reader(filepath, dir)
303 304 305 306 307 308 309 310 311 312 313 314

    def add_remain(self):
        """Add remain data to data_manager.

        Add remain data to data manager according its component type and tag
        one by one.
        """
        for reader in self.readers.values():
            self.reader = reader
            remain = self.reader.get_remain()
            for item in remain:
                component, dir, tag, record = self.parse_from_bin(item)
走神的阿圆's avatar
走神的阿圆 已提交
315

316 317 318
                self.data_manager.add_item(component, self.reader.dir, tag,
                                           record)

走神的阿圆's avatar
走神的阿圆 已提交
319
    def get_remain(self, reader=None):
320 321
        """Get all remain data by self.reader.
        """
走神的阿圆's avatar
走神的阿圆 已提交
322
        if self.reader is None and reader is None:
323
            raise RuntimeError("Please specify log path!")
324 325
        return self.reader.get_remain(
        ) if reader is None else reader.get_remain()
326

走神的阿圆's avatar
走神的阿圆 已提交
327
    def read_log_data(self, remain, update=True):
走神的阿圆's avatar
走神的阿圆 已提交
328 329 330 331 332
        """Parse data from log file without sampling.

        Args:
            remain: Raw data from log file.
        """
333 334
        _log_data = collections.defaultdict(lambda: collections.defaultdict(
            list))
走神的阿圆's avatar
走神的阿圆 已提交
335 336
        for item in remain:
            component, dir, tag, record = self.parse_from_bin(item)
走神的阿圆's avatar
走神的阿圆 已提交
337 338 339 340
            _log_data[component][tag].append(record)
        if update:
            self._log_data = _log_data
        return _log_data
走神的阿圆's avatar
走神的阿圆 已提交
341 342 343 344 345

    @property
    def log_data(self):
        return self._log_data

346 347 348 349 350 351 352 353 354
    def runs(self, update=True):
        self.logs(update=update)
        return list(self.walks.keys())

    def tags(self):
        if self._tags is None:
            self.add_remain()
        return self._tags

355
    def components(self, update=False):
356 357
        """Get components type used by vdl.
        """
358 359
        if self.logdir is None:
            return set()
360 361
        if update is True:
            self.load_new_data(update=update)
362
        components_set = set(self._tags.values())
363

364
        return components_set
365

366 367 368 369 370 371 372 373 374 375 376 377 378 379
    def component_tabs(self, update=False):
        """Get component tabs used by vdl frontend.
        """
        component_tabs = set()
        if not self.logdir:
            return component_tabs
        if update is True:
            self.load_new_data(update=update)
        for component in set(self._tags.values()):
            if component == 'meta_data':
                continue
            component_tabs.add(component)
        return component_tabs

380 381 382 383 384 385
    def load_new_data(self, update=True):
        """Load remain data.

        Make sure all readers for every vdl log file are registered, load all
        remain data.
        """
386 387 388
        if self.logdir is not None:
            self.register_readers(update=update)
            self.add_remain()
走神的阿圆's avatar
走神的阿圆 已提交
389 390 391 392 393 394

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass