deps.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # Copyright (c) 2024 PaddlePaddle Authors. 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, software
  10. # 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. import importlib.metadata
  15. import importlib.util
  16. import inspect
  17. import re
  18. from collections import defaultdict
  19. from functools import lru_cache, wraps
  20. from packaging.requirements import Requirement
  21. from . import logging
  22. _EXTRA_PATTERN = re.compile(
  23. r"(?:;|and)*[ \t]*extra[ \t]*==[ \t]*['\"]([a-z0-9]+(?:-[a-z0-9]+)*)['\"]"
  24. )
  25. _COLLECTIVE_EXTRA_NAMES = {"base", "plugins", "all"}
  26. def _get_extra_name_and_remove_extra_marker(dep_spec):
  27. # XXX: Not sure if this is correct
  28. m = _EXTRA_PATTERN.search(dep_spec)
  29. if m:
  30. return m.group(1), dep_spec[: m.start()] + dep_spec[m.end() :]
  31. else:
  32. return None, dep_spec
  33. def get_extras():
  34. metadata = importlib.metadata.metadata("paddlex")
  35. extras = {}
  36. # XXX: The `metadata.get_all` used here is not well documented.
  37. for name in metadata.get_all("Provides-Extra", []):
  38. if name not in _COLLECTIVE_EXTRA_NAMES:
  39. extras[name] = defaultdict(list)
  40. for dep_spec in importlib.metadata.requires("paddlex"):
  41. extra_name, dep_spec = _get_extra_name_and_remove_extra_marker(dep_spec)
  42. if extra_name is not None and extra_name not in _COLLECTIVE_EXTRA_NAMES:
  43. dep_spec = dep_spec.rstrip()
  44. req = Requirement(dep_spec)
  45. assert extra_name in extras, extra_name
  46. extras[extra_name][req.name].append(dep_spec)
  47. return extras
  48. EXTRAS = get_extras()
  49. def get_dep_specs():
  50. dep_specs = []
  51. for dep_spec in importlib.metadata.requires("paddlex"):
  52. extra_name, dep_spec = _get_extra_name_and_remove_extra_marker(dep_spec)
  53. if extra_name is None or extra_name == "all":
  54. dep_spec = dep_spec.rstrip()
  55. dep_specs.append(dep_spec)
  56. return dep_specs
  57. DEP_SPECS = get_dep_specs()
  58. def get_dep_version(dep):
  59. try:
  60. return importlib.metadata.version(dep)
  61. except importlib.metadata.PackageNotFoundError:
  62. return None
  63. @lru_cache()
  64. def is_dep_available(dep, /):
  65. # Currently for several special deps we check if the import packages exist.
  66. if dep == "paddlepaddle":
  67. return importlib.util.find_spec("paddle") is not None
  68. elif dep == "paddle-custom-device":
  69. return importlib.util.find_spec("paddle_custom_device") is not None
  70. elif dep == "ultra-infer":
  71. return importlib.util.find_spec("ultra_infer") is not None
  72. return get_dep_version(dep) is not None
  73. def require_deps(*deps, obj_name=None):
  74. unavailable_deps = [dep for dep in deps if not is_dep_available(dep)]
  75. if len(unavailable_deps) > 0:
  76. if obj_name is not None:
  77. msg = f"`{obj_name}` is not ready for use, because the"
  78. else:
  79. msg = "The"
  80. msg += " following dependencies are not available:\n" + "\n".join(
  81. unavailable_deps
  82. )
  83. raise RuntimeError(msg)
  84. def function_requires_deps(*deps):
  85. def _deco(func):
  86. @wraps(func)
  87. def _wrapper(*args, **kwargs):
  88. require_deps(*func._deps_, obj_name=func.__name__)
  89. return func(*args, **kwargs)
  90. func._deps_ = set(deps)
  91. return _wrapper
  92. return _deco
  93. def class_requires_deps(*deps):
  94. def _deco(cls):
  95. @wraps(cls.__init__)
  96. def _wrapper(self, *args, **kwargs):
  97. require_deps(*cls._deps_, obj_name=cls.__name__)
  98. return old_init_func(self, *args, **kwargs)
  99. cls._deps_ = set(deps)
  100. for base_cls in inspect.getmro(cls)[1:-1]:
  101. if hasattr(base_cls, "_deps_"):
  102. cls._deps_.update(base_cls._deps_)
  103. if "__init__" in cls.__dict__:
  104. old_init_func = cls.__init__
  105. else:
  106. def _forward(self, *args, **kwargs):
  107. return super(cls, self).__init__(*args, **kwargs)
  108. old_init_func = _forward
  109. cls.__init__ = _wrapper
  110. return cls
  111. return _deco
  112. @lru_cache()
  113. def is_extra_available(extra):
  114. flags = [is_dep_available(dep) for dep in EXTRAS[extra]]
  115. if all(flags):
  116. return True
  117. logging.debug(
  118. "These dependencies are not available: %s",
  119. [d for d, f in zip(EXTRAS[extra], flags) if not f],
  120. )
  121. return False
  122. def require_extra(extra, *, obj_name=None):
  123. if not is_extra_available(extra):
  124. if obj_name is not None:
  125. msg = f"`{obj_name}` requires additional dependencies."
  126. else:
  127. msg = "Additional dependencies are required."
  128. msg += f" To install them, run `pip install paddlex[{extra}]==<PADDLEX_VERSION>` if you’re installing `paddlex` from an index, or `pip install -e /path/to/PaddleX[{extra}]` if you’re installing `paddlex` locally."
  129. raise RuntimeError(msg)
  130. def pipeline_requires_extra(extra):
  131. def _deco(pipeline_cls):
  132. @wraps(pipeline_cls.__init__)
  133. def _wrapper(self, *args, **kwargs):
  134. require_extra(extra, obj_name=pipeline_name)
  135. return old_init_func(self, *args, **kwargs)
  136. old_init_func = pipeline_cls.__init__
  137. pipeline_name = pipeline_cls.entities
  138. if isinstance(pipeline_name, list):
  139. assert len(pipeline_name) == 1, pipeline_name
  140. pipeline_name = pipeline_name[0]
  141. pipeline_cls.__init__ = _wrapper
  142. return pipeline_cls
  143. return _deco
  144. def is_hpip_available():
  145. return is_dep_available("ultra-infer")
  146. def require_hpip():
  147. if not is_hpip_available():
  148. raise RuntimeError(
  149. "The high-performance inference plugin is not available. Please install it properly."
  150. )
  151. def is_serving_plugin_available():
  152. return is_extra_available("serving")
  153. def require_serving_plugin():
  154. if not is_serving_plugin_available():
  155. raise RuntimeError(
  156. "The serving plugin is not available. Please install it properly."
  157. )
  158. def get_serving_dep_specs():
  159. dep_specs = []
  160. for item in EXTRAS["serving"].values():
  161. dep_specs += item
  162. return dep_specs
  163. def is_paddle2onnx_plugin_available():
  164. return is_dep_available("paddle2onnx")
  165. def require_paddle2onnx_plugin():
  166. if not is_paddle2onnx_plugin_available():
  167. raise RuntimeError(
  168. "The Paddle2ONNX plugin is not available. Please install it properly."
  169. )
  170. def get_paddle2onnx_spec():
  171. return "paddle2onnx == 2.0.0a2"