code
stringlengths
17
6.64M
def make_vgg_layer(inplanes, planes, num_blocks, dilation=1, with_bn=False, ceil_mode=False): layers = [] for _ in range(num_blocks): layers.append(conv3x3(inplanes, planes, dilation)) if with_bn: layers.append(nn.BatchNorm2d(planes)) layers.append(nn.ReLU(inplace=True)) ...
class VGG(nn.Module): 'VGG backbone.\n\n Args:\n depth (int): Depth of vgg, from {11, 13, 16, 19}.\n with_bn (bool): Use BatchNorm or not.\n num_classes (int): number of classes for classification.\n num_stages (int): VGG stages, normally 5.\n dilations (Sequence[int]): Dilat...
def constant_init(module, val, bias=0): if (hasattr(module, 'weight') and (module.weight is not None)): nn.init.constant_(module.weight, val) if (hasattr(module, 'bias') and (module.bias is not None)): nn.init.constant_(module.bias, bias)
def xavier_init(module, gain=1, bias=0, distribution='normal'): assert (distribution in ['uniform', 'normal']) if (distribution == 'uniform'): nn.init.xavier_uniform_(module.weight, gain=gain) else: nn.init.xavier_normal_(module.weight, gain=gain) if (hasattr(module, 'bias') and (modul...
def normal_init(module, mean=0, std=1, bias=0): nn.init.normal_(module.weight, mean, std) if (hasattr(module, 'bias') and (module.bias is not None)): nn.init.constant_(module.bias, bias)
def uniform_init(module, a=0, b=1, bias=0): nn.init.uniform_(module.weight, a, b) if (hasattr(module, 'bias') and (module.bias is not None)): nn.init.constant_(module.bias, bias)
def kaiming_init(module, a=0, mode='fan_out', nonlinearity='relu', bias=0, distribution='normal'): assert (distribution in ['uniform', 'normal']) if (distribution == 'uniform'): nn.init.kaiming_uniform_(module.weight, a=a, mode=mode, nonlinearity=nonlinearity) else: nn.init.kaiming_normal_...
def caffe2_xavier_init(module, bias=0): kaiming_init(module, a=1, mode='fan_in', nonlinearity='leaky_relu', distribution='uniform')
def bias_init_with_prob(prior_prob): ' initialize conv/fc bias value according to giving probablity' bias_init = float((- np.log(((1 - prior_prob) / prior_prob)))) return bias_init
class BaseFileHandler(metaclass=ABCMeta): @abstractmethod def load_from_fileobj(self, file, **kwargs): pass @abstractmethod def dump_to_fileobj(self, obj, file, **kwargs): pass @abstractmethod def dump_to_str(self, obj, **kwargs): pass def load_from_path(self, f...
class JsonHandler(BaseFileHandler): def load_from_fileobj(self, file): return json.load(file) def dump_to_fileobj(self, obj, file, **kwargs): json.dump(obj, file, **kwargs) def dump_to_str(self, obj, **kwargs): return json.dumps(obj, **kwargs)
class PickleHandler(BaseFileHandler): def load_from_fileobj(self, file, **kwargs): return pickle.load(file, **kwargs) def load_from_path(self, filepath, **kwargs): return super(PickleHandler, self).load_from_path(filepath, mode='rb', **kwargs) def dump_to_str(self, obj, **kwargs): ...
class YamlHandler(BaseFileHandler): def load_from_fileobj(self, file, **kwargs): kwargs.setdefault('Loader', Loader) return yaml.load(file, **kwargs) def dump_to_fileobj(self, obj, file, **kwargs): kwargs.setdefault('Dumper', Dumper) yaml.dump(obj, file, **kwargs) def du...
def load(file, file_format=None, **kwargs): 'Load data from json/yaml/pickle files.\n\n This method provides a unified api for loading data from serialized files.\n\n Args:\n file (str or :obj:`Path` or file-like object): Filename or a file-like\n object.\n file_format (str, optiona...
def dump(obj, file=None, file_format=None, **kwargs): 'Dump data to json/yaml/pickle strings or files.\n\n This method provides a unified api for dumping data as strings or to files,\n and also supports custom arguments for each file format.\n\n Args:\n obj (any): The python object to be dumped.\n...
def _register_handler(handler, file_formats): 'Register a handler for some file extensions.\n\n Args:\n handler (:obj:`BaseFileHandler`): Handler to be registered.\n file_formats (str or list[str]): File formats to be handled by this\n handler.\n ' if (not isinstance(handler, Ba...
def register_handler(file_formats, **kwargs): def wrap(cls): _register_handler(cls(**kwargs), file_formats) return cls return wrap
def list_from_file(filename, prefix='', offset=0, max_num=0): 'Load a text file and parse the content as a list of strings.\n\n Args:\n filename (str): Filename.\n prefix (str): The prefix to be inserted to the begining of each item.\n offset (int): The offset of lines.\n max_num (i...
def dict_from_file(filename, key_type=str): "Load a text file and parse the content as a dict.\n\n Each line of the text file will be two or more columns splited by\n whitespaces or tabs. The first column will be parsed as dict keys, and\n the following columns will be parsed as dict values.\n\n Args:...
def solarize(img, thr=128): 'Solarize an image (invert all pixel values above a threshold)\n\n Args:\n img (ndarray): Image to be solarized.\n thr (int): Threshold for solarizing (0 - 255).\n\n Returns:\n ndarray: The solarized image.\n ' img = np.where((img < thr), img, (255 - i...
def posterize(img, bits): 'Posterize an image (reduce the number of bits for each color channel)\n\n Args:\n img (ndarray): Image to be posterized.\n bits (int): Number of bits (1 to 8) to use for posterizing.\n\n Returns:\n ndarray: The posterized image.\n ' shift = (8 - bits) ...
def iminvert(img): 'Invert (negate) an image\n Args:\n img (ndarray): Image to be inverted.\n\n Returns:\n ndarray: The inverted image.\n ' return (np.full_like(img, 255) - img)
def bgr2gray(img, keepdim=False): 'Convert a BGR image to grayscale image.\n\n Args:\n img (ndarray): The input image.\n keepdim (bool): If False (by default), then return the grayscale image\n with 2 dims, otherwise 3 dims.\n\n Returns:\n ndarray: The converted grayscale ima...
def rgb2gray(img, keepdim=False): 'Convert a RGB image to grayscale image.\n\n Args:\n img (ndarray): The input image.\n keepdim (bool): If False (by default), then return the grayscale image\n with 2 dims, otherwise 3 dims.\n\n Returns:\n ndarray: The converted grayscale ima...
def gray2bgr(img): 'Convert a grayscale image to BGR image.\n\n Args:\n img (ndarray): The input image.\n\n Returns:\n ndarray: The converted BGR image.\n ' img = (img[(..., None)] if (img.ndim == 2) else img) out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
def gray2rgb(img): 'Convert a grayscale image to RGB image.\n\n Args:\n img (ndarray): The input image.\n\n Returns:\n ndarray: The converted BGR image.\n ' img = (img[(..., None)] if (img.ndim == 2) else img) out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) return out_img
def convert_color_factory(src, dst): code = getattr(cv2, 'COLOR_{}2{}'.format(src.upper(), dst.upper())) def convert_color(img): out_img = cv2.cvtColor(img, code) return out_img convert_color.__doc__ = 'Convert a {0} image to {1} image.\n\n Args:\n img (ndarray or str): The inpu...
def imnormalize(img, mean, std, to_rgb=True): 'Normalize an image with mean and std.\n\n Args:\n img (ndarray): Image to be normalized.\n mean (ndarray): The mean to be used for normalize.\n std (ndarray): The std to be used for normalize.\n to_rgb (bool): Whether to convert to rgb....
def imnormalize_(img, mean, std, to_rgb=True): 'Inplace normalize an image with mean and std.\n\n Args:\n img (ndarray): Image to be normalized.\n mean (ndarray): The mean to be used for normalize.\n std (ndarray): The std to be used for normalize.\n to_rgb (bool): Whether to conver...
def imdenormalize(img, mean, std, to_bgr=True): assert (img.dtype != np.uint8) mean = mean.reshape(1, (- 1)).astype(np.float64) std = std.reshape(1, (- 1)).astype(np.float64) img = cv2.multiply(img, std) cv2.add(img, mean, img) if to_bgr: cv2.cvtColor(img, cv2.COLOR_RGB2BGR, img) r...
def _scale_size(size, scale): 'Rescale a size by a ratio.\n\n Args:\n size (tuple): w, h.\n scale (float): Scaling factor.\n\n Returns:\n tuple[int]: scaled size.\n ' (w, h) = size return (int(((w * float(scale)) + 0.5)), int(((h * float(scale)) + 0.5)))
def imresize(img, size, return_scale=False, interpolation='bilinear', out=None): 'Resize image to a given size.\n\n Args:\n img (ndarray): The input image.\n size (tuple): Target (w, h).\n return_scale (bool): Whether to return `w_scale` and `h_scale`.\n interpolation (str): Interpo...
def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'): 'Resize image to the same size of a given image.\n\n Args:\n img (ndarray): The input image.\n dst_img (ndarray): The target image.\n return_scale (bool): Whether to return `w_scale` and `h_scale`.\n inte...
def rescale_size(old_size, scale, return_scale=False): 'Calculate the new size to be rescaled to.\n\n Args:\n old_size (tuple[int]): The old size of image.\n scale (float or tuple[int]): The scaling factor or maximum size.\n If it is a float number, then the image will be rescaled by t...
def imrescale(img, scale, return_scale=False, interpolation='bilinear'): 'Resize image while keeping the aspect ratio.\n\n Args:\n img (ndarray): The input image.\n scale (float or tuple[int]): The scaling factor or maximum size.\n If it is a float number, then the image will be rescal...
def scatter(input, devices, streams=None): 'Scatters tensor across multiple GPUs.\n ' if (streams is None): streams = ([None] * len(devices)) if isinstance(input, list): chunk_size = (((len(input) - 1) // len(devices)) + 1) outputs = [scatter(input[i], [devices[(i // chunk_size)...
def synchronize_stream(output, devices, streams): if isinstance(output, list): chunk_size = (len(output) // len(devices)) for i in range(len(devices)): for j in range(chunk_size): synchronize_stream(output[((i * chunk_size) + j)], [devices[i]], [streams[i]]) elif is...
def get_input_device(input): if isinstance(input, list): for item in input: input_device = get_input_device(item) if (input_device != (- 1)): return input_device return (- 1) elif isinstance(input, torch.Tensor): return (input.get_device() if inp...
class Scatter(object): @staticmethod def forward(target_gpus, input): input_device = get_input_device(input) streams = None if (input_device == (- 1)): streams = [_get_stream(device) for device in target_gpus] outputs = scatter(input, target_gpus, streams) ...
def collate(batch, samples_per_gpu=1): 'Puts each data field into a tensor/DataContainer with outer dimension\n batch size.\n\n Extend default_collate to add support for\n :type:`~mmcv.parallel.DataContainer`. There are 3 cases.\n\n 1. cpu_only = True, e.g., meta data\n 2. cpu_only = False, stack =...
def assert_tensor_type(func): @functools.wraps(func) def wrapper(*args, **kwargs): if (not isinstance(args[0].data, torch.Tensor)): raise AttributeError('{} has no attribute {} for type {}'.format(args[0].__class__.__name__, func.__name__, args[0].datatype)) return func(*args, **k...
class DataContainer(object): 'A container for any type of objects.\n\n Typically tensors will be stacked in the collate function and sliced along\n some dimension in the scatter function. This behavior has some limitations.\n 1. All tensors have to be the same size.\n 2. Types are limited (numpy array...
class MMDataParallel(DataParallel): def scatter(self, inputs, kwargs, device_ids): return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
class MMDistributedDataParallel(DistributedDataParallel): def scatter(self, inputs, kwargs, device_ids): return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
class MMDistributedDataParallel(nn.Module): def __init__(self, module, dim=0, broadcast_buffers=True, bucket_cap_mb=25): super(MMDistributedDataParallel, self).__init__() self.module = module self.dim = dim self.broadcast_buffers = broadcast_buffers self.broadcast_bucket_s...
def scatter(inputs, target_gpus, dim=0): 'Scatter inputs to target gpus.\n\n The only difference from original :func:`scatter` is to add support for\n :type:`~mmcv.parallel.DataContainer`.\n ' def scatter_map(obj): if isinstance(obj, torch.Tensor): return OrigScatter.apply(target...
def scatter_kwargs(inputs, kwargs, target_gpus, dim=0): 'Scatter with support for kwargs dictionary' inputs = (scatter(inputs, target_gpus, dim) if inputs else []) kwargs = (scatter(kwargs, target_gpus, dim) if kwargs else []) if (len(inputs) < len(kwargs)): inputs.extend([() for _ in range((l...
def load_state_dict(module, state_dict, strict=False, logger=None): "Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n ...
def load_url_dist(url): ' In distributed setting, this function only download checkpoint at\n local rank 0 ' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): checkpoint = model_zoo.load_url(url) if (world_size > 1): torch.distri...
def get_torchvision_models(): model_urls = dict() for (_, name, ispkg) in pkgutil.walk_packages(torchvision.models.__path__): if ispkg: continue _zoo = import_module('torchvision.models.{}'.format(name)) if hasattr(_zoo, 'model_urls'): _urls = getattr(_zoo, 'mod...
def _load_checkpoint(filename, map_location=None): 'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Either a filepath or URI.\n map_location (str | None): Same as :func:`torch.load`. Default: None.\n\n Returns:\n dict | OrderedDict: The loaded checkpoin...
def load_checkpoint(model, filename, map_location=None, strict=False, logger=None): 'Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Either a filepath or URL or modelzoo://xxxxxxx.\n map_location (str): Same as :func:`torch.load`...
def weights_to_cpu(state_dict): 'Copy a model state_dict to cpu.\n\n Args:\n state_dict (OrderedDict): Model weights on GPU.\n\n Returns:\n OrderedDict: Model weights on GPU.\n ' state_dict_cpu = OrderedDict() for (key, val) in state_dict.items(): state_dict_cpu[key] = val.c...
def save_checkpoint(model, filename, optimizer=None, meta=None): 'Save checkpoint to file.\n\n The checkpoint will have 3 fields: ``meta``, ``state_dict`` and\n ``optimizer``. By default ``meta`` will contain version and time info.\n\n Args:\n model (Module): Module whose params are to be saved.\n...
def init_dist(launcher, backend='nccl', **kwargs): if (mp.get_start_method(allow_none=True) is None): mp.set_start_method('spawn') if (launcher == 'pytorch'): _init_dist_pytorch(backend, **kwargs) elif (launcher == 'mpi'): _init_dist_mpi(backend, **kwargs) elif (launcher == 'sl...
def _init_dist_pytorch(backend, **kwargs): rank = int(os.environ['RANK']) num_gpus = torch.cuda.device_count() torch.cuda.set_device((rank % num_gpus)) dist.init_process_group(backend=backend, **kwargs)
def _init_dist_mpi(backend, **kwargs): raise NotImplementedError
def _init_dist_slurm(backend, port=29500, **kwargs): proc_id = int(os.environ['SLURM_PROCID']) ntasks = int(os.environ['SLURM_NTASKS']) node_list = os.environ['SLURM_NODELIST'] num_gpus = torch.cuda.device_count() torch.cuda.set_device((proc_id % num_gpus)) addr = subprocess.getoutput('scontro...
def get_dist_info(): if (torch.__version__ < '1.0'): initialized = dist._initialized elif dist.is_available(): initialized = dist.is_initialized() else: initialized = False if initialized: rank = dist.get_rank() world_size = dist.get_world_size() else: ...
def master_only(func): @functools.wraps(func) def wrapper(*args, **kwargs): (rank, _) = get_dist_info() if (rank == 0): return func(*args, **kwargs) return wrapper
@HOOKS.register_module class CheckpointHook(Hook): def __init__(self, interval=(- 1), save_optimizer=True, out_dir=None, **kwargs): self.interval = interval self.save_optimizer = save_optimizer self.out_dir = out_dir self.args = kwargs @master_only def after_train_epoch(s...
@HOOKS.register_module class ClosureHook(Hook): def __init__(self, fn_name, fn): assert hasattr(self, fn_name) assert callable(fn) setattr(self, fn_name, fn)
class Hook(object): def before_run(self, runner): pass def after_run(self, runner): pass def before_epoch(self, runner): pass def after_epoch(self, runner): pass def before_iter(self, runner): pass def after_iter(self, runner): pass de...
@HOOKS.register_module class IterTimerHook(Hook): def before_epoch(self, runner): self.t = time.time() def before_iter(self, runner): runner.log_buffer.update({'data_time': (time.time() - self.t)}) def after_iter(self, runner): runner.log_buffer.update({'time': (time.time() - se...
class LoggerHook(Hook): 'Base class for logger hooks.\n\n Args:\n interval (int): Logging interval (every k iterations).\n ignore_last (bool): Ignore the log of last iterations in each epoch\n if less than `interval`.\n reset_flag (bool): Whether to clear the output buffer after...
def is_scalar(val, include_np=True, include_torch=True): 'Tell the input variable is a scalar or not.\n\n Args:\n val: Input variable.\n include_np (bool): Whether include 0-d np.ndarray as a scalar.\n include_torch (bool): Whether include 0-d torch.Tensor as a scalar.\n\n Returns:\n ...
@HOOKS.register_module class PaviLoggerHook(LoggerHook): def __init__(self, init_kwargs=None, add_graph=False, add_last_ckpt=False, interval=10, ignore_last=True, reset_flag=True): super(PaviLoggerHook, self).__init__(interval, ignore_last, reset_flag) self.init_kwargs = init_kwargs self....
@HOOKS.register_module class TensorboardLoggerHook(LoggerHook): def __init__(self, log_dir=None, interval=10, ignore_last=True, reset_flag=True): super(TensorboardLoggerHook, self).__init__(interval, ignore_last, reset_flag) self.log_dir = log_dir @master_only def before_run(self, runner...
@HOOKS.register_module class TextLoggerHook(LoggerHook): def __init__(self, interval=10, ignore_last=True, reset_flag=False): super(TextLoggerHook, self).__init__(interval, ignore_last, reset_flag) self.time_sec_tot = 0 def before_run(self, runner): super(TextLoggerHook, self).before...
@HOOKS.register_module class WandbLoggerHook(LoggerHook): def __init__(self, init_kwargs=None, interval=10, ignore_last=True, reset_flag=True): super(WandbLoggerHook, self).__init__(interval, ignore_last, reset_flag) self.import_wandb() self.init_kwargs = init_kwargs def import_wandb...
class LrUpdaterHook(Hook): "LR Scheduler in MMCV\n\n Args:\n by_epoch (bool): LR changes epoch by epoch\n warmup (string): Type of warmup used. It can be None(use no warmup),\n 'constant', 'linear' or 'exp'\n warmup_iters (int): The number of iterations or epochs that warmup\n ...
@HOOKS.register_module class FixedLrUpdaterHook(LrUpdaterHook): def __init__(self, **kwargs): super(FixedLrUpdaterHook, self).__init__(**kwargs) def get_lr(self, runner, base_lr): return base_lr
@HOOKS.register_module class StepLrUpdaterHook(LrUpdaterHook): def __init__(self, step, gamma=0.1, **kwargs): assert isinstance(step, (list, int)) if isinstance(step, list): for s in step: assert (isinstance(s, int) and (s > 0)) elif isinstance(step, int): ...
@HOOKS.register_module class ExpLrUpdaterHook(LrUpdaterHook): def __init__(self, gamma, **kwargs): self.gamma = gamma super(ExpLrUpdaterHook, self).__init__(**kwargs) def get_lr(self, runner, base_lr): progress = (runner.epoch if self.by_epoch else runner.iter) return (base_l...
@HOOKS.register_module class PolyLrUpdaterHook(LrUpdaterHook): def __init__(self, power=1.0, min_lr=0.0, **kwargs): self.power = power self.min_lr = min_lr super(PolyLrUpdaterHook, self).__init__(**kwargs) def get_lr(self, runner, base_lr): if self.by_epoch: progr...
@HOOKS.register_module class InvLrUpdaterHook(LrUpdaterHook): def __init__(self, gamma, power=1.0, **kwargs): self.gamma = gamma self.power = power super(InvLrUpdaterHook, self).__init__(**kwargs) def get_lr(self, runner, base_lr): progress = (runner.epoch if self.by_epoch el...
@HOOKS.register_module class CosineLrUpdaterHook(LrUpdaterHook): def __init__(self, target_lr=0, **kwargs): self.target_lr = target_lr super(CosineLrUpdaterHook, self).__init__(**kwargs) def get_lr(self, runner, base_lr): if self.by_epoch: progress = runner.epoch ...
@HOOKS.register_module class EmptyCacheHook(Hook): def __init__(self, before_epoch=False, after_epoch=True, after_iter=False): self._before_epoch = before_epoch self._after_epoch = after_epoch self._after_iter = after_iter def after_iter(self, runner): if self._after_iter: ...
@HOOKS.register_module class OptimizerHook(Hook): def __init__(self, grad_clip=None): self.grad_clip = grad_clip def clip_grads(self, params): clip_grad.clip_grad_norm_(filter((lambda p: p.requires_grad), params), **self.grad_clip) def after_train_iter(self, runner): runner.opti...
@HOOKS.register_module class DistSamplerSeedHook(Hook): def before_epoch(self, runner): runner.data_loader.sampler.set_epoch(runner.epoch)
class LogBuffer(object): def __init__(self): self.val_history = OrderedDict() self.n_history = OrderedDict() self.output = OrderedDict() self.ready = False def clear(self): self.val_history.clear() self.n_history.clear() self.clear_output() def cl...
def worker_func(model_cls, model_kwargs, checkpoint, dataset, data_func, gpu_id, idx_queue, result_queue): model = model_cls(**model_kwargs) load_checkpoint(model, checkpoint, map_location='cpu') torch.cuda.set_device(gpu_id) model.cuda() model.eval() with torch.no_grad(): while True: ...
def parallel_test(model_cls, model_kwargs, checkpoint, dataset, data_func, gpus, workers_per_gpu=1): 'Parallel testing on multiple GPUs.\n\n Args:\n model_cls (type): Model class type.\n model_kwargs (dict): Arguments to init the model.\n checkpoint (str): Checkpoint filepath.\n dat...
class Priority(Enum): 'Hook priority levels.\n\n +------------+------------+\n | Level | Value |\n +============+============+\n | HIGHEST | 0 |\n +------------+------------+\n | VERY_HIGH | 10 |\n +------------+------------+\n | HIGH | 30 |\n ...
def get_priority(priority): 'Get priority value.\n\n Args:\n priority (int or str or :obj:`Priority`): Priority.\n\n Returns:\n int: The priority value.\n ' if isinstance(priority, int): if ((priority < 0) or (priority > 100)): raise ValueError('priority must be betw...
class Runner(object): 'A training helper for PyTorch.\n\n Args:\n model (:obj:`torch.nn.Module`): The model to be run.\n batch_processor (callable): A callable method that process a data\n batch. The interface of this method should be\n `batch_processor(model, data, train_mo...
def get_host_info(): return '{}@{}'.format(getuser(), gethostname())
def get_time_str(): return time.strftime('%Y%m%d_%H%M%S', time.localtime())
def obj_from_dict(info, parent=None, default_args=None): 'Initialize an object from dict.\n\n The dict must contain the key "type", which indicates the object type, it\n can be either a string or type, such as "list" or ``list``. Remaining\n fields are treated as the arguments for constructing the object...
class ConfigDict(Dict): def __missing__(self, name): raise KeyError(name) def __getattr__(self, name): try: value = super(ConfigDict, self).__getattr__(name) except KeyError: ex = AttributeError("'{}' object has no attribute '{}'".format(self.__class__.__name_...
def add_args(parser, cfg, prefix=''): for (k, v) in cfg.items(): if isinstance(v, str): parser.add_argument((('--' + prefix) + k)) elif isinstance(v, int): parser.add_argument((('--' + prefix) + k), type=int) elif isinstance(v, float): parser.add_argumen...
class Config(object): 'A facility for config and config files.\n\n It supports common file formats as configs: python/json/yaml. The interface\n is the same as a dict object and also allows access config values as\n attributes.\n\n Example:\n >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))\n ...
def get_logger(name, log_file=None, log_level=logging.INFO): 'Initialize and get a logger by name.\n\n If the logger has not been initialized, this method will initialize the\n logger by adding one or two handlers, otherwise the initialized logger will\n be directly returned. During initialization, a Str...
def print_log(msg, logger=None, level=logging.INFO): 'Print a log message.\n\n Args:\n msg (str): The message to be logged.\n logger (logging.Logger | str | None): The logger to be used.\n Some special loggers are:\n - "silent": no message will be printed.\n - oth...
def is_str(x): 'Whether the input is an string instance.\n\n Note: This method is deprecated since python 2 is no longer supported.\n ' return isinstance(x, str)
def iter_cast(inputs, dst_type, return_type=None): 'Cast elements of an iterable object into some type.\n\n Args:\n inputs (Iterable): The input object.\n dst_type (type): Destination type.\n return_type (type, optional): If specified, the output object will be\n converted to th...
def list_cast(inputs, dst_type): 'Cast elements of an iterable object into a list of some type.\n\n A partial method of :func:`iter_cast`.\n ' return iter_cast(inputs, dst_type, return_type=list)
def tuple_cast(inputs, dst_type): 'Cast elements of an iterable object into a tuple of some type.\n\n A partial method of :func:`iter_cast`.\n ' return iter_cast(inputs, dst_type, return_type=tuple)
def is_seq_of(seq, expected_type, seq_type=None): 'Check whether it is a sequence of some type.\n\n Args:\n seq (Sequence): The sequence to be checked.\n expected_type (type): Expected type of sequence items.\n seq_type (type, optional): Expected sequence type.\n\n Returns:\n boo...
def is_list_of(seq, expected_type): 'Check whether it is a list of some type.\n\n A partial method of :func:`is_seq_of`.\n ' return is_seq_of(seq, expected_type, seq_type=list)