|
| 1 | +# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, |
| 10 | +# software distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import importlib |
| 16 | +import re |
| 17 | +from typing import Any, Type |
| 18 | + |
| 19 | + |
| 20 | +LOGGER_REGISTRY = "src.deepsparse.loggers_v2.registry.__init__" |
| 21 | + |
| 22 | + |
| 23 | +def import_from_registry(name: str) -> Type[Any]: |
| 24 | + """ |
| 25 | + Import `name` from the LOGGER_REGISTRY |
| 26 | +
|
| 27 | + :param name: name of the function or class name in LOGGER_REGISTRY |
| 28 | + :return: Function or class object |
| 29 | + """ |
| 30 | + module = importlib.import_module(LOGGER_REGISTRY) |
| 31 | + try: |
| 32 | + return getattr(module, name) |
| 33 | + except AttributeError: |
| 34 | + raise AttributeError( |
| 35 | + f"Cannot import class/func with name '{name}' from {LOGGER_REGISTRY}" |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +def import_from_path(path: str) -> Type[Any]: |
| 40 | + """ |
| 41 | + Import the module and the name of the function/class separated by : |
| 42 | +
|
| 43 | + Examples: |
| 44 | + path = "/path/to/file.py:func_name" |
| 45 | + path = "/path/to/file:class_name" |
| 46 | +
|
| 47 | + :param path: path including the file path and object name |
| 48 | + :return Function or class object |
| 49 | +
|
| 50 | + """ |
| 51 | + path, class_name = path.split(":") |
| 52 | + _path = path |
| 53 | + |
| 54 | + path = path.split(".py")[0] |
| 55 | + path = re.sub(r"/+", ".", path) |
| 56 | + try: |
| 57 | + module = importlib.import_module(path) |
| 58 | + except ImportError: |
| 59 | + raise ImportError(f"Cannot find module with path {_path}") |
| 60 | + |
| 61 | + try: |
| 62 | + return getattr(module, class_name) |
| 63 | + except AttributeError: |
| 64 | + raise AttributeError(f"Cannot find {class_name} in {_path}") |
0 commit comments