mirror of https://github.com/JDAI-CV/fast-reid.git
75 lines
1.7 KiB
Python
75 lines
1.7 KiB
Python
# encoding: utf-8
|
|
"""
|
|
@author: liaoxingyu
|
|
@contact: xyliao1993@qq.com
|
|
"""
|
|
|
|
from __future__ import absolute_import
|
|
from __future__ import division
|
|
from __future__ import print_function
|
|
from __future__ import unicode_literals
|
|
|
|
import errno
|
|
import os
|
|
import shutil
|
|
import sys
|
|
|
|
import os.path as osp
|
|
import torch
|
|
|
|
|
|
class Logger(object):
|
|
"""
|
|
Write console output to external text file.
|
|
Code imported from https://github.com/Cysu/open-reid/blob/master/reid/utils/logging.py.
|
|
"""
|
|
|
|
def __init__(self, fpath=None):
|
|
self.console = sys.stdout
|
|
self.file = None
|
|
if fpath is not None:
|
|
mkdir_if_missing(os.path.dirname(fpath))
|
|
self.file = open(fpath, 'w')
|
|
|
|
def __del__(self):
|
|
self.close()
|
|
|
|
def __enter__(self):
|
|
pass
|
|
|
|
def __exit__(self, *args):
|
|
self.close()
|
|
|
|
def write(self, msg):
|
|
self.console.write(msg)
|
|
if self.file is not None:
|
|
self.file.write(msg)
|
|
|
|
def flush(self):
|
|
self.console.flush()
|
|
if self.file is not None:
|
|
self.file.flush()
|
|
os.fsync(self.file.fileno())
|
|
|
|
def close(self):
|
|
self.console.close()
|
|
if self.file is not None:
|
|
self.file.close()
|
|
|
|
|
|
def mkdir_if_missing(dir_path):
|
|
try:
|
|
os.makedirs(dir_path)
|
|
except OSError as e:
|
|
if e.errno != errno.EEXIST:
|
|
raise
|
|
|
|
|
|
def save_checkpoint(state, is_best, save_dir, filename='checkpoint.pth.tar'):
|
|
fpath = '_'.join((str(state['epoch']), filename))
|
|
fpath = osp.join(save_dir, fpath)
|
|
mkdir_if_missing(save_dir)
|
|
torch.save(state, fpath)
|
|
if is_best:
|
|
shutil.copy(fpath, osp.join(save_dir, 'model_best.pth.tar'))
|