core.py 8.7 KB

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