core.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 os
  15. import sys
  16. from collections import OrderedDict
  17. from ..utils import logging
  18. from .utils import install_deps_using_pip
  19. from .meta import get_all_repo_names, get_repo_meta
  20. from .repo import (
  21. build_repo_instance,
  22. build_repo_group_getter,
  23. build_repo_group_installer,
  24. )
  25. __all__ = [
  26. "set_parent_dirs",
  27. "setup",
  28. "wheel",
  29. "is_initialized",
  30. "initialize",
  31. "get_versions",
  32. ]
  33. def _parse_repo_deps(repos):
  34. ret = []
  35. for repo_name in repos:
  36. repo_meta = get_repo_meta(repo_name)
  37. ret.extend(_parse_repo_deps(repo_meta.get("requires", [])))
  38. ret.append(repo_name)
  39. return ret
  40. class _GlobalContext(object):
  41. REPO_PARENT_DIR = None
  42. PDX_COLLECTION_MOD = None
  43. REPOS = None
  44. @classmethod
  45. def set_parent_dirs(cls, repo_parent_dir, pdx_collection_mod):
  46. """set_parent_dirs"""
  47. cls.REPO_PARENT_DIR = repo_parent_dir
  48. cls.PDX_COLLECTION_MOD = pdx_collection_mod
  49. @classmethod
  50. def build_repo_instance(cls, repo_name):
  51. """build_repo_instance"""
  52. return build_repo_instance(
  53. repo_name, cls.REPO_PARENT_DIR, cls.PDX_COLLECTION_MOD
  54. )
  55. @classmethod
  56. def is_initialized(cls):
  57. """is_initialized"""
  58. return cls.REPOS is not None
  59. @classmethod
  60. def initialize(cls):
  61. """initialize"""
  62. cls.REPOS = []
  63. @classmethod
  64. def add_repo(cls, repo):
  65. """add_repo"""
  66. if not cls.is_initialized():
  67. cls.initialize()
  68. cls.REPOS.append(repo)
  69. @classmethod
  70. def add_repos(cls, repos):
  71. """add_repos"""
  72. if len(repos) == 0 and not cls.is_initialized():
  73. cls.initialize()
  74. for repo in repos:
  75. cls.add_repo(repo)
  76. set_parent_dirs = _GlobalContext.set_parent_dirs
  77. is_initialized = _GlobalContext.is_initialized
  78. def setup(
  79. repo_names,
  80. no_deps=False,
  81. constraints=None,
  82. platform=None,
  83. update_repos=False,
  84. use_local_repos=False,
  85. deps_to_replace=None,
  86. ):
  87. """setup"""
  88. if update_repos and use_local_repos:
  89. logging.error(
  90. f"The `--update_repos` and `--use_local_repos` should not be True at the same time. They are global setting for all repos. `--update_repos` means that update all repos to sync with remote, and `--use_local_repos` means that don't update when local repo is exsting."
  91. )
  92. raise Exception()
  93. repo_names = list(set(_parse_repo_deps(repo_names)))
  94. repos = []
  95. for repo_name in repo_names:
  96. repo = _GlobalContext.build_repo_instance(repo_name)
  97. repos.append(repo)
  98. changed_repos = []
  99. repos_to_get = []
  100. for repo in repos:
  101. repo_name = repo.name
  102. if repo.check_repo_exiting():
  103. if use_local_repos:
  104. # when use_local_repos has been set, it can be only assume that the local repo has changed, otherwise there is no need to specify.
  105. changed_repos.append(repo_name)
  106. logging.warning(
  107. f"We will use the existing repo of {repo.name} and the repo will be reinstall."
  108. )
  109. continue
  110. logging.warning(f"Existing of {repo.name} repo.")
  111. if update_repos:
  112. remove_existing = True
  113. else:
  114. if sys.stdin.isatty():
  115. logging.warning("Should we remove it (y/n)?")
  116. try:
  117. remove_existing = input()
  118. except EOFError:
  119. logging.warning(
  120. "Unable to read from stdin. Please set `--use_local_repos` to \
  121. True or False to apply a global setting for using exsting or re-getting repos."
  122. )
  123. raise
  124. remove_existing = remove_existing.lower() in ("y", "yes")
  125. if remove_existing:
  126. changed_repos.append(repo_name)
  127. repo.remove()
  128. logging.warning(f"Existing {repo.name} repo has been removed.")
  129. repos_to_get.append(repo)
  130. else:
  131. logging.warning(f"We will use the existing repo of {repo.name}.")
  132. else:
  133. changed_repos.append(repo)
  134. repos_to_get.append(repo)
  135. repos_to_install = []
  136. for repo in repos:
  137. repo_name = repo.name
  138. if repo.check_installation():
  139. logging.warning(f"Existing installation of {repo.name} detected.")
  140. reinstall = repo_name in changed_repos
  141. if reinstall:
  142. uninstall_existing = True
  143. else:
  144. if sys.stdin.isatty():
  145. logging.warning("Should we uninstall it (y/n)?")
  146. try:
  147. uninstall_existing = input()
  148. except EOFError:
  149. logging.warning(
  150. "Unable to read from stdin. Please set `reinstall` to \
  151. True or False to apply a global setting for reinstalling repos."
  152. )
  153. raise
  154. uninstall_existing = uninstall_existing.lower() in ("y", "yes")
  155. if uninstall_existing:
  156. repo.uninstall()
  157. repos_to_install.append(repo)
  158. else:
  159. logging.warning(
  160. f"We will use the existing installation of {repo.name}."
  161. )
  162. else:
  163. repos_to_install.append(repo)
  164. getter = build_repo_group_getter(*repos_to_get)
  165. installer = build_repo_group_installer(*repos_to_install)
  166. if len(repos_to_get) > 0:
  167. logging.info(
  168. f"Now download and update the repos: {list(repo.name for repo in repos_to_get)}."
  169. )
  170. getter.get(force=True, platform=platform)
  171. logging.info("All repos are existing.")
  172. else:
  173. logging.info("No repo need to download or update.")
  174. if not no_deps:
  175. logging.info("Dependencies are listed below:")
  176. logging.info(installer.get_deps())
  177. logging.info("Now installing the packages...")
  178. installer.install(
  179. force_reinstall=False,
  180. no_deps=no_deps,
  181. constraints=constraints,
  182. deps_to_replace=deps_to_replace,
  183. )
  184. install_deps_using_pip()
  185. logging.info("All packages are installed.")
  186. def wheel(repo_names, dst_dir="./", fail_fast=False):
  187. """wheel"""
  188. for repo_name in repo_names:
  189. repo = _GlobalContext.build_repo_instance(repo_name)
  190. logging.info(f"Now building Wheel for {repo_name}...")
  191. try:
  192. tgt_dir = os.path.join(dst_dir, repo.pkg_name)
  193. if os.path.exists(tgt_dir):
  194. raise FileExistsError(f"{tgt_dir} already exists.")
  195. repo.wheel(tgt_dir)
  196. except Exception as e:
  197. logging.warning(
  198. f"Failed to build wheel for {repo_name}. We encountered the following error:\n {str(e)}\n"
  199. )
  200. if fail_fast:
  201. raise
  202. else:
  203. logging.info(f"Wheel for {repo_name} is built.\n")
  204. def initialize(repo_names=None):
  205. """initialize"""
  206. if _GlobalContext.is_initialized():
  207. raise RuntimeError(
  208. "PDX has already been initialized. Reinitialization is not supported."
  209. )
  210. if repo_names is None:
  211. try_all = True
  212. repo_names = get_all_repo_names()
  213. else:
  214. try_all = False
  215. repos = []
  216. for repo_name in repo_names:
  217. logging.debug(f"Now initializing {repo_name}...")
  218. repo = _GlobalContext.build_repo_instance(repo_name)
  219. flag = repo.initialize()
  220. if flag:
  221. logging.debug(f"{repo_name} is initialized.")
  222. repos.append(repo)
  223. else:
  224. if try_all:
  225. logging.debug(
  226. f"Failed to initialize {repo_name}. Please make sure {repo_name} is properly installed."
  227. )
  228. else:
  229. pass
  230. _GlobalContext.add_repos(repos)
  231. def get_versions(repo_names=None):
  232. """get_versions"""
  233. if repo_names is None:
  234. repo_names = get_all_repo_names()
  235. name2versions = OrderedDict()
  236. for repo_name in repo_names:
  237. repo = _GlobalContext.build_repo_instance(repo_name)
  238. versions = repo.get_version()
  239. name2versions[repo_name] = versions
  240. return name2versions