index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
730,230
mmengine.fileio.backends.petrel_backend
put_text
Write text to a given ``filepath``. Args: obj (str): Data to be written. filepath (str or Path): Path to write data. encoding (str): The encoding format used to encode the ``obj``. Defaults to 'utf-8'. Examples: >>> backend = PetrelBackend() >>> filepath = 'petrel://path/of/file' >>> backend.put_text('hello world', filepath)
def put_text( self, obj: str, filepath: Union[str, Path], encoding: str = 'utf-8', ) -> None: """Write text to a given ``filepath``. Args: obj (str): Data to be written. filepath (str or Path): Path to write data. encoding (str): The encoding format used to encode the ``obj``. Defaults to 'utf-8'. Examples: >>> backend = PetrelBackend() >>> filepath = 'petrel://path/of/file' >>> backend.put_text('hello world', filepath) """ self.put(bytes(obj, encoding=encoding), filepath)
(self, obj: str, filepath: Union[str, pathlib.Path], encoding: str = 'utf-8') -> NoneType
730,231
mmengine.fileio.backends.petrel_backend
remove
Remove a file. Args: filepath (str or Path): Path to be removed. Raises: FileNotFoundError: If filepath does not exist, an FileNotFoundError will be raised. IsADirectoryError: If filepath is a directory, an IsADirectoryError will be raised. Examples: >>> backend = PetrelBackend() >>> filepath = 'petrel://path/of/file' >>> backend.remove(filepath)
def remove(self, filepath: Union[str, Path]) -> None: """Remove a file. Args: filepath (str or Path): Path to be removed. Raises: FileNotFoundError: If filepath does not exist, an FileNotFoundError will be raised. IsADirectoryError: If filepath is a directory, an IsADirectoryError will be raised. Examples: >>> backend = PetrelBackend() >>> filepath = 'petrel://path/of/file' >>> backend.remove(filepath) """ if not has_method(self._client, 'delete'): raise NotImplementedError( 'Current version of Petrel Python SDK has not supported ' 'the `delete` method, please use a higher version or dev ' 'branch instead.') if not self.exists(filepath): raise FileNotFoundError(f'filepath {filepath} does not exist') if self.isdir(filepath): raise IsADirectoryError('filepath should be a file') filepath = self._map_path(filepath) filepath = self._format_path(filepath) filepath = self._replace_prefix(filepath) self._client.delete(filepath)
(self, filepath: Union[str, pathlib.Path]) -> NoneType
730,232
mmengine.fileio.backends.petrel_backend
rmtree
Recursively delete a directory tree. Args: dir_path (str or Path): A directory to be removed. Examples: >>> backend = PetrelBackend() >>> dir_path = 'petrel://path/of/dir' >>> backend.rmtree(dir_path)
def rmtree(self, dir_path: Union[str, Path]) -> None: """Recursively delete a directory tree. Args: dir_path (str or Path): A directory to be removed. Examples: >>> backend = PetrelBackend() >>> dir_path = 'petrel://path/of/dir' >>> backend.rmtree(dir_path) """ for path in self.list_dir_or_file( dir_path, list_dir=False, recursive=True): filepath = self.join_path(dir_path, path) self.remove(filepath)
(self, dir_path: Union[str, pathlib.Path]) -> NoneType
730,233
mmengine.fileio.handlers.pickle_handler
PickleHandler
null
class PickleHandler(BaseFileHandler): str_like = False def load_from_fileobj(self, file, **kwargs): return pickle.load(file, **kwargs) def load_from_path(self, filepath, **kwargs): return super().load_from_path(filepath, mode='rb', **kwargs) def dump_to_str(self, obj, **kwargs): kwargs.setdefault('protocol', 2) return pickle.dumps(obj, **kwargs) def dump_to_fileobj(self, obj, file, **kwargs): kwargs.setdefault('protocol', 2) pickle.dump(obj, file, **kwargs) def dump_to_path(self, obj, filepath, **kwargs): super().dump_to_path(obj, filepath, mode='wb', **kwargs)
()
730,234
mmengine.fileio.handlers.pickle_handler
dump_to_fileobj
null
def dump_to_fileobj(self, obj, file, **kwargs): kwargs.setdefault('protocol', 2) pickle.dump(obj, file, **kwargs)
(self, obj, file, **kwargs)
730,235
mmengine.fileio.handlers.pickle_handler
dump_to_path
null
def dump_to_path(self, obj, filepath, **kwargs): super().dump_to_path(obj, filepath, mode='wb', **kwargs)
(self, obj, filepath, **kwargs)
730,236
mmengine.fileio.handlers.pickle_handler
dump_to_str
null
def dump_to_str(self, obj, **kwargs): kwargs.setdefault('protocol', 2) return pickle.dumps(obj, **kwargs)
(self, obj, **kwargs)
730,237
mmengine.fileio.handlers.pickle_handler
load_from_fileobj
null
def load_from_fileobj(self, file, **kwargs): return pickle.load(file, **kwargs)
(self, file, **kwargs)
730,238
mmengine.fileio.handlers.pickle_handler
load_from_path
null
def load_from_path(self, filepath, **kwargs): return super().load_from_path(filepath, mode='rb', **kwargs)
(self, filepath, **kwargs)
730,239
mmengine.utils.progressbar
ProgressBar
A progress bar which can print the progress. Args: task_num (int): Number of total steps. Defaults to 0. bar_width (int): Width of the progress bar. Defaults to 50. start (bool): Whether to start the progress bar in the constructor. Defaults to True. file (callable): Progress bar output mode. Defaults to "sys.stdout". Examples: >>> import mmengine >>> import time >>> bar = mmengine.ProgressBar(10) >>> for i in range(10): >>> bar.update() >>> time.sleep(1)
class ProgressBar: """A progress bar which can print the progress. Args: task_num (int): Number of total steps. Defaults to 0. bar_width (int): Width of the progress bar. Defaults to 50. start (bool): Whether to start the progress bar in the constructor. Defaults to True. file (callable): Progress bar output mode. Defaults to "sys.stdout". Examples: >>> import mmengine >>> import time >>> bar = mmengine.ProgressBar(10) >>> for i in range(10): >>> bar.update() >>> time.sleep(1) """ def __init__(self, task_num: int = 0, bar_width: int = 50, start: bool = True, file=sys.stdout): self.task_num = task_num self.bar_width = bar_width self.completed = 0 self.file = file if start: self.start() @property def terminal_width(self): width, _ = get_terminal_size() return width def start(self): if self.task_num > 0: self.file.write(f'[{" " * self.bar_width}] 0/{self.task_num}, ' 'elapsed: 0s, ETA:') else: self.file.write('completed: 0, elapsed: 0s') self.file.flush() self.timer = Timer() def update(self, num_tasks: int = 1): """update progressbar. Args: num_tasks (int): Update step size. """ assert num_tasks > 0 self.completed += num_tasks elapsed = self.timer.since_start() if elapsed > 0: fps = self.completed / elapsed else: fps = float('inf') if self.task_num > 0: percentage = self.completed / float(self.task_num) eta = int(elapsed * (1 - percentage) / percentage + 0.5) msg = f'\r[{{}}] {self.completed}/{self.task_num}, ' \ f'{fps:.1f} task/s, elapsed: {int(elapsed + 0.5)}s, ' \ f'ETA: {eta:5}s' bar_width = min(self.bar_width, int(self.terminal_width - len(msg)) + 2, int(self.terminal_width * 0.6)) bar_width = max(2, bar_width) mark_width = int(bar_width * percentage) bar_chars = '>' * mark_width + ' ' * (bar_width - mark_width) self.file.write(msg.format(bar_chars)) else: self.file.write( f'completed: {self.completed}, elapsed: {int(elapsed + 0.5)}s,' f' {fps:.1f} tasks/s') self.file.flush()
(task_num: int = 0, bar_width: int = 50, start: bool = True, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)
730,240
mmengine.utils.progressbar
__init__
null
def __init__(self, task_num: int = 0, bar_width: int = 50, start: bool = True, file=sys.stdout): self.task_num = task_num self.bar_width = bar_width self.completed = 0 self.file = file if start: self.start()
(self, task_num: int = 0, bar_width: int = 50, start: bool = True, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)
730,241
mmengine.utils.progressbar
start
null
def start(self): if self.task_num > 0: self.file.write(f'[{" " * self.bar_width}] 0/{self.task_num}, ' 'elapsed: 0s, ETA:') else: self.file.write('completed: 0, elapsed: 0s') self.file.flush() self.timer = Timer()
(self)
730,242
mmengine.utils.progressbar
update
update progressbar. Args: num_tasks (int): Update step size.
def update(self, num_tasks: int = 1): """update progressbar. Args: num_tasks (int): Update step size. """ assert num_tasks > 0 self.completed += num_tasks elapsed = self.timer.since_start() if elapsed > 0: fps = self.completed / elapsed else: fps = float('inf') if self.task_num > 0: percentage = self.completed / float(self.task_num) eta = int(elapsed * (1 - percentage) / percentage + 0.5) msg = f'\r[{{}}] {self.completed}/{self.task_num}, ' \ f'{fps:.1f} task/s, elapsed: {int(elapsed + 0.5)}s, ' \ f'ETA: {eta:5}s' bar_width = min(self.bar_width, int(self.terminal_width - len(msg)) + 2, int(self.terminal_width * 0.6)) bar_width = max(2, bar_width) mark_width = int(bar_width * percentage) bar_chars = '>' * mark_width + ' ' * (bar_width - mark_width) self.file.write(msg.format(bar_chars)) else: self.file.write( f'completed: {self.completed}, elapsed: {int(elapsed + 0.5)}s,' f' {fps:.1f} tasks/s') self.file.flush()
(self, num_tasks: int = 1)
730,243
mmengine.registry.registry
Registry
A registry to map strings to classes or functions. Registered object could be built from registry. Meanwhile, registered functions could be called from registry. Args: name (str): Registry name. build_func (callable, optional): A function to construct instance from Registry. :func:`build_from_cfg` is used if neither ``parent`` or ``build_func`` is specified. If ``parent`` is specified and ``build_func`` is not given, ``build_func`` will be inherited from ``parent``. Defaults to None. parent (:obj:`Registry`, optional): Parent registry. The class registered in children registry could be built from parent. Defaults to None. scope (str, optional): The scope of registry. It is the key to search for children registry. If not specified, scope will be the name of the package where class is defined, e.g. mmdet, mmcls, mmseg. Defaults to None. locations (list): The locations to import the modules registered in this registry. Defaults to []. New in version 0.4.0. Examples: >>> # define a registry >>> MODELS = Registry('models') >>> # registry the `ResNet` to `MODELS` >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> # build model from `MODELS` >>> resnet = MODELS.build(dict(type='ResNet')) >>> @MODELS.register_module() >>> def resnet50(): >>> pass >>> resnet = MODELS.build(dict(type='resnet50')) >>> # hierarchical registry >>> DETECTORS = Registry('detectors', parent=MODELS, scope='det') >>> @DETECTORS.register_module() >>> class FasterRCNN: >>> pass >>> fasterrcnn = DETECTORS.build(dict(type='FasterRCNN')) >>> # add locations to enable auto import >>> DETECTORS = Registry('detectors', parent=MODELS, >>> scope='det', locations=['det.models.detectors']) >>> # define this class in 'det.models.detectors' >>> @DETECTORS.register_module() >>> class MaskRCNN: >>> pass >>> # The registry will auto import det.models.detectors.MaskRCNN >>> fasterrcnn = DETECTORS.build(dict(type='det.MaskRCNN')) More advanced usages can be found at https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html.
class Registry: """A registry to map strings to classes or functions. Registered object could be built from registry. Meanwhile, registered functions could be called from registry. Args: name (str): Registry name. build_func (callable, optional): A function to construct instance from Registry. :func:`build_from_cfg` is used if neither ``parent`` or ``build_func`` is specified. If ``parent`` is specified and ``build_func`` is not given, ``build_func`` will be inherited from ``parent``. Defaults to None. parent (:obj:`Registry`, optional): Parent registry. The class registered in children registry could be built from parent. Defaults to None. scope (str, optional): The scope of registry. It is the key to search for children registry. If not specified, scope will be the name of the package where class is defined, e.g. mmdet, mmcls, mmseg. Defaults to None. locations (list): The locations to import the modules registered in this registry. Defaults to []. New in version 0.4.0. Examples: >>> # define a registry >>> MODELS = Registry('models') >>> # registry the `ResNet` to `MODELS` >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> # build model from `MODELS` >>> resnet = MODELS.build(dict(type='ResNet')) >>> @MODELS.register_module() >>> def resnet50(): >>> pass >>> resnet = MODELS.build(dict(type='resnet50')) >>> # hierarchical registry >>> DETECTORS = Registry('detectors', parent=MODELS, scope='det') >>> @DETECTORS.register_module() >>> class FasterRCNN: >>> pass >>> fasterrcnn = DETECTORS.build(dict(type='FasterRCNN')) >>> # add locations to enable auto import >>> DETECTORS = Registry('detectors', parent=MODELS, >>> scope='det', locations=['det.models.detectors']) >>> # define this class in 'det.models.detectors' >>> @DETECTORS.register_module() >>> class MaskRCNN: >>> pass >>> # The registry will auto import det.models.detectors.MaskRCNN >>> fasterrcnn = DETECTORS.build(dict(type='det.MaskRCNN')) More advanced usages can be found at https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html. """ def __init__(self, name: str, build_func: Optional[Callable] = None, parent: Optional['Registry'] = None, scope: Optional[str] = None, locations: List = []): from .build_functions import build_from_cfg self._name = name self._module_dict: Dict[str, Type] = dict() self._children: Dict[str, 'Registry'] = dict() self._locations = locations self._imported = False if scope is not None: assert isinstance(scope, str) self._scope = scope else: self._scope = self.infer_scope() # See https://mypy.readthedocs.io/en/stable/common_issues.html# # variables-vs-type-aliases for the use self.parent: Optional['Registry'] if parent is not None: assert isinstance(parent, Registry) parent._add_child(self) self.parent = parent else: self.parent = None # self.build_func will be set with the following priority: # 1. build_func # 2. parent.build_func # 3. build_from_cfg self.build_func: Callable if build_func is None: if self.parent is not None: self.build_func = self.parent.build_func else: self.build_func = build_from_cfg else: self.build_func = build_func def __len__(self): return len(self._module_dict) def __contains__(self, key): return self.get(key) is not None def __repr__(self): table = Table(title=f'Registry of {self._name}') table.add_column('Names', justify='left', style='cyan') table.add_column('Objects', justify='left', style='green') for name, obj in sorted(self._module_dict.items()): table.add_row(name, str(obj)) console = Console() with console.capture() as capture: console.print(table, end='') return capture.get() @staticmethod def infer_scope() -> str: """Infer the scope of registry. The name of the package where registry is defined will be returned. Returns: str: The inferred scope name. Examples: >>> # in mmdet/models/backbone/resnet.py >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> # The scope of ``ResNet`` will be ``mmdet``. """ from ..logging import print_log # `sys._getframe` returns the frame object that many calls below the # top of the stack. The call stack for `infer_scope` can be listed as # follow: # frame-0: `infer_scope` itself # frame-1: `__init__` of `Registry` which calls the `infer_scope` # frame-2: Where the `Registry(...)` is called module = inspect.getmodule(sys._getframe(2)) if module is not None: filename = module.__name__ split_filename = filename.split('.') scope = split_filename[0] else: # use "mmengine" to handle some cases which can not infer the scope # like initializing Registry in interactive mode scope = 'mmengine' print_log( 'set scope as "mmengine" when scope can not be inferred. You ' 'can silence this warning by passing a "scope" argument to ' 'Registry like `Registry(name, scope="toy")`', logger='current', level=logging.WARNING) return scope @staticmethod def split_scope_key(key: str) -> Tuple[Optional[str], str]: """Split scope and key. The first scope will be split from key. Return: tuple[str | None, str]: The former element is the first scope of the key, which can be ``None``. The latter is the remaining key. Examples: >>> Registry.split_scope_key('mmdet.ResNet') 'mmdet', 'ResNet' >>> Registry.split_scope_key('ResNet') None, 'ResNet' """ split_index = key.find('.') if split_index != -1: return key[:split_index], key[split_index + 1:] else: return None, key @property def name(self): return self._name @property def scope(self): return self._scope @property def module_dict(self): return self._module_dict @property def children(self): return self._children @property def root(self): return self._get_root_registry() @contextmanager def switch_scope_and_registry(self, scope: Optional[str]) -> Generator: """Temporarily switch default scope to the target scope, and get the corresponding registry. If the registry of the corresponding scope exists, yield the registry, otherwise yield the current itself. Args: scope (str, optional): The target scope. Examples: >>> from mmengine.registry import Registry, DefaultScope, MODELS >>> import time >>> # External Registry >>> MMDET_MODELS = Registry('mmdet_model', scope='mmdet', >>> parent=MODELS) >>> MMCLS_MODELS = Registry('mmcls_model', scope='mmcls', >>> parent=MODELS) >>> # Local Registry >>> CUSTOM_MODELS = Registry('custom_model', scope='custom', >>> parent=MODELS) >>> >>> # Initiate DefaultScope >>> DefaultScope.get_instance(f'scope_{time.time()}', >>> scope_name='custom') >>> # Check default scope >>> DefaultScope.get_current_instance().scope_name custom >>> # Switch to mmcls scope and get `MMCLS_MODELS` registry. >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as registry: >>> DefaultScope.get_current_instance().scope_name mmcls >>> registry.scope mmcls >>> # Nested switch scope >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmdet') as mmdet_registry: >>> DefaultScope.get_current_instance().scope_name mmdet >>> mmdet_registry.scope mmdet >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as mmcls_registry: >>> DefaultScope.get_current_instance().scope_name mmcls >>> mmcls_registry.scope mmcls >>> >>> # Check switch back to original scope. >>> DefaultScope.get_current_instance().scope_name custom """ # noqa: E501 from ..logging import print_log # Switch to the given scope temporarily. If the corresponding registry # can be found in root registry, return the registry under the scope, # otherwise return the registry itself. with DefaultScope.overwrite_default_scope(scope): # Get the global default scope default_scope = DefaultScope.get_current_instance() # Get registry by scope if default_scope is not None: scope_name = default_scope.scope_name try: import_module(f'{scope_name}.registry') except (ImportError, AttributeError, ModuleNotFoundError): if scope in MODULE2PACKAGE: print_log( f'{scope} is not installed and its ' 'modules will not be registered. If you ' 'want to use modules defined in ' f'{scope}, Please install {scope} by ' f'`pip install {MODULE2PACKAGE[scope]}.', logger='current', level=logging.WARNING) else: print_log( f'Failed to import `{scope}.registry` ' f'make sure the registry.py exists in `{scope}` ' 'package.', logger='current', level=logging.WARNING) root = self._get_root_registry() registry = root._search_child(scope_name) if registry is None: # if `default_scope` can not be found, fallback to argument # `registry` print_log( f'Failed to search registry with scope "{scope_name}" ' f'in the "{root.name}" registry tree. ' f'As a workaround, the current "{self.name}" registry ' f'in "{self.scope}" is used to build instance. This ' 'may cause unexpected failure when running the built ' f'modules. Please check whether "{scope_name}" is a ' 'correct scope, or whether the registry is ' 'initialized.', logger='current', level=logging.WARNING) registry = self # If there is no built default scope, just return current registry. else: registry = self yield registry def _get_root_registry(self) -> 'Registry': """Return the root registry.""" root = self while root.parent is not None: root = root.parent return root def import_from_location(self) -> None: """import modules from the pre-defined locations in self._location.""" if not self._imported: # Avoid circular import from ..logging import print_log # avoid BC breaking if len(self._locations) == 0 and self.scope in MODULE2PACKAGE: print_log( f'The "{self.name}" registry in {self.scope} did not ' 'set import location. Fallback to call ' f'`{self.scope}.utils.register_all_modules` ' 'instead.', logger='current', level=logging.DEBUG) try: module = import_module(f'{self.scope}.utils') except (ImportError, AttributeError, ModuleNotFoundError): if self.scope in MODULE2PACKAGE: print_log( f'{self.scope} is not installed and its ' 'modules will not be registered. If you ' 'want to use modules defined in ' f'{self.scope}, Please install {self.scope} by ' f'`pip install {MODULE2PACKAGE[self.scope]}.', logger='current', level=logging.WARNING) else: print_log( f'Failed to import {self.scope} and register ' 'its modules, please make sure you ' 'have registered the module manually.', logger='current', level=logging.WARNING) else: # The import errors triggered during the registration # may be more complex, here just throwing # the error to avoid causing more implicit registry errors # like `xxx`` not found in `yyy` registry. module.register_all_modules(False) # type: ignore for loc in self._locations: import_module(loc) print_log( f"Modules of {self.scope}'s {self.name} registry have " f'been automatically imported from {loc}', logger='current', level=logging.DEBUG) self._imported = True def get(self, key: str) -> Optional[Type]: """Get the registry record. If `key`` represents the whole object name with its module information, for example, `mmengine.model.BaseModel`, ``get`` will directly return the class object :class:`BaseModel`. Otherwise, it will first parse ``key`` and check whether it contains a scope name. The logic to search for ``key``: - ``key`` does not contain a scope name, i.e., it is purely a module name like "ResNet": :meth:`get` will search for ``ResNet`` from the current registry to its parent or ancestors until finding it. - ``key`` contains a scope name and it is equal to the scope of the current registry (e.g., "mmcls"), e.g., "mmcls.ResNet": :meth:`get` will only search for ``ResNet`` in the current registry. - ``key`` contains a scope name and it is not equal to the scope of the current registry (e.g., "mmdet"), e.g., "mmcls.FCNet": If the scope exists in its children, :meth:`get` will get "FCNet" from them. If not, :meth:`get` will first get the root registry and root registry call its own :meth:`get` method. Args: key (str): Name of the registered item, e.g., the class name in string format. Returns: Type or None: Return the corresponding class if ``key`` exists, otherwise return None. Examples: >>> # define a registry >>> MODELS = Registry('models') >>> # register `ResNet` to `MODELS` >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> resnet_cls = MODELS.get('ResNet') >>> # hierarchical registry >>> DETECTORS = Registry('detector', parent=MODELS, scope='det') >>> # `ResNet` does not exist in `DETECTORS` but `get` method >>> # will try to search from its parents or ancestors >>> resnet_cls = DETECTORS.get('ResNet') >>> CLASSIFIER = Registry('classifier', parent=MODELS, scope='cls') >>> @CLASSIFIER.register_module() >>> class MobileNet: >>> pass >>> # `get` from its sibling registries >>> mobilenet_cls = DETECTORS.get('cls.MobileNet') """ # Avoid circular import from ..logging import print_log if not isinstance(key, str): raise TypeError( 'The key argument of `Registry.get` must be a str, ' f'got {type(key)}') scope, real_key = self.split_scope_key(key) obj_cls = None registry_name = self.name scope_name = self.scope # lazy import the modules to register them into the registry self.import_from_location() if scope is None or scope == self._scope: # get from self if real_key in self._module_dict: obj_cls = self._module_dict[real_key] elif scope is None: # try to get the target from its parent or ancestors parent = self.parent while parent is not None: if real_key in parent._module_dict: obj_cls = parent._module_dict[real_key] registry_name = parent.name scope_name = parent.scope break parent = parent.parent else: # import the registry to add the nodes into the registry tree try: import_module(f'{scope}.registry') print_log( f'Registry node of {scope} has been automatically ' 'imported.', logger='current', level=logging.DEBUG) except (ImportError, AttributeError, ModuleNotFoundError): print_log( f'Cannot auto import {scope}.registry, please check ' f'whether the package "{scope}" is installed correctly ' 'or import the registry manually.', logger='current', level=logging.DEBUG) # get from self._children if scope in self._children: obj_cls = self._children[scope].get(real_key) registry_name = self._children[scope].name scope_name = scope else: root = self._get_root_registry() if scope != root._scope and scope not in root._children: # If not skip directly, `root.get(key)` will recursively # call itself until RecursionError is thrown. pass else: obj_cls = root.get(key) if obj_cls is None: # Actually, it's strange to implement this `try ... except` to # get the object by its name in `Registry.get`. However, If we # want to build the model using a configuration like # `dict(type='mmengine.model.BaseModel')`, which can # be dumped by lazy import config, we need this code snippet # for `Registry.get` to work. try: obj_cls = get_object_from_string(key) except Exception: raise RuntimeError(f'Failed to get {key}') if obj_cls is not None: # For some rare cases (e.g. obj_cls is a partial function), obj_cls # doesn't have `__name__`. Use default value to prevent error cls_name = getattr(obj_cls, '__name__', str(obj_cls)) print_log( f'Get class `{cls_name}` from "{registry_name}"' f' registry in "{scope_name}"', logger='current', level=logging.DEBUG) return obj_cls def _search_child(self, scope: str) -> Optional['Registry']: """Depth-first search for the corresponding registry in its children. Note that the method only search for the corresponding registry from the current registry. Therefore, if we want to search from the root registry, :meth:`_get_root_registry` should be called to get the root registry first. Args: scope (str): The scope name used for searching for its corresponding registry. Returns: Registry or None: Return the corresponding registry if ``scope`` exists, otherwise return None. """ if self._scope == scope: return self for child in self._children.values(): registry = child._search_child(scope) if registry is not None: return registry return None def build(self, cfg: dict, *args, **kwargs) -> Any: """Build an instance. Build an instance by calling :attr:`build_func`. Args: cfg (dict): Config dict needs to be built. Returns: Any: The constructed object. Examples: >>> from mmengine import Registry >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> def __init__(self, depth, stages=4): >>> self.depth = depth >>> self.stages = stages >>> cfg = dict(type='ResNet', depth=50) >>> model = MODELS.build(cfg) """ return self.build_func(cfg, *args, **kwargs, registry=self) def _add_child(self, registry: 'Registry') -> None: """Add a child for a registry. Args: registry (:obj:`Registry`): The ``registry`` will be added as a child of the ``self``. """ assert isinstance(registry, Registry) assert registry.scope is not None assert registry.scope not in self.children, \ f'scope {registry.scope} exists in {self.name} registry' self.children[registry.scope] = registry def _register_module(self, module: Type, module_name: Optional[Union[str, List[str]]] = None, force: bool = False) -> None: """Register a module. Args: module (type): Module to be registered. Typically a class or a function, but generally all ``Callable`` are acceptable. module_name (str or list of str, optional): The module name to be registered. If not specified, the class name will be used. Defaults to None. force (bool): Whether to override an existing class with the same name. Defaults to False. """ if not callable(module): raise TypeError(f'module must be Callable, but got {type(module)}') if module_name is None: module_name = module.__name__ if isinstance(module_name, str): module_name = [module_name] for name in module_name: if not force and name in self._module_dict: existed_module = self.module_dict[name] raise KeyError(f'{name} is already registered in {self.name} ' f'at {existed_module.__module__}') self._module_dict[name] = module def register_module( self, name: Optional[Union[str, List[str]]] = None, force: bool = False, module: Optional[Type] = None) -> Union[type, Callable]: """Register a module. A record will be added to ``self._module_dict``, whose key is the class name or the specified name, and value is the class itself. It can be used as a decorator or a normal function. Args: name (str or list of str, optional): The module name to be registered. If not specified, the class name will be used. force (bool): Whether to override an existing class with the same name. Defaults to False. module (type, optional): Module class or function to be registered. Defaults to None. Examples: >>> backbones = Registry('backbone') >>> # as a decorator >>> @backbones.register_module() >>> class ResNet: >>> pass >>> backbones = Registry('backbone') >>> @backbones.register_module(name='mnet') >>> class MobileNet: >>> pass >>> # as a normal function >>> class ResNet: >>> pass >>> backbones.register_module(module=ResNet) """ if not isinstance(force, bool): raise TypeError(f'force must be a boolean, but got {type(force)}') # raise the error ahead of time if not (name is None or isinstance(name, str) or is_seq_of(name, str)): raise TypeError( 'name must be None, an instance of str, or a sequence of str, ' f'but got {type(name)}') # use it as a normal method: x.register_module(module=SomeClass) if module is not None: self._register_module(module=module, module_name=name, force=force) return module # use it as a decorator: @x.register_module() def _register(module): self._register_module(module=module, module_name=name, force=force) return module return _register
(name: str, build_func: Optional[collections.abc.Callable] = None, parent: Optional[ForwardRef('Registry')] = None, scope: Optional[str] = None, locations: List = [])
730,244
mmengine.registry.registry
__contains__
null
def __contains__(self, key): return self.get(key) is not None
(self, key)
730,245
mmengine.registry.registry
__init__
null
def __init__(self, name: str, build_func: Optional[Callable] = None, parent: Optional['Registry'] = None, scope: Optional[str] = None, locations: List = []): from .build_functions import build_from_cfg self._name = name self._module_dict: Dict[str, Type] = dict() self._children: Dict[str, 'Registry'] = dict() self._locations = locations self._imported = False if scope is not None: assert isinstance(scope, str) self._scope = scope else: self._scope = self.infer_scope() # See https://mypy.readthedocs.io/en/stable/common_issues.html# # variables-vs-type-aliases for the use self.parent: Optional['Registry'] if parent is not None: assert isinstance(parent, Registry) parent._add_child(self) self.parent = parent else: self.parent = None # self.build_func will be set with the following priority: # 1. build_func # 2. parent.build_func # 3. build_from_cfg self.build_func: Callable if build_func is None: if self.parent is not None: self.build_func = self.parent.build_func else: self.build_func = build_from_cfg else: self.build_func = build_func
(self, name: str, build_func: Optional[collections.abc.Callable] = None, parent: Optional[mmengine.registry.registry.Registry] = None, scope: Optional[str] = None, locations: List = [])
730,246
mmengine.registry.registry
__len__
null
def __len__(self): return len(self._module_dict)
(self)
730,247
mmengine.registry.registry
__repr__
null
def __repr__(self): table = Table(title=f'Registry of {self._name}') table.add_column('Names', justify='left', style='cyan') table.add_column('Objects', justify='left', style='green') for name, obj in sorted(self._module_dict.items()): table.add_row(name, str(obj)) console = Console() with console.capture() as capture: console.print(table, end='') return capture.get()
(self)
730,248
mmengine.registry.registry
_add_child
Add a child for a registry. Args: registry (:obj:`Registry`): The ``registry`` will be added as a child of the ``self``.
def _add_child(self, registry: 'Registry') -> None: """Add a child for a registry. Args: registry (:obj:`Registry`): The ``registry`` will be added as a child of the ``self``. """ assert isinstance(registry, Registry) assert registry.scope is not None assert registry.scope not in self.children, \ f'scope {registry.scope} exists in {self.name} registry' self.children[registry.scope] = registry
(self, registry: mmengine.registry.registry.Registry) -> NoneType
730,249
mmengine.registry.registry
_get_root_registry
Return the root registry.
def _get_root_registry(self) -> 'Registry': """Return the root registry.""" root = self while root.parent is not None: root = root.parent return root
(self) -> mmengine.registry.registry.Registry
730,250
mmengine.registry.registry
_register_module
Register a module. Args: module (type): Module to be registered. Typically a class or a function, but generally all ``Callable`` are acceptable. module_name (str or list of str, optional): The module name to be registered. If not specified, the class name will be used. Defaults to None. force (bool): Whether to override an existing class with the same name. Defaults to False.
def _register_module(self, module: Type, module_name: Optional[Union[str, List[str]]] = None, force: bool = False) -> None: """Register a module. Args: module (type): Module to be registered. Typically a class or a function, but generally all ``Callable`` are acceptable. module_name (str or list of str, optional): The module name to be registered. If not specified, the class name will be used. Defaults to None. force (bool): Whether to override an existing class with the same name. Defaults to False. """ if not callable(module): raise TypeError(f'module must be Callable, but got {type(module)}') if module_name is None: module_name = module.__name__ if isinstance(module_name, str): module_name = [module_name] for name in module_name: if not force and name in self._module_dict: existed_module = self.module_dict[name] raise KeyError(f'{name} is already registered in {self.name} ' f'at {existed_module.__module__}') self._module_dict[name] = module
(self, module: Type, module_name: Union[str, List[str], NoneType] = None, force: bool = False) -> NoneType
730,251
mmengine.registry.registry
_search_child
Depth-first search for the corresponding registry in its children. Note that the method only search for the corresponding registry from the current registry. Therefore, if we want to search from the root registry, :meth:`_get_root_registry` should be called to get the root registry first. Args: scope (str): The scope name used for searching for its corresponding registry. Returns: Registry or None: Return the corresponding registry if ``scope`` exists, otherwise return None.
def _search_child(self, scope: str) -> Optional['Registry']: """Depth-first search for the corresponding registry in its children. Note that the method only search for the corresponding registry from the current registry. Therefore, if we want to search from the root registry, :meth:`_get_root_registry` should be called to get the root registry first. Args: scope (str): The scope name used for searching for its corresponding registry. Returns: Registry or None: Return the corresponding registry if ``scope`` exists, otherwise return None. """ if self._scope == scope: return self for child in self._children.values(): registry = child._search_child(scope) if registry is not None: return registry return None
(self, scope: str) -> Optional[mmengine.registry.registry.Registry]
730,252
mmengine.registry.registry
build
Build an instance. Build an instance by calling :attr:`build_func`. Args: cfg (dict): Config dict needs to be built. Returns: Any: The constructed object. Examples: >>> from mmengine import Registry >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> def __init__(self, depth, stages=4): >>> self.depth = depth >>> self.stages = stages >>> cfg = dict(type='ResNet', depth=50) >>> model = MODELS.build(cfg)
def build(self, cfg: dict, *args, **kwargs) -> Any: """Build an instance. Build an instance by calling :attr:`build_func`. Args: cfg (dict): Config dict needs to be built. Returns: Any: The constructed object. Examples: >>> from mmengine import Registry >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> def __init__(self, depth, stages=4): >>> self.depth = depth >>> self.stages = stages >>> cfg = dict(type='ResNet', depth=50) >>> model = MODELS.build(cfg) """ return self.build_func(cfg, *args, **kwargs, registry=self)
(self, cfg: dict, *args, **kwargs) -> Any
730,253
mmengine.registry.registry
get
Get the registry record. If `key`` represents the whole object name with its module information, for example, `mmengine.model.BaseModel`, ``get`` will directly return the class object :class:`BaseModel`. Otherwise, it will first parse ``key`` and check whether it contains a scope name. The logic to search for ``key``: - ``key`` does not contain a scope name, i.e., it is purely a module name like "ResNet": :meth:`get` will search for ``ResNet`` from the current registry to its parent or ancestors until finding it. - ``key`` contains a scope name and it is equal to the scope of the current registry (e.g., "mmcls"), e.g., "mmcls.ResNet": :meth:`get` will only search for ``ResNet`` in the current registry. - ``key`` contains a scope name and it is not equal to the scope of the current registry (e.g., "mmdet"), e.g., "mmcls.FCNet": If the scope exists in its children, :meth:`get` will get "FCNet" from them. If not, :meth:`get` will first get the root registry and root registry call its own :meth:`get` method. Args: key (str): Name of the registered item, e.g., the class name in string format. Returns: Type or None: Return the corresponding class if ``key`` exists, otherwise return None. Examples: >>> # define a registry >>> MODELS = Registry('models') >>> # register `ResNet` to `MODELS` >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> resnet_cls = MODELS.get('ResNet') >>> # hierarchical registry >>> DETECTORS = Registry('detector', parent=MODELS, scope='det') >>> # `ResNet` does not exist in `DETECTORS` but `get` method >>> # will try to search from its parents or ancestors >>> resnet_cls = DETECTORS.get('ResNet') >>> CLASSIFIER = Registry('classifier', parent=MODELS, scope='cls') >>> @CLASSIFIER.register_module() >>> class MobileNet: >>> pass >>> # `get` from its sibling registries >>> mobilenet_cls = DETECTORS.get('cls.MobileNet')
def get(self, key: str) -> Optional[Type]: """Get the registry record. If `key`` represents the whole object name with its module information, for example, `mmengine.model.BaseModel`, ``get`` will directly return the class object :class:`BaseModel`. Otherwise, it will first parse ``key`` and check whether it contains a scope name. The logic to search for ``key``: - ``key`` does not contain a scope name, i.e., it is purely a module name like "ResNet": :meth:`get` will search for ``ResNet`` from the current registry to its parent or ancestors until finding it. - ``key`` contains a scope name and it is equal to the scope of the current registry (e.g., "mmcls"), e.g., "mmcls.ResNet": :meth:`get` will only search for ``ResNet`` in the current registry. - ``key`` contains a scope name and it is not equal to the scope of the current registry (e.g., "mmdet"), e.g., "mmcls.FCNet": If the scope exists in its children, :meth:`get` will get "FCNet" from them. If not, :meth:`get` will first get the root registry and root registry call its own :meth:`get` method. Args: key (str): Name of the registered item, e.g., the class name in string format. Returns: Type or None: Return the corresponding class if ``key`` exists, otherwise return None. Examples: >>> # define a registry >>> MODELS = Registry('models') >>> # register `ResNet` to `MODELS` >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> resnet_cls = MODELS.get('ResNet') >>> # hierarchical registry >>> DETECTORS = Registry('detector', parent=MODELS, scope='det') >>> # `ResNet` does not exist in `DETECTORS` but `get` method >>> # will try to search from its parents or ancestors >>> resnet_cls = DETECTORS.get('ResNet') >>> CLASSIFIER = Registry('classifier', parent=MODELS, scope='cls') >>> @CLASSIFIER.register_module() >>> class MobileNet: >>> pass >>> # `get` from its sibling registries >>> mobilenet_cls = DETECTORS.get('cls.MobileNet') """ # Avoid circular import from ..logging import print_log if not isinstance(key, str): raise TypeError( 'The key argument of `Registry.get` must be a str, ' f'got {type(key)}') scope, real_key = self.split_scope_key(key) obj_cls = None registry_name = self.name scope_name = self.scope # lazy import the modules to register them into the registry self.import_from_location() if scope is None or scope == self._scope: # get from self if real_key in self._module_dict: obj_cls = self._module_dict[real_key] elif scope is None: # try to get the target from its parent or ancestors parent = self.parent while parent is not None: if real_key in parent._module_dict: obj_cls = parent._module_dict[real_key] registry_name = parent.name scope_name = parent.scope break parent = parent.parent else: # import the registry to add the nodes into the registry tree try: import_module(f'{scope}.registry') print_log( f'Registry node of {scope} has been automatically ' 'imported.', logger='current', level=logging.DEBUG) except (ImportError, AttributeError, ModuleNotFoundError): print_log( f'Cannot auto import {scope}.registry, please check ' f'whether the package "{scope}" is installed correctly ' 'or import the registry manually.', logger='current', level=logging.DEBUG) # get from self._children if scope in self._children: obj_cls = self._children[scope].get(real_key) registry_name = self._children[scope].name scope_name = scope else: root = self._get_root_registry() if scope != root._scope and scope not in root._children: # If not skip directly, `root.get(key)` will recursively # call itself until RecursionError is thrown. pass else: obj_cls = root.get(key) if obj_cls is None: # Actually, it's strange to implement this `try ... except` to # get the object by its name in `Registry.get`. However, If we # want to build the model using a configuration like # `dict(type='mmengine.model.BaseModel')`, which can # be dumped by lazy import config, we need this code snippet # for `Registry.get` to work. try: obj_cls = get_object_from_string(key) except Exception: raise RuntimeError(f'Failed to get {key}') if obj_cls is not None: # For some rare cases (e.g. obj_cls is a partial function), obj_cls # doesn't have `__name__`. Use default value to prevent error cls_name = getattr(obj_cls, '__name__', str(obj_cls)) print_log( f'Get class `{cls_name}` from "{registry_name}"' f' registry in "{scope_name}"', logger='current', level=logging.DEBUG) return obj_cls
(self, key: str) -> Optional[Type]
730,254
mmengine.registry.registry
import_from_location
import modules from the pre-defined locations in self._location.
def import_from_location(self) -> None: """import modules from the pre-defined locations in self._location.""" if not self._imported: # Avoid circular import from ..logging import print_log # avoid BC breaking if len(self._locations) == 0 and self.scope in MODULE2PACKAGE: print_log( f'The "{self.name}" registry in {self.scope} did not ' 'set import location. Fallback to call ' f'`{self.scope}.utils.register_all_modules` ' 'instead.', logger='current', level=logging.DEBUG) try: module = import_module(f'{self.scope}.utils') except (ImportError, AttributeError, ModuleNotFoundError): if self.scope in MODULE2PACKAGE: print_log( f'{self.scope} is not installed and its ' 'modules will not be registered. If you ' 'want to use modules defined in ' f'{self.scope}, Please install {self.scope} by ' f'`pip install {MODULE2PACKAGE[self.scope]}.', logger='current', level=logging.WARNING) else: print_log( f'Failed to import {self.scope} and register ' 'its modules, please make sure you ' 'have registered the module manually.', logger='current', level=logging.WARNING) else: # The import errors triggered during the registration # may be more complex, here just throwing # the error to avoid causing more implicit registry errors # like `xxx`` not found in `yyy` registry. module.register_all_modules(False) # type: ignore for loc in self._locations: import_module(loc) print_log( f"Modules of {self.scope}'s {self.name} registry have " f'been automatically imported from {loc}', logger='current', level=logging.DEBUG) self._imported = True
(self) -> NoneType
730,255
mmengine.registry.registry
infer_scope
Infer the scope of registry. The name of the package where registry is defined will be returned. Returns: str: The inferred scope name. Examples: >>> # in mmdet/models/backbone/resnet.py >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> # The scope of ``ResNet`` will be ``mmdet``.
@staticmethod def infer_scope() -> str: """Infer the scope of registry. The name of the package where registry is defined will be returned. Returns: str: The inferred scope name. Examples: >>> # in mmdet/models/backbone/resnet.py >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> pass >>> # The scope of ``ResNet`` will be ``mmdet``. """ from ..logging import print_log # `sys._getframe` returns the frame object that many calls below the # top of the stack. The call stack for `infer_scope` can be listed as # follow: # frame-0: `infer_scope` itself # frame-1: `__init__` of `Registry` which calls the `infer_scope` # frame-2: Where the `Registry(...)` is called module = inspect.getmodule(sys._getframe(2)) if module is not None: filename = module.__name__ split_filename = filename.split('.') scope = split_filename[0] else: # use "mmengine" to handle some cases which can not infer the scope # like initializing Registry in interactive mode scope = 'mmengine' print_log( 'set scope as "mmengine" when scope can not be inferred. You ' 'can silence this warning by passing a "scope" argument to ' 'Registry like `Registry(name, scope="toy")`', logger='current', level=logging.WARNING) return scope
() -> str
730,256
mmengine.registry.registry
register_module
Register a module. A record will be added to ``self._module_dict``, whose key is the class name or the specified name, and value is the class itself. It can be used as a decorator or a normal function. Args: name (str or list of str, optional): The module name to be registered. If not specified, the class name will be used. force (bool): Whether to override an existing class with the same name. Defaults to False. module (type, optional): Module class or function to be registered. Defaults to None. Examples: >>> backbones = Registry('backbone') >>> # as a decorator >>> @backbones.register_module() >>> class ResNet: >>> pass >>> backbones = Registry('backbone') >>> @backbones.register_module(name='mnet') >>> class MobileNet: >>> pass >>> # as a normal function >>> class ResNet: >>> pass >>> backbones.register_module(module=ResNet)
def register_module( self, name: Optional[Union[str, List[str]]] = None, force: bool = False, module: Optional[Type] = None) -> Union[type, Callable]: """Register a module. A record will be added to ``self._module_dict``, whose key is the class name or the specified name, and value is the class itself. It can be used as a decorator or a normal function. Args: name (str or list of str, optional): The module name to be registered. If not specified, the class name will be used. force (bool): Whether to override an existing class with the same name. Defaults to False. module (type, optional): Module class or function to be registered. Defaults to None. Examples: >>> backbones = Registry('backbone') >>> # as a decorator >>> @backbones.register_module() >>> class ResNet: >>> pass >>> backbones = Registry('backbone') >>> @backbones.register_module(name='mnet') >>> class MobileNet: >>> pass >>> # as a normal function >>> class ResNet: >>> pass >>> backbones.register_module(module=ResNet) """ if not isinstance(force, bool): raise TypeError(f'force must be a boolean, but got {type(force)}') # raise the error ahead of time if not (name is None or isinstance(name, str) or is_seq_of(name, str)): raise TypeError( 'name must be None, an instance of str, or a sequence of str, ' f'but got {type(name)}') # use it as a normal method: x.register_module(module=SomeClass) if module is not None: self._register_module(module=module, module_name=name, force=force) return module # use it as a decorator: @x.register_module() def _register(module): self._register_module(module=module, module_name=name, force=force) return module return _register
(self, name: Union[str, List[str], NoneType] = None, force: bool = False, module: Optional[Type] = None) -> Union[type, collections.abc.Callable]
730,257
mmengine.registry.registry
split_scope_key
Split scope and key. The first scope will be split from key. Return: tuple[str | None, str]: The former element is the first scope of the key, which can be ``None``. The latter is the remaining key. Examples: >>> Registry.split_scope_key('mmdet.ResNet') 'mmdet', 'ResNet' >>> Registry.split_scope_key('ResNet') None, 'ResNet'
@staticmethod def split_scope_key(key: str) -> Tuple[Optional[str], str]: """Split scope and key. The first scope will be split from key. Return: tuple[str | None, str]: The former element is the first scope of the key, which can be ``None``. The latter is the remaining key. Examples: >>> Registry.split_scope_key('mmdet.ResNet') 'mmdet', 'ResNet' >>> Registry.split_scope_key('ResNet') None, 'ResNet' """ split_index = key.find('.') if split_index != -1: return key[:split_index], key[split_index + 1:] else: return None, key
(key: str) -> Tuple[Optional[str], str]
730,258
mmengine.registry.registry
switch_scope_and_registry
Temporarily switch default scope to the target scope, and get the corresponding registry. If the registry of the corresponding scope exists, yield the registry, otherwise yield the current itself. Args: scope (str, optional): The target scope. Examples: >>> from mmengine.registry import Registry, DefaultScope, MODELS >>> import time >>> # External Registry >>> MMDET_MODELS = Registry('mmdet_model', scope='mmdet', >>> parent=MODELS) >>> MMCLS_MODELS = Registry('mmcls_model', scope='mmcls', >>> parent=MODELS) >>> # Local Registry >>> CUSTOM_MODELS = Registry('custom_model', scope='custom', >>> parent=MODELS) >>> >>> # Initiate DefaultScope >>> DefaultScope.get_instance(f'scope_{time.time()}', >>> scope_name='custom') >>> # Check default scope >>> DefaultScope.get_current_instance().scope_name custom >>> # Switch to mmcls scope and get `MMCLS_MODELS` registry. >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as registry: >>> DefaultScope.get_current_instance().scope_name mmcls >>> registry.scope mmcls >>> # Nested switch scope >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmdet') as mmdet_registry: >>> DefaultScope.get_current_instance().scope_name mmdet >>> mmdet_registry.scope mmdet >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as mmcls_registry: >>> DefaultScope.get_current_instance().scope_name mmcls >>> mmcls_registry.scope mmcls >>> >>> # Check switch back to original scope. >>> DefaultScope.get_current_instance().scope_name custom
@contextmanager def switch_scope_and_registry(self, scope: Optional[str]) -> Generator: """Temporarily switch default scope to the target scope, and get the corresponding registry. If the registry of the corresponding scope exists, yield the registry, otherwise yield the current itself. Args: scope (str, optional): The target scope. Examples: >>> from mmengine.registry import Registry, DefaultScope, MODELS >>> import time >>> # External Registry >>> MMDET_MODELS = Registry('mmdet_model', scope='mmdet', >>> parent=MODELS) >>> MMCLS_MODELS = Registry('mmcls_model', scope='mmcls', >>> parent=MODELS) >>> # Local Registry >>> CUSTOM_MODELS = Registry('custom_model', scope='custom', >>> parent=MODELS) >>> >>> # Initiate DefaultScope >>> DefaultScope.get_instance(f'scope_{time.time()}', >>> scope_name='custom') >>> # Check default scope >>> DefaultScope.get_current_instance().scope_name custom >>> # Switch to mmcls scope and get `MMCLS_MODELS` registry. >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as registry: >>> DefaultScope.get_current_instance().scope_name mmcls >>> registry.scope mmcls >>> # Nested switch scope >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmdet') as mmdet_registry: >>> DefaultScope.get_current_instance().scope_name mmdet >>> mmdet_registry.scope mmdet >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as mmcls_registry: >>> DefaultScope.get_current_instance().scope_name mmcls >>> mmcls_registry.scope mmcls >>> >>> # Check switch back to original scope. >>> DefaultScope.get_current_instance().scope_name custom """ # noqa: E501 from ..logging import print_log # Switch to the given scope temporarily. If the corresponding registry # can be found in root registry, return the registry under the scope, # otherwise return the registry itself. with DefaultScope.overwrite_default_scope(scope): # Get the global default scope default_scope = DefaultScope.get_current_instance() # Get registry by scope if default_scope is not None: scope_name = default_scope.scope_name try: import_module(f'{scope_name}.registry') except (ImportError, AttributeError, ModuleNotFoundError): if scope in MODULE2PACKAGE: print_log( f'{scope} is not installed and its ' 'modules will not be registered. If you ' 'want to use modules defined in ' f'{scope}, Please install {scope} by ' f'`pip install {MODULE2PACKAGE[scope]}.', logger='current', level=logging.WARNING) else: print_log( f'Failed to import `{scope}.registry` ' f'make sure the registry.py exists in `{scope}` ' 'package.', logger='current', level=logging.WARNING) root = self._get_root_registry() registry = root._search_child(scope_name) if registry is None: # if `default_scope` can not be found, fallback to argument # `registry` print_log( f'Failed to search registry with scope "{scope_name}" ' f'in the "{root.name}" registry tree. ' f'As a workaround, the current "{self.name}" registry ' f'in "{self.scope}" is used to build instance. This ' 'may cause unexpected failure when running the built ' f'modules. Please check whether "{scope_name}" is a ' 'correct scope, or whether the registry is ' 'initialized.', logger='current', level=logging.WARNING) registry = self # If there is no built default scope, just return current registry. else: registry = self yield registry
(self, scope: Optional[str]) -> Generator
730,259
mmengine.utils.timer
Timer
A flexible Timer class. Examples: >>> import time >>> import mmcv >>> with mmcv.Timer(): >>> # simulate a code block that will run for 1s >>> time.sleep(1) 1.000 >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'): >>> # simulate a code block that will run for 1s >>> time.sleep(1) it takes 1.0 seconds >>> timer = mmcv.Timer() >>> time.sleep(0.5) >>> print(timer.since_start()) 0.500 >>> time.sleep(0.5) >>> print(timer.since_last_check()) 0.500 >>> print(timer.since_start()) 1.000
class Timer: """A flexible Timer class. Examples: >>> import time >>> import mmcv >>> with mmcv.Timer(): >>> # simulate a code block that will run for 1s >>> time.sleep(1) 1.000 >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'): >>> # simulate a code block that will run for 1s >>> time.sleep(1) it takes 1.0 seconds >>> timer = mmcv.Timer() >>> time.sleep(0.5) >>> print(timer.since_start()) 0.500 >>> time.sleep(0.5) >>> print(timer.since_last_check()) 0.500 >>> print(timer.since_start()) 1.000 """ def __init__(self, start=True, print_tmpl=None): self._is_running = False self.print_tmpl = print_tmpl if print_tmpl else '{:.3f}' if start: self.start() @property def is_running(self): """bool: indicate whether the timer is running""" return self._is_running def __enter__(self): self.start() return self def __exit__(self, type, value, traceback): print(self.print_tmpl.format(self.since_last_check())) self._is_running = False def start(self): """Start the timer.""" if not self._is_running: self._t_start = time() self._is_running = True self._t_last = time() def since_start(self): """Total time since the timer is started. Returns: float: Time in seconds. """ if not self._is_running: raise TimerError('timer is not running') self._t_last = time() return self._t_last - self._t_start def since_last_check(self): """Time since the last checking. Either :func:`since_start` or :func:`since_last_check` is a checking operation. Returns: float: Time in seconds. """ if not self._is_running: raise TimerError('timer is not running') dur = time() - self._t_last self._t_last = time() return dur
(start=True, print_tmpl=None)
730,261
mmengine.utils.timer
__exit__
null
def __exit__(self, type, value, traceback): print(self.print_tmpl.format(self.since_last_check())) self._is_running = False
(self, type, value, traceback)
730,262
mmengine.utils.timer
__init__
null
def __init__(self, start=True, print_tmpl=None): self._is_running = False self.print_tmpl = print_tmpl if print_tmpl else '{:.3f}' if start: self.start()
(self, start=True, print_tmpl=None)
730,263
mmengine.utils.timer
since_last_check
Time since the last checking. Either :func:`since_start` or :func:`since_last_check` is a checking operation. Returns: float: Time in seconds.
def since_last_check(self): """Time since the last checking. Either :func:`since_start` or :func:`since_last_check` is a checking operation. Returns: float: Time in seconds. """ if not self._is_running: raise TimerError('timer is not running') dur = time() - self._t_last self._t_last = time() return dur
(self)
730,264
mmengine.utils.timer
since_start
Total time since the timer is started. Returns: float: Time in seconds.
def since_start(self): """Total time since the timer is started. Returns: float: Time in seconds. """ if not self._is_running: raise TimerError('timer is not running') self._t_last = time() return self._t_last - self._t_start
(self)
730,265
mmengine.utils.timer
start
Start the timer.
def start(self): """Start the timer.""" if not self._is_running: self._t_start = time() self._is_running = True self._t_last = time()
(self)
730,266
mmengine.utils.timer
TimerError
null
class TimerError(Exception): def __init__(self, message): self.message = message super().__init__(message)
(message)
730,267
mmengine.utils.timer
__init__
null
def __init__(self, message): self.message = message super().__init__(message)
(self, message)
730,268
mmengine.fileio.handlers.yaml_handler
YamlHandler
null
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 dump_to_str(self, obj, **kwargs): kwargs.setdefault('Dumper', Dumper) return yaml.dump(obj, **kwargs)
()
730,269
mmengine.fileio.handlers.yaml_handler
dump_to_fileobj
null
def dump_to_fileobj(self, obj, file, **kwargs): kwargs.setdefault('Dumper', Dumper) yaml.dump(obj, file, **kwargs)
(self, obj, file, **kwargs)
730,271
mmengine.fileio.handlers.yaml_handler
dump_to_str
null
def dump_to_str(self, obj, **kwargs): kwargs.setdefault('Dumper', Dumper) return yaml.dump(obj, **kwargs)
(self, obj, **kwargs)
730,272
mmengine.fileio.handlers.yaml_handler
load_from_fileobj
null
def load_from_fileobj(self, file, **kwargs): kwargs.setdefault('Loader', Loader) return yaml.load(file, **kwargs)
(self, file, **kwargs)
730,274
mmengine.utils.misc
apply_to
Apply function to each element in dict, list or tuple that matches with the expression. For examples, if you want to convert each element in a list of dict from `np.ndarray` to `Tensor`. You can use the following code: Examples: >>> from mmengine.utils import apply_to >>> import numpy as np >>> import torch >>> data = dict(array=[np.array(1)]) # {'array': [array(1)]} >>> result = apply_to(data, lambda x: isinstance(x, np.ndarray), lambda x: torch.from_numpy(x)) >>> print(result) # {'array': [tensor(1)]} Args: data (Any): Data to be applied. expr (Callable): Expression to tell which data should be applied with the function. It should return a boolean. apply_func (Callable): Function applied to data. Returns: Any: The data after applying.
def apply_to(data: Any, expr: Callable, apply_func: Callable): """Apply function to each element in dict, list or tuple that matches with the expression. For examples, if you want to convert each element in a list of dict from `np.ndarray` to `Tensor`. You can use the following code: Examples: >>> from mmengine.utils import apply_to >>> import numpy as np >>> import torch >>> data = dict(array=[np.array(1)]) # {'array': [array(1)]} >>> result = apply_to(data, lambda x: isinstance(x, np.ndarray), lambda x: torch.from_numpy(x)) >>> print(result) # {'array': [tensor(1)]} Args: data (Any): Data to be applied. expr (Callable): Expression to tell which data should be applied with the function. It should return a boolean. apply_func (Callable): Function applied to data. Returns: Any: The data after applying. """ # noqa: E501 if isinstance(data, dict): # Keep the original dict type res = type(data)() for key, value in data.items(): res[key] = apply_to(value, expr, apply_func) return res elif isinstance(data, tuple) and hasattr(data, '_fields'): # namedtuple return type(data)(*(apply_to(sample, expr, apply_func) for sample in data)) # type: ignore # noqa: E501 # yapf:disable elif isinstance(data, (tuple, list)): return type(data)(apply_to(sample, expr, apply_func) for sample in data) # type: ignore # noqa: E501 # yapf:disable elif expr(data): return apply_func(data) else: return data
(data: Any, expr: Callable, apply_func: Callable)
730,275
mmengine.registry.build_functions
build_from_cfg
Build a module from config dict when it is a class configuration, or call a function from config dict when it is a function configuration. If the global variable default scope (:obj:`DefaultScope`) exists, :meth:`build` will firstly get the responding registry and then call its own :meth:`build`. At least one of the ``cfg`` and ``default_args`` contains the key "type", which should be either str or class. If they all contain it, the key in ``cfg`` will be used because ``cfg`` has a high priority than ``default_args`` that means if a key exists in both of them, the value of the key will be ``cfg[key]``. They will be merged first and the key "type" will be popped up and the remaining keys will be used as initialization arguments. Examples: >>> from mmengine import Registry, build_from_cfg >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> def __init__(self, depth, stages=4): >>> self.depth = depth >>> self.stages = stages >>> cfg = dict(type='ResNet', depth=50) >>> model = build_from_cfg(cfg, MODELS) >>> # Returns an instantiated object >>> @MODELS.register_module() >>> def resnet50(): >>> pass >>> resnet = build_from_cfg(dict(type='resnet50'), MODELS) >>> # Return a result of the calling function Args: cfg (dict or ConfigDict or Config): Config dict. It should at least contain the key "type". registry (:obj:`Registry`): The registry to search the type from. default_args (dict or ConfigDict or Config, optional): Default initialization arguments. Defaults to None. Returns: object: The constructed object.
def build_from_cfg( cfg: Union[dict, ConfigDict, Config], registry: Registry, default_args: Optional[Union[dict, ConfigDict, Config]] = None) -> Any: """Build a module from config dict when it is a class configuration, or call a function from config dict when it is a function configuration. If the global variable default scope (:obj:`DefaultScope`) exists, :meth:`build` will firstly get the responding registry and then call its own :meth:`build`. At least one of the ``cfg`` and ``default_args`` contains the key "type", which should be either str or class. If they all contain it, the key in ``cfg`` will be used because ``cfg`` has a high priority than ``default_args`` that means if a key exists in both of them, the value of the key will be ``cfg[key]``. They will be merged first and the key "type" will be popped up and the remaining keys will be used as initialization arguments. Examples: >>> from mmengine import Registry, build_from_cfg >>> MODELS = Registry('models') >>> @MODELS.register_module() >>> class ResNet: >>> def __init__(self, depth, stages=4): >>> self.depth = depth >>> self.stages = stages >>> cfg = dict(type='ResNet', depth=50) >>> model = build_from_cfg(cfg, MODELS) >>> # Returns an instantiated object >>> @MODELS.register_module() >>> def resnet50(): >>> pass >>> resnet = build_from_cfg(dict(type='resnet50'), MODELS) >>> # Return a result of the calling function Args: cfg (dict or ConfigDict or Config): Config dict. It should at least contain the key "type". registry (:obj:`Registry`): The registry to search the type from. default_args (dict or ConfigDict or Config, optional): Default initialization arguments. Defaults to None. Returns: object: The constructed object. """ # Avoid circular import from ..logging import print_log if not isinstance(cfg, (dict, ConfigDict, Config)): raise TypeError( f'cfg should be a dict, ConfigDict or Config, but got {type(cfg)}') if 'type' not in cfg: if default_args is None or 'type' not in default_args: raise KeyError( '`cfg` or `default_args` must contain the key "type", ' f'but got {cfg}\n{default_args}') if not isinstance(registry, Registry): raise TypeError('registry must be a mmengine.Registry object, ' f'but got {type(registry)}') if not (isinstance(default_args, (dict, ConfigDict, Config)) or default_args is None): raise TypeError( 'default_args should be a dict, ConfigDict, Config or None, ' f'but got {type(default_args)}') args = cfg.copy() if default_args is not None: for name, value in default_args.items(): args.setdefault(name, value) # Instance should be built under target scope, if `_scope_` is defined # in cfg, current default scope should switch to specified scope # temporarily. scope = args.pop('_scope_', None) with registry.switch_scope_and_registry(scope) as registry: obj_type = args.pop('type') if isinstance(obj_type, str): obj_cls = registry.get(obj_type) if obj_cls is None: raise KeyError( f'{obj_type} is not in the {registry.scope}::{registry.name} registry. ' # noqa: E501 f'Please check whether the value of `{obj_type}` is ' 'correct or it was registered as expected. More details ' 'can be found at ' 'https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#import-the-custom-module' # noqa: E501 ) # this will include classes, functions, partial functions and more elif callable(obj_type): obj_cls = obj_type else: raise TypeError( f'type must be a str or valid type, but got {type(obj_type)}') # If `obj_cls` inherits from `ManagerMixin`, it should be # instantiated by `ManagerMixin.get_instance` to ensure that it # can be accessed globally. if inspect.isclass(obj_cls) and \ issubclass(obj_cls, ManagerMixin): # type: ignore obj = obj_cls.get_instance(**args) # type: ignore else: obj = obj_cls(**args) # type: ignore if (inspect.isclass(obj_cls) or inspect.isfunction(obj_cls) or inspect.ismethod(obj_cls)): print_log( f'An `{obj_cls.__name__}` instance is built from ' # type: ignore # noqa: E501 'registry, and its implementation can be found in ' f'{obj_cls.__module__}', # type: ignore logger='current', level=logging.DEBUG) else: print_log( 'An instance is built from registry, and its constructor ' f'is {obj_cls}', logger='current', level=logging.DEBUG) return obj
(cfg: Union[dict, mmengine.config.config.ConfigDict, mmengine.config.config.Config], registry: mmengine.registry.registry.Registry, default_args: Union[dict, mmengine.config.config.ConfigDict, mmengine.config.config.Config, NoneType] = None) -> Any
730,276
mmengine.registry.build_functions
build_model_from_cfg
Build a PyTorch model from config dict(s). Different from ``build_from_cfg``, if cfg is a list, a ``nn.Sequential`` will be built. Args: cfg (dict, list[dict]): The config of modules, which is either a config dict or a list of config dicts. If cfg is a list, the built modules will be wrapped with ``nn.Sequential``. registry (:obj:`Registry`): A registry the module belongs to. default_args (dict, optional): Default arguments to build the module. Defaults to None. Returns: nn.Module: A built nn.Module.
def build_model_from_cfg( cfg: Union[dict, ConfigDict, Config], registry: Registry, default_args: Optional[Union[dict, 'ConfigDict', 'Config']] = None ) -> 'nn.Module': """Build a PyTorch model from config dict(s). Different from ``build_from_cfg``, if cfg is a list, a ``nn.Sequential`` will be built. Args: cfg (dict, list[dict]): The config of modules, which is either a config dict or a list of config dicts. If cfg is a list, the built modules will be wrapped with ``nn.Sequential``. registry (:obj:`Registry`): A registry the module belongs to. default_args (dict, optional): Default arguments to build the module. Defaults to None. Returns: nn.Module: A built nn.Module. """ from ..model import Sequential if isinstance(cfg, list): modules = [ build_from_cfg(_cfg, registry, default_args) for _cfg in cfg ] return Sequential(*modules) else: return build_from_cfg(cfg, registry, default_args)
(cfg: Union[dict, mmengine.config.config.ConfigDict, mmengine.config.config.Config], registry: mmengine.registry.registry.Registry, default_args: Union[dict, ForwardRef('ConfigDict'), ForwardRef('Config'), NoneType] = None) -> 'nn.Module'
730,277
mmengine.registry.build_functions
build_runner_from_cfg
Build a Runner object. Examples: >>> from mmengine.registry import Registry, build_runner_from_cfg >>> RUNNERS = Registry('runners', build_func=build_runner_from_cfg) >>> @RUNNERS.register_module() >>> class CustomRunner(Runner): >>> def setup_env(env_cfg): >>> pass >>> cfg = dict(runner_type='CustomRunner', ...) >>> custom_runner = RUNNERS.build(cfg) Args: cfg (dict or ConfigDict or Config): Config dict. If "runner_type" key exists, it will be used to build a custom runner. Otherwise, it will be used to build a default runner. registry (:obj:`Registry`): The registry to search the type from. Returns: object: The constructed runner object.
def build_runner_from_cfg(cfg: Union[dict, ConfigDict, Config], registry: Registry) -> 'Runner': """Build a Runner object. Examples: >>> from mmengine.registry import Registry, build_runner_from_cfg >>> RUNNERS = Registry('runners', build_func=build_runner_from_cfg) >>> @RUNNERS.register_module() >>> class CustomRunner(Runner): >>> def setup_env(env_cfg): >>> pass >>> cfg = dict(runner_type='CustomRunner', ...) >>> custom_runner = RUNNERS.build(cfg) Args: cfg (dict or ConfigDict or Config): Config dict. If "runner_type" key exists, it will be used to build a custom runner. Otherwise, it will be used to build a default runner. registry (:obj:`Registry`): The registry to search the type from. Returns: object: The constructed runner object. """ from ..config import Config, ConfigDict from ..logging import print_log assert isinstance( cfg, (dict, ConfigDict, Config )), f'cfg should be a dict, ConfigDict or Config, but got {type(cfg)}' assert isinstance( registry, Registry), ('registry should be a mmengine.Registry object', f'but got {type(registry)}') args = cfg.copy() # Runner should be built under target scope, if `_scope_` is defined # in cfg, current default scope should switch to specified scope # temporarily. scope = args.pop('_scope_', None) with registry.switch_scope_and_registry(scope) as registry: obj_type = args.get('runner_type', 'Runner') if isinstance(obj_type, str): runner_cls = registry.get(obj_type) if runner_cls is None: raise KeyError( f'{obj_type} is not in the {registry.name} registry. ' f'Please check whether the value of `{obj_type}` is ' 'correct or it was registered as expected. More details ' 'can be found at https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#import-the-custom-module' # noqa: E501 ) elif inspect.isclass(obj_type): runner_cls = obj_type else: raise TypeError( f'type must be a str or valid type, but got {type(obj_type)}') runner = runner_cls.from_cfg(args) # type: ignore print_log( f'An `{runner_cls.__name__}` instance is built from ' # type: ignore # noqa: E501 'registry, its implementation can be found in' f'{runner_cls.__module__}', # type: ignore logger='current', level=logging.DEBUG) return runner
(cfg: Union[dict, mmengine.config.config.ConfigDict, mmengine.config.config.Config], registry: mmengine.registry.registry.Registry) -> 'Runner'
730,278
mmengine.registry.build_functions
build_scheduler_from_cfg
Builds a ``ParamScheduler`` instance from config. ``ParamScheduler`` supports building instance by its constructor or method ``build_iter_from_epoch``. Therefore, its registry needs a build function to handle both cases. Args: cfg (dict or ConfigDict or Config): Config dictionary. If it contains the key ``convert_to_iter_based``, instance will be built by method ``convert_to_iter_based``, otherwise instance will be built by its constructor. registry (:obj:`Registry`): The ``PARAM_SCHEDULERS`` registry. default_args (dict or ConfigDict or Config, optional): Default initialization arguments. It must contain key ``optimizer``. If ``convert_to_iter_based`` is defined in ``cfg``, it must additionally contain key ``epoch_length``. Defaults to None. Returns: object: The constructed ``ParamScheduler``.
def build_scheduler_from_cfg( cfg: Union[dict, ConfigDict, Config], registry: Registry, default_args: Optional[Union[dict, ConfigDict, Config]] = None ) -> '_ParamScheduler': """Builds a ``ParamScheduler`` instance from config. ``ParamScheduler`` supports building instance by its constructor or method ``build_iter_from_epoch``. Therefore, its registry needs a build function to handle both cases. Args: cfg (dict or ConfigDict or Config): Config dictionary. If it contains the key ``convert_to_iter_based``, instance will be built by method ``convert_to_iter_based``, otherwise instance will be built by its constructor. registry (:obj:`Registry`): The ``PARAM_SCHEDULERS`` registry. default_args (dict or ConfigDict or Config, optional): Default initialization arguments. It must contain key ``optimizer``. If ``convert_to_iter_based`` is defined in ``cfg``, it must additionally contain key ``epoch_length``. Defaults to None. Returns: object: The constructed ``ParamScheduler``. """ assert isinstance( cfg, (dict, ConfigDict, Config )), f'cfg should be a dict, ConfigDict or Config, but got {type(cfg)}' assert isinstance( registry, Registry), ('registry should be a mmengine.Registry object', f'but got {type(registry)}') args = cfg.copy() if default_args is not None: for name, value in default_args.items(): args.setdefault(name, value) scope = args.pop('_scope_', None) with registry.switch_scope_and_registry(scope) as registry: convert_to_iter = args.pop('convert_to_iter_based', False) if convert_to_iter: scheduler_type = args.pop('type') assert 'epoch_length' in args and args.get('by_epoch', True), ( 'Only epoch-based parameter scheduler can be converted to ' 'iter-based, and `epoch_length` should be set') if isinstance(scheduler_type, str): scheduler_cls = registry.get(scheduler_type) if scheduler_cls is None: raise KeyError( f'{scheduler_type} is not in the {registry.name} ' 'registry. Please check whether the value of ' f'`{scheduler_type}` is correct or it was registered ' 'as expected. More details can be found at https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#import-the-custom-module' # noqa: E501 ) elif inspect.isclass(scheduler_type): scheduler_cls = scheduler_type else: raise TypeError('type must be a str or valid type, but got ' f'{type(scheduler_type)}') return scheduler_cls.build_iter_from_epoch( # type: ignore **args) else: args.pop('epoch_length', None) return build_from_cfg(args, registry)
(cfg: Union[dict, mmengine.config.config.ConfigDict, mmengine.config.config.Config], registry: mmengine.registry.registry.Registry, default_args: Union[dict, mmengine.config.config.ConfigDict, mmengine.config.config.Config, NoneType] = None) -> '_ParamScheduler'
730,279
mmengine.utils.package_utils
call_command
null
def call_command(cmd: list) -> None: try: subprocess.check_call(cmd) except Exception as e: raise e # type: ignore
(cmd: list) -> NoneType
730,280
mmengine.utils.path
check_file_exist
null
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'): if not osp.isfile(filename): raise FileNotFoundError(msg_tmpl.format(filename))
(filename, msg_tmpl='file "{}" does not exist')
730,281
mmengine.utils.misc
check_prerequisites
A decorator factory to check if prerequisites are satisfied. Args: prerequisites (str of list[str]): Prerequisites to be checked. checker (callable): The checker method that returns True if a prerequisite is meet, False otherwise. msg_tmpl (str): The message template with two variables. Returns: decorator: A specific decorator.
def check_prerequisites( prerequisites, checker, msg_tmpl='Prerequisites "{}" are required in method "{}" but not ' 'found, please install them first.'): # yapf: disable """A decorator factory to check if prerequisites are satisfied. Args: prerequisites (str of list[str]): Prerequisites to be checked. checker (callable): The checker method that returns True if a prerequisite is meet, False otherwise. msg_tmpl (str): The message template with two variables. Returns: decorator: A specific decorator. """ def wrap(func): @functools.wraps(func) def wrapped_func(*args, **kwargs): requirements = [prerequisites] if isinstance( prerequisites, str) else prerequisites missing = [] for item in requirements: if not checker(item): missing.append(item) if missing: print(msg_tmpl.format(', '.join(missing), func.__name__)) raise RuntimeError('Prerequisites not meet.') else: return func(*args, **kwargs) return wrapped_func return wrap
(prerequisites, checker, msg_tmpl='Prerequisites "{}" are required in method "{}" but not found, please install them first.')
730,282
mmengine.utils.timer
check_time
Add check points in a single line. This method is suitable for running a task on a list of items. A timer will be registered when the method is called for the first time. Examples: >>> import time >>> import mmcv >>> for i in range(1, 6): >>> # simulate a code block >>> time.sleep(i) >>> mmcv.check_time('task1') 2.000 3.000 4.000 5.000 Args: str: Timer identifier.
def check_time(timer_id): """Add check points in a single line. This method is suitable for running a task on a list of items. A timer will be registered when the method is called for the first time. Examples: >>> import time >>> import mmcv >>> for i in range(1, 6): >>> # simulate a code block >>> time.sleep(i) >>> mmcv.check_time('task1') 2.000 3.000 4.000 5.000 Args: str: Timer identifier. """ if timer_id not in _g_timers: _g_timers[timer_id] = Timer() return 0 else: return _g_timers[timer_id].since_last_check()
(timer_id)
730,283
mmengine.utils.misc
concat_list
Concatenate a list of list into a single list. Args: in_list (list): The list of list to be merged. Returns: list: The concatenated flat list.
def concat_list(in_list): """Concatenate a list of list into a single list. Args: in_list (list): The list of list to be merged. Returns: list: The concatenated flat list. """ return list(itertools.chain(*in_list))
(in_list)
730,285
mmengine.fileio.io
copy_if_symlink_fails
Create a symbolic link pointing to src named dst. If failed to create a symbolic link pointing to src, directory copy src to dst instead. Args: src (str or Path): Create a symbolic link pointing to src. dst (str or Path): Create a symbolic link named dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return True if successfully create a symbolic link pointing to src. Otherwise, return False. Examples: >>> src = '/path/of/file' >>> dst = '/path1/of/file1' >>> copy_if_symlink_fails(src, dst) True >>> src = '/path/of/dir' >>> dst = '/path1/of/dir1' >>> copy_if_symlink_fails(src, dst) True
def copy_if_symlink_fails( src: Union[str, Path], dst: Union[str, Path], backend_args: Optional[dict] = None, ) -> bool: """Create a symbolic link pointing to src named dst. If failed to create a symbolic link pointing to src, directory copy src to dst instead. Args: src (str or Path): Create a symbolic link pointing to src. dst (str or Path): Create a symbolic link named dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return True if successfully create a symbolic link pointing to src. Otherwise, return False. Examples: >>> src = '/path/of/file' >>> dst = '/path1/of/file1' >>> copy_if_symlink_fails(src, dst) True >>> src = '/path/of/dir' >>> dst = '/path1/of/dir1' >>> copy_if_symlink_fails(src, dst) True """ backend = get_file_backend( src, backend_args=backend_args, enable_singleton=True) return backend.copy_if_symlink_fails(src, dst)
(src: Union[str, pathlib.Path], dst: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> bool
730,286
mmengine.fileio.io
copyfile
Copy a file src to dst and return the destination file. src and dst should have the same prefix. If dst specifies a directory, the file will be copied into dst using the base filename from src. If dst specifies a file that already exists, it will be replaced. Args: src (str or Path): A file to be copied. dst (str or Path): Copy file to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination file. Raises: SameFileError: If src and dst are the same file, a SameFileError will be raised. Examples: >>> # dst is a file >>> src = '/path/of/file' >>> dst = '/path1/of/file1' >>> # src will be copied to '/path1/of/file1' >>> copyfile(src, dst) '/path1/of/file1' >>> # dst is a directory >>> dst = '/path1/of/dir' >>> # src will be copied to '/path1/of/dir/file' >>> copyfile(src, dst) '/path1/of/dir/file'
def copyfile( src: Union[str, Path], dst: Union[str, Path], backend_args: Optional[dict] = None, ) -> Union[str, Path]: """Copy a file src to dst and return the destination file. src and dst should have the same prefix. If dst specifies a directory, the file will be copied into dst using the base filename from src. If dst specifies a file that already exists, it will be replaced. Args: src (str or Path): A file to be copied. dst (str or Path): Copy file to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination file. Raises: SameFileError: If src and dst are the same file, a SameFileError will be raised. Examples: >>> # dst is a file >>> src = '/path/of/file' >>> dst = '/path1/of/file1' >>> # src will be copied to '/path1/of/file1' >>> copyfile(src, dst) '/path1/of/file1' >>> # dst is a directory >>> dst = '/path1/of/dir' >>> # src will be copied to '/path1/of/dir/file' >>> copyfile(src, dst) '/path1/of/dir/file' """ backend = get_file_backend( src, backend_args=backend_args, enable_singleton=True) return backend.copyfile(src, dst)
(src: Union[str, pathlib.Path], dst: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Union[str, pathlib.Path]
730,287
mmengine.fileio.io
copyfile_from_local
Copy a local file src to dst and return the destination file. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copyfile`. Args: src (str or Path): A local file to be copied. dst (str or Path): Copy file to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: If dst specifies a directory, the file will be copied into dst using the base filename from src. Examples: >>> # dst is a file >>> src = '/path/of/file' >>> dst = 's3://openmmlab/mmengine/file1' >>> # src will be copied to 's3://openmmlab/mmengine/file1' >>> copyfile_from_local(src, dst) s3://openmmlab/mmengine/file1 >>> # dst is a directory >>> dst = 's3://openmmlab/mmengine' >>> # src will be copied to 's3://openmmlab/mmengine/file'' >>> copyfile_from_local(src, dst) 's3://openmmlab/mmengine/file'
def copyfile_from_local( src: Union[str, Path], dst: Union[str, Path], backend_args: Optional[dict] = None, ) -> Union[str, Path]: """Copy a local file src to dst and return the destination file. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copyfile`. Args: src (str or Path): A local file to be copied. dst (str or Path): Copy file to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: If dst specifies a directory, the file will be copied into dst using the base filename from src. Examples: >>> # dst is a file >>> src = '/path/of/file' >>> dst = 's3://openmmlab/mmengine/file1' >>> # src will be copied to 's3://openmmlab/mmengine/file1' >>> copyfile_from_local(src, dst) s3://openmmlab/mmengine/file1 >>> # dst is a directory >>> dst = 's3://openmmlab/mmengine' >>> # src will be copied to 's3://openmmlab/mmengine/file'' >>> copyfile_from_local(src, dst) 's3://openmmlab/mmengine/file' """ backend = get_file_backend( dst, backend_args=backend_args, enable_singleton=True) return backend.copyfile_from_local(src, dst)
(src: Union[str, pathlib.Path], dst: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Union[str, pathlib.Path]
730,288
mmengine.fileio.io
copyfile_to_local
Copy the file src to local dst and return the destination file. If dst specifies a directory, the file will be copied into dst using the base filename from src. If dst specifies a file that already exists, it will be replaced. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copyfile`. Args: src (str or Path): A file to be copied. dst (str or Path): Copy file to to local dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: If dst specifies a directory, the file will be copied into dst using the base filename from src. Examples: >>> # dst is a file >>> src = 's3://openmmlab/mmengine/file' >>> dst = '/path/of/file' >>> # src will be copied to '/path/of/file' >>> copyfile_to_local(src, dst) '/path/of/file' >>> # dst is a directory >>> dst = '/path/of/dir' >>> # src will be copied to '/path/of/dir/file' >>> copyfile_to_local(src, dst) '/path/of/dir/file'
def copyfile_to_local( src: Union[str, Path], dst: Union[str, Path], backend_args: Optional[dict] = None, ) -> Union[str, Path]: """Copy the file src to local dst and return the destination file. If dst specifies a directory, the file will be copied into dst using the base filename from src. If dst specifies a file that already exists, it will be replaced. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copyfile`. Args: src (str or Path): A file to be copied. dst (str or Path): Copy file to to local dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: If dst specifies a directory, the file will be copied into dst using the base filename from src. Examples: >>> # dst is a file >>> src = 's3://openmmlab/mmengine/file' >>> dst = '/path/of/file' >>> # src will be copied to '/path/of/file' >>> copyfile_to_local(src, dst) '/path/of/file' >>> # dst is a directory >>> dst = '/path/of/dir' >>> # src will be copied to '/path/of/dir/file' >>> copyfile_to_local(src, dst) '/path/of/dir/file' """ backend = get_file_backend( dst, backend_args=backend_args, enable_singleton=True) return backend.copyfile_to_local(src, dst)
(src: Union[str, pathlib.Path], dst: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Union[str, pathlib.Path]
730,289
mmengine.fileio.io
copytree
Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. src and dst should have the same prefix and dst must not already exist. Args: src (str or Path): A directory to be copied. dst (str or Path): Copy directory to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination directory. Raises: FileExistsError: If dst had already existed, a FileExistsError will be raised. Examples: >>> src = '/path/of/dir1' >>> dst = '/path/of/dir2' >>> copytree(src, dst) '/path/of/dir2'
def copytree( src: Union[str, Path], dst: Union[str, Path], backend_args: Optional[dict] = None, ) -> Union[str, Path]: """Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. src and dst should have the same prefix and dst must not already exist. Args: src (str or Path): A directory to be copied. dst (str or Path): Copy directory to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination directory. Raises: FileExistsError: If dst had already existed, a FileExistsError will be raised. Examples: >>> src = '/path/of/dir1' >>> dst = '/path/of/dir2' >>> copytree(src, dst) '/path/of/dir2' """ backend = get_file_backend( src, backend_args=backend_args, enable_singleton=True) return backend.copytree(src, dst)
(src: Union[str, pathlib.Path], dst: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Union[str, pathlib.Path]
730,290
mmengine.fileio.io
copytree_from_local
Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copytree`. Args: src (str or Path): A local directory to be copied. dst (str or Path): Copy directory to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination directory. Examples: >>> src = '/path/of/dir' >>> dst = 's3://openmmlab/mmengine/dir' >>> copyfile_from_local(src, dst) 's3://openmmlab/mmengine/dir'
def copytree_from_local( src: Union[str, Path], dst: Union[str, Path], backend_args: Optional[dict] = None, ) -> Union[str, Path]: """Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copytree`. Args: src (str or Path): A local directory to be copied. dst (str or Path): Copy directory to dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination directory. Examples: >>> src = '/path/of/dir' >>> dst = 's3://openmmlab/mmengine/dir' >>> copyfile_from_local(src, dst) 's3://openmmlab/mmengine/dir' """ backend = get_file_backend( dst, backend_args=backend_args, enable_singleton=True) return backend.copytree_from_local(src, dst)
(src: Union[str, pathlib.Path], dst: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Union[str, pathlib.Path]
730,291
mmengine.fileio.io
copytree_to_local
Recursively copy an entire directory tree rooted at src to a local directory named dst and return the destination directory. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copytree`. Args: src (str or Path): A directory to be copied. dst (str or Path): Copy directory to local dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination directory. Examples: >>> src = 's3://openmmlab/mmengine/dir' >>> dst = '/path/of/dir' >>> copytree_to_local(src, dst) '/path/of/dir'
def copytree_to_local( src: Union[str, Path], dst: Union[str, Path], backend_args: Optional[dict] = None, ) -> Union[str, Path]: """Recursively copy an entire directory tree rooted at src to a local directory named dst and return the destination directory. Note: If the backend is the instance of LocalBackend, it does the same thing with :func:`copytree`. Args: src (str or Path): A directory to be copied. dst (str or Path): Copy directory to local dst. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The destination directory. Examples: >>> src = 's3://openmmlab/mmengine/dir' >>> dst = '/path/of/dir' >>> copytree_to_local(src, dst) '/path/of/dir' """ backend = get_file_backend( dst, backend_args=backend_args, enable_singleton=True) return backend.copytree_to_local(src, dst)
(src: Union[str, pathlib.Path], dst: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Union[str, pathlib.Path]
730,292
mmengine.registry.utils
count_registered_modules
Scan all modules in MMEngine's root and child registries and dump to json. Args: save_path (str, optional): Path to save the json file. verbose (bool): Whether to print log. Defaults to True. Returns: dict: Statistic results of all registered modules.
def count_registered_modules(save_path: Optional[str] = None, verbose: bool = True) -> dict: """Scan all modules in MMEngine's root and child registries and dump to json. Args: save_path (str, optional): Path to save the json file. verbose (bool): Whether to print log. Defaults to True. Returns: dict: Statistic results of all registered modules. """ # import modules to trigger registering import mmengine.dataset import mmengine.evaluator import mmengine.hooks import mmengine.model import mmengine.optim import mmengine.runner import mmengine.visualization # noqa: F401 registries_info = {} # traverse all registries in MMEngine for item in dir(root): if not item.startswith('__'): registry = getattr(root, item) if isinstance(registry, Registry): registries_info[item] = traverse_registry_tree( registry, verbose) scan_data = dict( scan_date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), registries=registries_info) if verbose: print_log( f'Finish registry analysis, got: {scan_data}', logger='current') if save_path is not None: json_path = osp.join(save_path, 'modules_statistic_results.json') dump(scan_data, json_path, indent=2) print_log(f'Result has been saved to {json_path}', logger='current') return scan_data
(save_path: Optional[str] = None, verbose: bool = True) -> dict
730,293
mmengine.utils.misc
deprecated_api_warning
A decorator to check if some arguments are deprecate and try to replace deprecate src_arg_name to dst_arg_name. Args: name_dict(dict): key (str): Deprecate argument names. val (str): Expected argument names. Returns: func: New function.
def deprecated_api_warning(name_dict: dict, cls_name: Optional[str] = None) -> Callable: """A decorator to check if some arguments are deprecate and try to replace deprecate src_arg_name to dst_arg_name. Args: name_dict(dict): key (str): Deprecate argument names. val (str): Expected argument names. Returns: func: New function. """ def api_warning_wrapper(old_func): @functools.wraps(old_func) def new_func(*args, **kwargs): # get the arg spec of the decorated method args_info = getfullargspec(old_func) # get name of the function func_name = old_func.__name__ if cls_name is not None: func_name = f'{cls_name}.{func_name}' if args: arg_names = args_info.args[:len(args)] for src_arg_name, dst_arg_name in name_dict.items(): if src_arg_name in arg_names: warnings.warn( f'"{src_arg_name}" is deprecated in ' f'`{func_name}`, please use "{dst_arg_name}" ' 'instead', DeprecationWarning) arg_names[arg_names.index(src_arg_name)] = dst_arg_name if kwargs: for src_arg_name, dst_arg_name in name_dict.items(): if src_arg_name in kwargs: assert dst_arg_name not in kwargs, ( f'The expected behavior is to replace ' f'the deprecated key `{src_arg_name}` to ' f'new key `{dst_arg_name}`, but got them ' f'in the arguments at the same time, which ' f'is confusing. `{src_arg_name} will be ' f'deprecated in the future, please ' f'use `{dst_arg_name}` instead.') warnings.warn( f'"{src_arg_name}" is deprecated in ' f'`{func_name}`, please use "{dst_arg_name}" ' 'instead', DeprecationWarning) kwargs[dst_arg_name] = kwargs.pop(src_arg_name) # apply converted arguments to the decorated method output = old_func(*args, **kwargs) return output return new_func return api_warning_wrapper
(name_dict: dict, cls_name: Optional[str] = None) -> Callable
730,294
mmengine.utils.misc
deprecated_function
Marks functions as deprecated. Throw a warning when a deprecated function is called, and add a note in the docstring. Modified from https://github.com/pytorch/pytorch/blob/master/torch/onnx/_deprecation.py Args: since (str): The version when the function was first deprecated. removed_in (str): The version when the function will be removed. instructions (str): The action users should take. Returns: Callable: A new function, which will be deprecated soon.
def deprecated_function(since: str, removed_in: str, instructions: str) -> Callable: """Marks functions as deprecated. Throw a warning when a deprecated function is called, and add a note in the docstring. Modified from https://github.com/pytorch/pytorch/blob/master/torch/onnx/_deprecation.py Args: since (str): The version when the function was first deprecated. removed_in (str): The version when the function will be removed. instructions (str): The action users should take. Returns: Callable: A new function, which will be deprecated soon. """ # noqa: E501 from mmengine import print_log def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): print_log( f"'{function.__module__}.{function.__name__}' " f'is deprecated in version {since} and will be ' f'removed in version {removed_in}. Please {instructions}.', logger='current', level=logging.WARNING, ) return function(*args, **kwargs) indent = ' ' # Add a deprecation note to the docstring. docstring = function.__doc__ or '' # Add a note to the docstring. deprecation_note = textwrap.dedent(f"""\ .. deprecated:: {since} Deprecated and will be removed in version {removed_in}. Please {instructions}. """) # Split docstring at first occurrence of newline pattern = '\n\n' summary_and_body = re.split(pattern, docstring, 1) if len(summary_and_body) > 1: summary, body = summary_and_body body = textwrap.indent(textwrap.dedent(body), indent) summary = '\n'.join( [textwrap.dedent(string) for string in summary.split('\n')]) summary = textwrap.indent(summary, prefix=indent) # Dedent the body. We cannot do this with the presence of the # summary because the body contains leading whitespaces when the # summary does not. new_docstring_parts = [ deprecation_note, '\n\n', summary, '\n\n', body ] else: summary = summary_and_body[0] summary = '\n'.join( [textwrap.dedent(string) for string in summary.split('\n')]) summary = textwrap.indent(summary, prefix=indent) new_docstring_parts = [deprecation_note, '\n\n', summary] wrapper.__doc__ = ''.join(new_docstring_parts) return wrapper return decorator
(since: str, removed_in: str, instructions: str) -> Callable
730,295
mmengine.fileio.parse
dict_from_file
Load a text file and parse the content as a dict. Each line of the text file will be two or more columns split by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. ``dict_from_file`` supports loading a text file which can be storaged in different backends and parsing the content as a dict. Args: filename(str): Filename. key_type(type): Type of the dict keys. str is user by default and type conversion will be performed if specified. encoding (str): Encoding used to open the file. Defaults to utf-8. file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> dict_from_file('/path/of/your/file') # disk {'key1': 'value1', 'key2': 'value2'} >>> dict_from_file('s3://path/of/your/file') # ceph or petrel {'key1': 'value1', 'key2': 'value2'} Returns: dict: The parsed contents.
def dict_from_file(filename, key_type=str, encoding='utf-8', file_client_args=None, backend_args=None): """Load a text file and parse the content as a dict. Each line of the text file will be two or more columns split by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. ``dict_from_file`` supports loading a text file which can be storaged in different backends and parsing the content as a dict. Args: filename(str): Filename. key_type(type): Type of the dict keys. str is user by default and type conversion will be performed if specified. encoding (str): Encoding used to open the file. Defaults to utf-8. file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> dict_from_file('/path/of/your/file') # disk {'key1': 'value1', 'key2': 'value2'} >>> dict_from_file('s3://path/of/your/file') # ceph or petrel {'key1': 'value1', 'key2': 'value2'} Returns: dict: The parsed contents. """ if file_client_args is not None: warnings.warn( '"file_client_args" will be deprecated in future. ' 'Please use "backend_args" instead', DeprecationWarning) if backend_args is not None: raise ValueError( '"file_client_args" and "backend_args" cannot be set at the ' 'same time.') mapping = {} if file_client_args is not None: file_client = FileClient.infer_client(file_client_args, filename) text = file_client.get_text(filename, encoding) else: text = get_text(filename, encoding, backend_args=backend_args) with StringIO(text) as f: for line in f: items = line.rstrip('\n').split() assert len(items) >= 2 key = key_type(items[0]) val = items[1:] if len(items) > 2 else items[1] mapping[key] = val return mapping
(filename, key_type=<class 'str'>, encoding='utf-8', file_client_args=None, backend_args=None)
730,296
mmengine.utils.version_utils
digit_version
Convert a version string into a tuple of integers. This method is usually used for comparing two versions. For pre-release versions: alpha < beta < rc. Args: version_str (str): The version string. length (int): The maximum number of version levels. Defaults to 4. Returns: tuple[int]: The version info in digits (integers).
def digit_version(version_str: str, length: int = 4): """Convert a version string into a tuple of integers. This method is usually used for comparing two versions. For pre-release versions: alpha < beta < rc. Args: version_str (str): The version string. length (int): The maximum number of version levels. Defaults to 4. Returns: tuple[int]: The version info in digits (integers). """ assert 'parrots' not in version_str version = parse(version_str) assert version.release, f'failed to parse version {version_str}' release = list(version.release) release = release[:length] if len(release) < length: release = release + [0] * (length - len(release)) if version.is_prerelease: mapping = {'a': -3, 'b': -2, 'rc': -1} val = -4 # version.pre can be None if version.pre: if version.pre[0] not in mapping: warnings.warn(f'unknown prerelease version {version.pre[0]}, ' 'version checking may go wrong') else: val = mapping[version.pre[0]] release.extend([val, version.pre[-1]]) else: release.extend([val, 0]) elif version.is_postrelease: release.extend([1, version.post]) # type: ignore else: release.extend([0, 0]) return tuple(release)
(version_str: str, length: int = 4)
730,297
mmengine.fileio.io
dump
Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. ``dump`` supports dumping data as strings or to files which is saved to different backends. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is dumped to a str, otherwise to a file specified by the filename or file-like object. file_format (str, optional): Same as :func:`load`. file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> dump('hello world', '/path/of/your/file') # disk >>> dump('hello world', 's3://path/of/your/file') # ceph or petrel Returns: bool: True for success, False otherwise.
def dump(obj, file=None, file_format=None, file_client_args=None, backend_args=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. ``dump`` supports dumping data as strings or to files which is saved to different backends. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is dumped to a str, otherwise to a file specified by the filename or file-like object. file_format (str, optional): Same as :func:`load`. file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> dump('hello world', '/path/of/your/file') # disk >>> dump('hello world', 's3://path/of/your/file') # ceph or petrel Returns: bool: True for success, False otherwise. """ if isinstance(file, Path): file = str(file) if file_format is None: if is_str(file): file_format = file.split('.')[-1] elif file is None: raise ValueError( 'file_format must be specified since file is None') if file_format not in file_handlers: raise TypeError(f'Unsupported format: {file_format}') if file_client_args is not None: warnings.warn( '"file_client_args" will be deprecated in future. ' 'Please use "backend_args" instead', DeprecationWarning) if backend_args is not None: raise ValueError( '"file_client_args" and "backend_args" cannot be set at the ' 'same time.') handler = file_handlers[file_format] if file is None: return handler.dump_to_str(obj, **kwargs) elif is_str(file): if file_client_args is not None: file_client = FileClient.infer_client(file_client_args, file) file_backend = file_client else: file_backend = get_file_backend(file, backend_args=backend_args) if handler.str_like: with StringIO() as f: handler.dump_to_fileobj(obj, f, **kwargs) file_backend.put_text(f.getvalue(), file) else: with BytesIO() as f: handler.dump_to_fileobj(obj, f, **kwargs) file_backend.put(f.getvalue(), file) elif hasattr(file, 'write'): handler.dump_to_fileobj(obj, file, **kwargs) else: raise TypeError('"file" must be a filename str or a file-object')
(obj, file=None, file_format=None, file_client_args=None, backend_args=None, **kwargs)
730,298
mmengine.fileio.io
exists
Check whether a file path exists. Args: filepath (str or Path): Path to be checked whether exists. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. Examples: >>> filepath = '/path/of/file' >>> exists(filepath) True
def exists( filepath: Union[str, Path], backend_args: Optional[dict] = None, ) -> bool: """Check whether a file path exists. Args: filepath (str or Path): Path to be checked whether exists. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. Examples: >>> filepath = '/path/of/file' >>> exists(filepath) True """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) return backend.exists(filepath)
(filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> bool
730,300
mmengine.utils.path
fopen
null
def fopen(filepath, *args, **kwargs): if is_str(filepath): return open(filepath, *args, **kwargs) elif isinstance(filepath, Path): return filepath.open(*args, **kwargs) raise ValueError('`filepath` should be a string or a Path')
(filepath, *args, **kwargs)
730,301
mmengine.fileio.io
generate_presigned_url
Generate the presigned url of video stream which can be passed to mmcv.VideoReader. Now only work on Petrel backend. Note: Now only work on Petrel backend. Args: url (str): Url of video stream. client_method (str): Method of client, 'get_object' or 'put_object'. Defaults to 'get_object'. expires_in (int): expires, in seconds. Defaults to 3600. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: Generated presigned url.
def generate_presigned_url( url: str, client_method: str = 'get_object', expires_in: int = 3600, backend_args: Optional[dict] = None, ) -> str: """Generate the presigned url of video stream which can be passed to mmcv.VideoReader. Now only work on Petrel backend. Note: Now only work on Petrel backend. Args: url (str): Url of video stream. client_method (str): Method of client, 'get_object' or 'put_object'. Defaults to 'get_object'. expires_in (int): expires, in seconds. Defaults to 3600. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: Generated presigned url. """ backend = get_file_backend( url, backend_args=backend_args, enable_singleton=True) return backend.generate_presigned_url(url, client_method, expires_in)
(url: str, client_method: str = 'get_object', expires_in: int = 3600, backend_args: Optional[dict] = None) -> str
730,302
mmengine.fileio.io
get
Read bytes from a given ``filepath`` with 'rb' mode. Args: filepath (str or Path): Path to read data. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bytes: Expected bytes object. Examples: >>> filepath = '/path/of/file' >>> get(filepath) b'hello world'
def get( filepath: Union[str, Path], backend_args: Optional[dict] = None, ) -> bytes: """Read bytes from a given ``filepath`` with 'rb' mode. Args: filepath (str or Path): Path to read data. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bytes: Expected bytes object. Examples: >>> filepath = '/path/of/file' >>> get(filepath) b'hello world' """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) return backend.get(filepath)
(filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> bytes
730,303
mmengine.fileio.io
get_file_backend
Return a file backend based on the prefix of uri or backend_args. Args: uri (str or Path): Uri to be parsed that contains the file prefix. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. enable_singleton (bool): Whether to enable the singleton pattern. If it is True, the backend created will be reused if the signature is same with the previous one. Defaults to False. Returns: BaseStorageBackend: Instantiated Backend object. Examples: >>> # get file backend based on the prefix of uri >>> uri = 's3://path/of/your/file' >>> backend = get_file_backend(uri) >>> # get file backend based on the backend_args >>> backend = get_file_backend(backend_args={'backend': 'petrel'}) >>> # backend name has a higher priority if 'backend' in backend_args >>> backend = get_file_backend(uri, backend_args={'backend': 'petrel'})
def get_file_backend( uri: Union[str, Path, None] = None, *, backend_args: Optional[dict] = None, enable_singleton: bool = False, ): """Return a file backend based on the prefix of uri or backend_args. Args: uri (str or Path): Uri to be parsed that contains the file prefix. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. enable_singleton (bool): Whether to enable the singleton pattern. If it is True, the backend created will be reused if the signature is same with the previous one. Defaults to False. Returns: BaseStorageBackend: Instantiated Backend object. Examples: >>> # get file backend based on the prefix of uri >>> uri = 's3://path/of/your/file' >>> backend = get_file_backend(uri) >>> # get file backend based on the backend_args >>> backend = get_file_backend(backend_args={'backend': 'petrel'}) >>> # backend name has a higher priority if 'backend' in backend_args >>> backend = get_file_backend(uri, backend_args={'backend': 'petrel'}) """ global backend_instances if backend_args is None: backend_args = {} if uri is None and 'backend' not in backend_args: raise ValueError( 'uri should not be None when "backend" does not exist in ' 'backend_args') if uri is not None: prefix = _parse_uri_prefix(uri) else: prefix = '' if enable_singleton: # TODO: whether to pass sort_key to json.dumps unique_key = f'{prefix}:{json.dumps(backend_args)}' if unique_key in backend_instances: return backend_instances[unique_key] backend = _get_file_backend(prefix, backend_args) backend_instances[unique_key] = backend return backend else: backend = _get_file_backend(prefix, backend_args) return backend
(uri: Union[str, pathlib.Path, NoneType] = None, *, backend_args: Optional[dict] = None, enable_singleton: bool = False)
730,304
mmengine.utils.version_utils
get_git_hash
Get the git hash of the current repo. Args: fallback (str, optional): The fallback string when git hash is unavailable. Defaults to 'unknown'. digits (int, optional): kept digits of the hash. Defaults to None, meaning all digits are kept. Returns: str: Git commit hash.
def get_git_hash(fallback='unknown', digits=None): """Get the git hash of the current repo. Args: fallback (str, optional): The fallback string when git hash is unavailable. Defaults to 'unknown'. digits (int, optional): kept digits of the hash. Defaults to None, meaning all digits are kept. Returns: str: Git commit hash. """ if digits is not None and not isinstance(digits, int): raise TypeError('digits must be None or an integer') try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) sha = out.strip().decode('ascii') if digits is not None: sha = sha[:digits] except OSError: sha = fallback return sha
(fallback='unknown', digits=None)
730,305
mmengine.utils.package_utils
get_installed_path
Get installed path of package. Args: package (str): Name of package. Example: >>> get_installed_path('mmcls') >>> '.../lib/python3.7/site-packages/mmcls'
def get_installed_path(package: str) -> str: """Get installed path of package. Args: package (str): Name of package. Example: >>> get_installed_path('mmcls') >>> '.../lib/python3.7/site-packages/mmcls' """ import importlib.util from pkg_resources import DistributionNotFound, get_distribution # if the package name is not the same as module name, module name should be # inferred. For example, mmcv-full is the package name, but mmcv is module # name. If we want to get the installed path of mmcv-full, we should concat # the pkg.location and module name try: pkg = get_distribution(package) except DistributionNotFound as e: # if the package is not installed, package path set in PYTHONPATH # can be detected by `find_spec` spec = importlib.util.find_spec(package) if spec is not None: if spec.origin is not None: return osp.dirname(spec.origin) else: # `get_installed_path` cannot get the installed path of # namespace packages raise RuntimeError( f'{package} is a namespace package, which is invalid ' 'for `get_install_path`') else: raise e possible_path = osp.join(pkg.location, package) if osp.exists(possible_path): return possible_path else: return osp.join(pkg.location, package2module(package))
(package: str) -> str
730,306
mmengine.fileio.io
get_local_path
Download data from ``filepath`` and write the data to local path. ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It can be called with ``with`` statement, and when exists from the ``with`` statement, the temporary path will be released. Note: If the ``filepath`` is a local path, just return itself and it will not be released (removed). Args: filepath (str or Path): Path to be read data. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Yields: Iterable[str]: Only yield one path. Examples: >>> with get_local_path('s3://bucket/abc.jpg') as path: ... # do something here
def exists( filepath: Union[str, Path], backend_args: Optional[dict] = None, ) -> bool: """Check whether a file path exists. Args: filepath (str or Path): Path to be checked whether exists. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. Examples: >>> filepath = '/path/of/file' >>> exists(filepath) True """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) return backend.exists(filepath)
(filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Generator[Union[str, pathlib.Path], NoneType, NoneType]
730,307
mmengine.utils.misc
get_object_from_string
Get object from name. Args: obj_name (str): The name of the object. Examples: >>> get_object_from_string('torch.optim.sgd.SGD') >>> torch.optim.sgd.SGD
def get_object_from_string(obj_name: str): """Get object from name. Args: obj_name (str): The name of the object. Examples: >>> get_object_from_string('torch.optim.sgd.SGD') >>> torch.optim.sgd.SGD """ parts = iter(obj_name.split('.')) module_name = next(parts) # import module while True: try: module = import_module(module_name) part = next(parts) # mmcv.ops has nms.py and nms function at the same time. So the # function will have a higher priority obj = getattr(module, part, None) if obj is not None and not ismodule(obj): break module_name = f'{module_name}.{part}' except StopIteration: # if obj is a module return module except ImportError: return None # get class or attribute from module obj = module while True: try: obj = getattr(obj, part) part = next(parts) except StopIteration: return obj except AttributeError: return None
(obj_name: str)
730,308
mmengine.fileio.io
get_text
Read text from a given ``filepath`` with 'r' mode. Args: filepath (str or Path): Path to read data. encoding (str): The encoding format used to open the ``filepath``. Defaults to 'utf-8'. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: Expected text reading from ``filepath``. Examples: >>> filepath = '/path/of/file' >>> get_text(filepath) 'hello world'
def get_text( filepath: Union[str, Path], encoding='utf-8', backend_args: Optional[dict] = None, ) -> str: """Read text from a given ``filepath`` with 'r' mode. Args: filepath (str or Path): Path to read data. encoding (str): The encoding format used to open the ``filepath``. Defaults to 'utf-8'. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: Expected text reading from ``filepath``. Examples: >>> filepath = '/path/of/file' >>> get_text(filepath) 'hello world' """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) return backend.get_text(filepath, encoding)
(filepath: Union[str, pathlib.Path], encoding='utf-8', backend_args: Optional[dict] = None) -> str
730,309
mmengine.utils.misc
has_method
Check whether the object has a method. Args: method (str): The method name to check. obj (object): The object to check. Returns: bool: True if the object has the method else False.
def has_method(obj: object, method: str) -> bool: """Check whether the object has a method. Args: method (str): The method name to check. obj (object): The object to check. Returns: bool: True if the object has the method else False. """ return hasattr(obj, method) and callable(getattr(obj, method))
(obj: object, method: str) -> bool
730,310
mmengine.utils.misc
import_modules_from_strings
Import modules from the given list of strings. Args: imports (list | str | None): The given module names to be imported. allow_failed_imports (bool): If True, the failed imports will return None. Otherwise, an ImportError is raise. Defaults to False. Returns: list[module] | module | None: The imported modules. Examples: >>> osp, sys = import_modules_from_strings( ... ['os.path', 'sys']) >>> import os.path as osp_ >>> import sys as sys_ >>> assert osp == osp_ >>> assert sys == sys_
def import_modules_from_strings(imports, allow_failed_imports=False): """Import modules from the given list of strings. Args: imports (list | str | None): The given module names to be imported. allow_failed_imports (bool): If True, the failed imports will return None. Otherwise, an ImportError is raise. Defaults to False. Returns: list[module] | module | None: The imported modules. Examples: >>> osp, sys = import_modules_from_strings( ... ['os.path', 'sys']) >>> import os.path as osp_ >>> import sys as sys_ >>> assert osp == osp_ >>> assert sys == sys_ """ if not imports: return single_import = False if isinstance(imports, str): single_import = True imports = [imports] if not isinstance(imports, list): raise TypeError( f'custom_imports must be a list but got type {type(imports)}') imported = [] for imp in imports: if not isinstance(imp, str): raise TypeError( f'{imp} is of type {type(imp)} and cannot be imported.') try: imported_tmp = import_module(imp) except ImportError: if allow_failed_imports: warnings.warn(f'{imp} failed to import and is ignored.', UserWarning) imported_tmp = None else: raise ImportError(f'Failed to import {imp}') imported.append(imported_tmp) if single_import: imported = imported[0] return imported
(imports, allow_failed_imports=False)
730,311
mmengine.registry.utils
init_default_scope
Initialize the given default scope. Args: scope (str): The name of the default scope.
def init_default_scope(scope: str) -> None: """Initialize the given default scope. Args: scope (str): The name of the default scope. """ never_created = DefaultScope.get_current_instance( ) is None or not DefaultScope.check_instance_created(scope) if never_created: DefaultScope.get_instance(scope, scope_name=scope) return current_scope = DefaultScope.get_current_instance() # type: ignore if current_scope.scope_name != scope: # type: ignore print_log( 'The current default scope ' # type: ignore f'"{current_scope.scope_name}" is not "{scope}", ' '`init_default_scope` will force set the current' f'default scope to "{scope}".', logger='current', level=logging.WARNING) # avoid name conflict new_instance_name = f'{scope}-{datetime.datetime.now()}' DefaultScope.get_instance(new_instance_name, scope_name=scope)
(scope: str) -> NoneType
730,312
mmengine.utils.package_utils
install_package
null
def install_package(package: str): if not is_installed(package): call_command(['python', '-m', 'pip', 'install', package])
(package: str)
730,313
mmengine.utils.path
is_abs
Check if path is an absolute path in different backends. Args: path (str): path of directory or file. Returns: bool: whether path is an absolute path.
def is_abs(path: str) -> bool: """Check if path is an absolute path in different backends. Args: path (str): path of directory or file. Returns: bool: whether path is an absolute path. """ if osp.isabs(path) or path.startswith(('http://', 'https://', 's3://')): return True else: return False
(path: str) -> bool
730,314
mmengine.utils.path
is_filepath
null
def is_filepath(x): return is_str(x) or isinstance(x, Path)
(x)
730,315
mmengine.utils.package_utils
is_installed
Check package whether installed. Args: package (str): Name of package to be checked.
def is_installed(package: str) -> bool: """Check package whether installed. Args: package (str): Name of package to be checked. """ # When executing `import mmengine.runner`, # pkg_resources will be imported and it takes too much time. # Therefore, import it in function scope to save time. import importlib.util import pkg_resources from pkg_resources import get_distribution # refresh the pkg_resources # more datails at https://github.com/pypa/setuptools/issues/373 importlib.reload(pkg_resources) try: get_distribution(package) return True except pkg_resources.DistributionNotFound: spec = importlib.util.find_spec(package) if spec is None: return False elif spec.origin is not None: return True else: return False
(package: str) -> bool
730,316
mmengine.utils.misc
is_list_of
Check whether it is a list of some type. A partial method of :func:`is_seq_of`.
def is_list_of(seq, expected_type): """Check whether it is a list of some type. A partial method of :func:`is_seq_of`. """ return is_seq_of(seq, expected_type, seq_type=list)
(seq, expected_type)
730,317
mmengine.utils.misc
is_method_overridden
Check if a method of base class is overridden in derived class. Args: method (str): the method name to check. base_class (type): the class of the base class. derived_class (type | Any): the class or instance of the derived class.
def is_method_overridden(method: str, base_class: type, derived_class: Union[type, Any]) -> bool: """Check if a method of base class is overridden in derived class. Args: method (str): the method name to check. base_class (type): the class of the base class. derived_class (type | Any): the class or instance of the derived class. """ assert isinstance(base_class, type), \ "base_class doesn't accept instance, Please pass class instead." if not isinstance(derived_class, type): derived_class = derived_class.__class__ base_method = getattr(base_class, method) derived_method = getattr(derived_class, method) return derived_method != base_method
(method: str, base_class: type, derived_class: Union[type, Any]) -> bool
730,318
mmengine.utils.misc
is_seq_of
Check whether it is a sequence of some type. Args: seq (Sequence): The sequence to be checked. expected_type (type or tuple): Expected type of sequence items. seq_type (type, optional): Expected sequence type. Defaults to None. Returns: bool: Return True if ``seq`` is valid else False. Examples: >>> from mmengine.utils import is_seq_of >>> seq = ['a', 'b', 'c'] >>> is_seq_of(seq, str) True >>> is_seq_of(seq, int) False
def is_seq_of(seq: Any, expected_type: Union[Type, tuple], seq_type: Type = None) -> bool: """Check whether it is a sequence of some type. Args: seq (Sequence): The sequence to be checked. expected_type (type or tuple): Expected type of sequence items. seq_type (type, optional): Expected sequence type. Defaults to None. Returns: bool: Return True if ``seq`` is valid else False. Examples: >>> from mmengine.utils import is_seq_of >>> seq = ['a', 'b', 'c'] >>> is_seq_of(seq, str) True >>> is_seq_of(seq, int) False """ if seq_type is None: exp_seq_type = abc.Sequence else: assert isinstance(seq_type, type) exp_seq_type = seq_type if not isinstance(seq, exp_seq_type): return False for item in seq: if not isinstance(item, expected_type): return False return True
(seq: Any, expected_type: Union[Type, tuple], seq_type: Optional[Type] = None) -> bool
730,319
mmengine.utils.misc
is_str
Whether the input is an string instance. Note: This method is deprecated since python 2 is no longer supported.
def is_str(x): """Whether the input is an string instance. Note: This method is deprecated since python 2 is no longer supported. """ return isinstance(x, str)
(x)
730,320
mmengine.utils.misc
is_tuple_of
Check whether it is a tuple of some type. A partial method of :func:`is_seq_of`.
def is_tuple_of(seq, expected_type): """Check whether it is a tuple of some type. A partial method of :func:`is_seq_of`. """ return is_seq_of(seq, expected_type, seq_type=tuple)
(seq, expected_type)
730,321
mmengine.fileio.io
isdir
Check whether a file path is a directory. Args: filepath (str or Path): Path to be checked whether it is a directory. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return ``True`` if ``filepath`` points to a directory, ``False`` otherwise. Examples: >>> filepath = '/path/of/dir' >>> isdir(filepath) True
def isdir( filepath: Union[str, Path], backend_args: Optional[dict] = None, ) -> bool: """Check whether a file path is a directory. Args: filepath (str or Path): Path to be checked whether it is a directory. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return ``True`` if ``filepath`` points to a directory, ``False`` otherwise. Examples: >>> filepath = '/path/of/dir' >>> isdir(filepath) True """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) return backend.isdir(filepath)
(filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> bool
730,322
mmengine.fileio.io
isfile
Check whether a file path is a file. Args: filepath (str or Path): Path to be checked whether it is a file. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return ``True`` if ``filepath`` points to a file, ``False`` otherwise. Examples: >>> filepath = '/path/of/file' >>> isfile(filepath) True
def isfile( filepath: Union[str, Path], backend_args: Optional[dict] = None, ) -> bool: """Check whether a file path is a file. Args: filepath (str or Path): Path to be checked whether it is a file. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: bool: Return ``True`` if ``filepath`` points to a file, ``False`` otherwise. Examples: >>> filepath = '/path/of/file' >>> isfile(filepath) True """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) return backend.isfile(filepath)
(filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> bool
730,323
mmengine.utils.misc
iter_cast
Cast elements of an iterable object into some type. Args: inputs (Iterable): The input object. dst_type (type): Destination type. return_type (type, optional): If specified, the output object will be converted to this type, otherwise an iterator. Returns: iterator or specified type: The converted object.
def iter_cast(inputs, dst_type, return_type=None): """Cast elements of an iterable object into some type. Args: inputs (Iterable): The input object. dst_type (type): Destination type. return_type (type, optional): If specified, the output object will be converted to this type, otherwise an iterator. Returns: iterator or specified type: The converted object. """ if not isinstance(inputs, abc.Iterable): raise TypeError('inputs must be an iterable object') if not isinstance(dst_type, type): raise TypeError('"dst_type" must be a valid type') out_iterable = map(dst_type, inputs) if return_type is None: return out_iterable else: return return_type(out_iterable)
(inputs, dst_type, return_type=None)
730,324
mmengine.fileio.io
join_path
Concatenate all file paths. Join one or more filepath components intelligently. The return value is the concatenation of filepath and any members of \*filepaths. Args: filepath (str or Path): Path to be concatenated. *filepaths (str or Path): Other paths to be concatenated. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The result of concatenation. Examples: >>> filepath1 = '/path/of/dir1' >>> filepath2 = 'dir2' >>> filepath3 = 'path/of/file' >>> join_path(filepath1, filepath2, filepath3) '/path/of/dir/dir2/path/of/file'
def join_path( filepath: Union[str, Path], *filepaths: Union[str, Path], backend_args: Optional[dict] = None, ) -> Union[str, Path]: r"""Concatenate all file paths. Join one or more filepath components intelligently. The return value is the concatenation of filepath and any members of \*filepaths. Args: filepath (str or Path): Path to be concatenated. *filepaths (str or Path): Other paths to be concatenated. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Returns: str: The result of concatenation. Examples: >>> filepath1 = '/path/of/dir1' >>> filepath2 = 'dir2' >>> filepath3 = 'path/of/file' >>> join_path(filepath1, filepath2, filepath3) '/path/of/dir/dir2/path/of/file' """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) return backend.join_path(filepath, *filepaths)
(filepath: Union[str, pathlib.Path], *filepaths: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> Union[str, pathlib.Path]
730,325
mmengine.utils.misc
list_cast
Cast elements of an iterable object into a list of some type. A partial method of :func:`iter_cast`.
def list_cast(inputs, dst_type): """Cast elements of an iterable object into a list of some type. A partial method of :func:`iter_cast`. """ return iter_cast(inputs, dst_type, return_type=list)
(inputs, dst_type)
730,326
mmengine.fileio.io
list_dir_or_file
Scan a directory to find the interested directories or files in arbitrary order. Note: :meth:`list_dir_or_file` returns the path relative to ``dir_path``. Args: dir_path (str or Path): Path of the directory. list_dir (bool): List the directories. Defaults to True. list_file (bool): List the path of files. Defaults to True. suffix (str or tuple[str], optional): File suffix that we are interested in. Defaults to None. recursive (bool): If set to True, recursively scan the directory. Defaults to False. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Yields: Iterable[str]: A relative path to ``dir_path``. Examples: >>> dir_path = '/path/of/dir' >>> for file_path in list_dir_or_file(dir_path): ... print(file_path) >>> # list those files and directories in current directory >>> for file_path in list_dir_or_file(dir_path): ... print(file_path) >>> # only list files >>> for file_path in list_dir_or_file(dir_path, list_dir=False): ... print(file_path) >>> # only list directories >>> for file_path in list_dir_or_file(dir_path, list_file=False): ... print(file_path) >>> # only list files ending with specified suffixes >>> for file_path in list_dir_or_file(dir_path, suffix='.txt'): ... print(file_path) >>> # list all files and directory recursively >>> for file_path in list_dir_or_file(dir_path, recursive=True): ... print(file_path)
def list_dir_or_file( dir_path: Union[str, Path], list_dir: bool = True, list_file: bool = True, suffix: Optional[Union[str, Tuple[str]]] = None, recursive: bool = False, backend_args: Optional[dict] = None, ) -> Iterator[str]: """Scan a directory to find the interested directories or files in arbitrary order. Note: :meth:`list_dir_or_file` returns the path relative to ``dir_path``. Args: dir_path (str or Path): Path of the directory. list_dir (bool): List the directories. Defaults to True. list_file (bool): List the path of files. Defaults to True. suffix (str or tuple[str], optional): File suffix that we are interested in. Defaults to None. recursive (bool): If set to True, recursively scan the directory. Defaults to False. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Yields: Iterable[str]: A relative path to ``dir_path``. Examples: >>> dir_path = '/path/of/dir' >>> for file_path in list_dir_or_file(dir_path): ... print(file_path) >>> # list those files and directories in current directory >>> for file_path in list_dir_or_file(dir_path): ... print(file_path) >>> # only list files >>> for file_path in list_dir_or_file(dir_path, list_dir=False): ... print(file_path) >>> # only list directories >>> for file_path in list_dir_or_file(dir_path, list_file=False): ... print(file_path) >>> # only list files ending with specified suffixes >>> for file_path in list_dir_or_file(dir_path, suffix='.txt'): ... print(file_path) >>> # list all files and directory recursively >>> for file_path in list_dir_or_file(dir_path, recursive=True): ... print(file_path) """ backend = get_file_backend( dir_path, backend_args=backend_args, enable_singleton=True) yield from backend.list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive)
(dir_path: Union[str, pathlib.Path], list_dir: bool = True, list_file: bool = True, suffix: Union[str, Tuple[str], NoneType] = None, recursive: bool = False, backend_args: Optional[dict] = None) -> Iterator[str]
730,327
mmengine.fileio.parse
list_from_file
Load a text file and parse the content as a list of strings. ``list_from_file`` supports loading a text file which can be storaged in different backends and parsing the content as a list for strings. Args: filename (str): Filename. prefix (str): The prefix to be inserted to the beginning of each item. offset (int): The offset of lines. max_num (int): The maximum number of lines to be read, zeros and negatives mean no limitation. encoding (str): Encoding used to open the file. Defaults to utf-8. file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> list_from_file('/path/of/your/file') # disk ['hello', 'world'] >>> list_from_file('s3://path/of/your/file') # ceph or petrel ['hello', 'world'] Returns: list[str]: A list of strings.
def list_from_file(filename, prefix='', offset=0, max_num=0, encoding='utf-8', file_client_args=None, backend_args=None): """Load a text file and parse the content as a list of strings. ``list_from_file`` supports loading a text file which can be storaged in different backends and parsing the content as a list for strings. Args: filename (str): Filename. prefix (str): The prefix to be inserted to the beginning of each item. offset (int): The offset of lines. max_num (int): The maximum number of lines to be read, zeros and negatives mean no limitation. encoding (str): Encoding used to open the file. Defaults to utf-8. file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> list_from_file('/path/of/your/file') # disk ['hello', 'world'] >>> list_from_file('s3://path/of/your/file') # ceph or petrel ['hello', 'world'] Returns: list[str]: A list of strings. """ if file_client_args is not None: warnings.warn( '"file_client_args" will be deprecated in future. ' 'Please use "backend_args" instead', DeprecationWarning) if backend_args is not None: raise ValueError( '"file_client_args" and "backend_args" cannot be set at the ' 'same time.') cnt = 0 item_list = [] if file_client_args is not None: file_client = FileClient.infer_client(file_client_args, filename) text = file_client.get_text(filename, encoding) else: text = get_text(filename, encoding, backend_args=backend_args) with StringIO(text) as f: for _ in range(offset): f.readline() for line in f: if 0 < max_num <= cnt: break item_list.append(prefix + line.rstrip('\n\r')) cnt += 1 return item_list
(filename, prefix='', offset=0, max_num=0, encoding='utf-8', file_client_args=None, backend_args=None)
730,328
mmengine.fileio.io
load
Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. ``load`` supports loading data from serialized files those can be storaged in different backends. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> load('/path/of/your/file') # file is storaged in disk >>> load('https://path/of/your/file') # file is storaged in Internet >>> load('s3://path/of/your/file') # file is storaged in petrel Returns: The content from the file.
def load(file, file_format=None, file_client_args=None, backend_args=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. ``load`` supports loading data from serialized files those can be storaged in different backends. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". file_client_args (dict, optional): Arguments to instantiate a FileClient. See :class:`mmengine.fileio.FileClient` for details. Defaults to None. It will be deprecated in future. Please use ``backend_args`` instead. backend_args (dict, optional): Arguments to instantiate the prefix of uri corresponding backend. Defaults to None. New in v0.2.0. Examples: >>> load('/path/of/your/file') # file is storaged in disk >>> load('https://path/of/your/file') # file is storaged in Internet >>> load('s3://path/of/your/file') # file is storaged in petrel Returns: The content from the file. """ if isinstance(file, Path): file = str(file) if file_format is None and is_str(file): file_format = file.split('.')[-1] if file_format not in file_handlers: raise TypeError(f'Unsupported format: {file_format}') if file_client_args is not None: warnings.warn( '"file_client_args" will be deprecated in future. ' 'Please use "backend_args" instead', DeprecationWarning) if backend_args is not None: raise ValueError( '"file_client_args and "backend_args" cannot be set at the ' 'same time.') handler = file_handlers[file_format] if is_str(file): if file_client_args is not None: file_client = FileClient.infer_client(file_client_args, file) file_backend = file_client else: file_backend = get_file_backend(file, backend_args=backend_args) if handler.str_like: with StringIO(file_backend.get_text(file)) as f: obj = handler.load_from_fileobj(f, **kwargs) else: with BytesIO(file_backend.get(file)) as f: obj = handler.load_from_fileobj(f, **kwargs) elif hasattr(file, 'read'): obj = handler.load_from_fileobj(file, **kwargs) else: raise TypeError('"file" must be a filepath str or a file-object') return obj
(file, file_format=None, file_client_args=None, backend_args=None, **kwargs)
730,330
mmengine.utils.path
mkdir_or_exist
null
def mkdir_or_exist(dir_name, mode=0o777): if dir_name == '': return dir_name = osp.expanduser(dir_name) os.makedirs(dir_name, mode=mode, exist_ok=True)
(dir_name, mode=511)
730,331
mmengine.logging.logger
print_log
Print a log message. Args: msg (str): The message to be logged. logger (Logger or str, optional): If the type of logger is ``logging.Logger``, we directly use logger to log messages. Some special loggers are: - "silent": No message will be printed. - "current": Use latest created logger to log message. - other str: Instance name of logger. The corresponding logger will log message if it has been created, otherwise ``print_log`` will raise a `ValueError`. - None: The `print()` method will be used to print log messages. level (int): Logging level. Only available when `logger` is a Logger object, "current", or a created logger instance name.
def print_log(msg, logger: Optional[Union[Logger, str]] = None, level=logging.INFO) -> None: """Print a log message. Args: msg (str): The message to be logged. logger (Logger or str, optional): If the type of logger is ``logging.Logger``, we directly use logger to log messages. Some special loggers are: - "silent": No message will be printed. - "current": Use latest created logger to log message. - other str: Instance name of logger. The corresponding logger will log message if it has been created, otherwise ``print_log`` will raise a `ValueError`. - None: The `print()` method will be used to print log messages. level (int): Logging level. Only available when `logger` is a Logger object, "current", or a created logger instance name. """ if logger is None: print(msg) elif isinstance(logger, logging.Logger): logger.log(level, msg) elif logger == 'silent': pass elif logger == 'current': logger_instance = MMLogger.get_current_instance() logger_instance.log(level, msg) elif isinstance(logger, str): # If the type of `logger` is `str`, but not with value of `current` or # `silent`, we assume it indicates the name of the logger. If the # corresponding logger has not been created, `print_log` will raise # a `ValueError`. if MMLogger.check_instance_created(logger): logger_instance = MMLogger.get_instance(logger) logger_instance.log(level, msg) else: raise ValueError(f'MMLogger: {logger} has not been created!') else: raise TypeError( '`logger` should be either a logging.Logger object, str, ' f'"silent", "current" or None, but got {type(logger)}')
(msg, logger: Union[logging.Logger, str, NoneType] = None, level=20) -> NoneType
730,332
mmengine.fileio.io
put
Write bytes to a given ``filepath`` with 'wb' mode. Note: ``put`` should create a directory if the directory of ``filepath`` does not exist. Args: obj (bytes): Data to be written. filepath (str or Path): Path to write data. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Examples: >>> filepath = '/path/of/file' >>> put(b'hello world', filepath)
def put( obj: bytes, filepath: Union[str, Path], backend_args: Optional[dict] = None, ) -> None: """Write bytes to a given ``filepath`` with 'wb' mode. Note: ``put`` should create a directory if the directory of ``filepath`` does not exist. Args: obj (bytes): Data to be written. filepath (str or Path): Path to write data. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Examples: >>> filepath = '/path/of/file' >>> put(b'hello world', filepath) """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) backend.put(obj, filepath)
(obj: bytes, filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> NoneType
730,333
mmengine.fileio.io
put_text
Write text to a given ``filepath`` with 'w' mode. Note: ``put_text`` should create a directory if the directory of ``filepath`` does not exist. Args: obj (str): Data to be written. filepath (str or Path): Path to write data. encoding (str, optional): The encoding format used to open the ``filepath``. Defaults to 'utf-8'. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Examples: >>> filepath = '/path/of/file' >>> put_text('hello world', filepath)
def put_text( obj: str, filepath: Union[str, Path], backend_args: Optional[dict] = None, ) -> None: """Write text to a given ``filepath`` with 'w' mode. Note: ``put_text`` should create a directory if the directory of ``filepath`` does not exist. Args: obj (str): Data to be written. filepath (str or Path): Path to write data. encoding (str, optional): The encoding format used to open the ``filepath``. Defaults to 'utf-8'. backend_args (dict, optional): Arguments to instantiate the corresponding backend. Defaults to None. Examples: >>> filepath = '/path/of/file' >>> put_text('hello world', filepath) """ backend = get_file_backend( filepath, backend_args=backend_args, enable_singleton=True) backend.put_text(obj, filepath)
(obj: str, filepath: Union[str, pathlib.Path], backend_args: Optional[dict] = None) -> NoneType
730,334
mmengine.config.config
read_base
Context manager to mark the base config. The pure Python-style configuration file allows you to use the import syntax. However, it is important to note that you need to import the base configuration file within the context of ``read_base``, and import other dependencies outside of it. You can see more usage of Python-style configuration in the `tutorial`_ .. _tutorial: https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#a-pure-python-style-configuration-file-beta
def __reduce_ex__(self, proto): # Override __reduce_ex__ to avoid `self.items` will be # called by CPython interpreter during pickling. See more details in # https://github.com/python/cpython/blob/8d61a71f9c81619e34d4a30b625922ebc83c561b/Objects/typeobject.c#L6196 # noqa: E501 if digit_version(platform.python_version()) < digit_version('3.8'): return (self.__class__, ({k: v for k, v in super().items()}, ), None, None, None) else: return (self.__class__, ({k: v for k, v in super().items()}, ), None, None, None, None)
()
730,335
mmengine.fileio.backends.registry_utils
register_backend
Register a backend. Args: name (str): The name of the registered backend. backend (class, optional): The backend class to be registered, which must be a subclass of :class:`BaseStorageBackend`. When this method is used as a decorator, backend is None. Defaults to None. force (bool): Whether to override the backend if the name has already been registered. Defaults to False. prefixes (str or list[str] or tuple[str], optional): The prefix of the registered storage backend. Defaults to None. This method can be used as a normal method or a decorator. Examples: >>> class NewBackend(BaseStorageBackend): ... def get(self, filepath): ... return filepath ... ... def get_text(self, filepath): ... return filepath >>> register_backend('new', NewBackend) >>> @register_backend('new') ... class NewBackend(BaseStorageBackend): ... def get(self, filepath): ... return filepath ... ... def get_text(self, filepath): ... return filepath
def register_backend(name: str, backend: Optional[Type[BaseStorageBackend]] = None, force: bool = False, prefixes: Union[str, list, tuple, None] = None): """Register a backend. Args: name (str): The name of the registered backend. backend (class, optional): The backend class to be registered, which must be a subclass of :class:`BaseStorageBackend`. When this method is used as a decorator, backend is None. Defaults to None. force (bool): Whether to override the backend if the name has already been registered. Defaults to False. prefixes (str or list[str] or tuple[str], optional): The prefix of the registered storage backend. Defaults to None. This method can be used as a normal method or a decorator. Examples: >>> class NewBackend(BaseStorageBackend): ... def get(self, filepath): ... return filepath ... ... def get_text(self, filepath): ... return filepath >>> register_backend('new', NewBackend) >>> @register_backend('new') ... class NewBackend(BaseStorageBackend): ... def get(self, filepath): ... return filepath ... ... def get_text(self, filepath): ... return filepath """ if backend is not None: _register_backend(name, backend, force=force, prefixes=prefixes) return def _register(backend_cls): _register_backend(name, backend_cls, force=force, prefixes=prefixes) return backend_cls return _register
(name: str, backend: Optional[Type[mmengine.fileio.backends.base.BaseStorageBackend]] = None, force: bool = False, prefixes: Union[str, list, tuple, NoneType] = None)