deps.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 re
  16. from collections import defaultdict
  17. from packaging.requirements import Requirement
  18. _EXTRA_PATTERN = re.compile(
  19. r"(?:;|and)*[ \t]*extra[ \t]*==[ \t]*['\"]([a-z0-9]+(?:-[a-z0-9]+)*)['\"]"
  20. )
  21. _EXTRA_NAMES_TO_EXCLUDE = {"base", "plugins"}
  22. def _get_extra_name_and_remove_extra_marker(dep_spec):
  23. # XXX: Not sure if this is correct
  24. m = _EXTRA_PATTERN.search(dep_spec)
  25. if m:
  26. return m.group(1), dep_spec[: m.start()] + dep_spec[m.end() :]
  27. else:
  28. return None, dep_spec
  29. def get_package_version(package_name):
  30. try:
  31. return importlib.metadata.version(package_name)
  32. except importlib.metadata.PackageNotFoundError:
  33. return None
  34. def get_extras():
  35. metadata = importlib.metadata.metadata("paddlex")
  36. extras = {}
  37. # XXX: The `metadata.get_all` used here is not well documented.
  38. for name in metadata.get_all("Provides-Extra", []):
  39. if name not in _EXTRA_NAMES_TO_EXCLUDE:
  40. extras[name] = defaultdict(list)
  41. for dep_spec in importlib.metadata.requires("paddlex"):
  42. extra_name, dep_spec = _get_extra_name_and_remove_extra_marker(dep_spec)
  43. if extra_name is not None and extra_name not in _EXTRA_NAMES_TO_EXCLUDE:
  44. dep_spec = dep_spec.rstrip()
  45. req = Requirement(dep_spec)
  46. assert extra_name in extras, extra_name
  47. extras[extra_name][req.name].append(dep_spec)
  48. return extras
  49. EXTRAS = get_extras()