components.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import importlib
  17. import inspect
  18. import typing
  19. from pathlib import Path
  20. from fate_flow.utils.log_utils import getLogger
  21. from fate_flow.components._base import ComponentMeta
  22. LOGGER = getLogger()
  23. def _get_module_name_by_path(path, base):
  24. return '.'.join(path.resolve().relative_to(base.resolve()).with_suffix('').parts)
  25. def _search_components(path, base):
  26. try:
  27. module_name = _get_module_name_by_path(path, base)
  28. module = importlib.import_module(module_name)
  29. except ImportError as e:
  30. # or skip ?
  31. raise e
  32. _obj_pairs = inspect.getmembers(module, lambda obj: isinstance(obj, ComponentMeta))
  33. return _obj_pairs, module_name
  34. class Components:
  35. provider_version = None
  36. provider_name = None
  37. provider_path = None
  38. @classmethod
  39. def _module_base(cls):
  40. return Path(cls.provider_path).resolve().parent
  41. @classmethod
  42. def _components_base(cls):
  43. return Path(cls.provider_path, 'components').resolve()
  44. @classmethod
  45. def get_names(cls) -> typing.Dict[str, dict]:
  46. names = {}
  47. for p in cls._components_base().glob("**/*.py"):
  48. obj_pairs, module_name = _search_components(p.resolve(), cls._module_base())
  49. for name, obj in obj_pairs:
  50. names[obj.name] = {"module": module_name}
  51. LOGGER.info(f"component register {obj.name} with cache info {module_name}")
  52. return names
  53. @classmethod
  54. def get(cls, name: str, cache) -> ComponentMeta:
  55. if cache:
  56. importlib.import_module(cache[name]["module"])
  57. else:
  58. for p in cls._components_base().glob("**/*.py"):
  59. module_name = _get_module_name_by_path(p, cls._module_base())
  60. importlib.import_module(module_name)
  61. cpn = ComponentMeta.get_meta(name)
  62. return cpn