utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. import json
  17. import platform
  18. import subprocess
  19. import contextlib
  20. from parsley import makeGrammar
  21. import lazy_paddle as paddle
  22. from ..utils.env import get_device_type
  23. from ..utils import logging
  24. PLATFORM = platform.system()
  25. def _check_call(*args, **kwargs):
  26. return subprocess.check_call(*args, **kwargs)
  27. def _check_output(*args, **kwargs):
  28. return subprocess.check_output(*args, **kwargs)
  29. def _compare_version(version1, version2):
  30. import re
  31. def parse_version(version_str):
  32. version_pattern = re.compile(
  33. r"^(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<pre_release>.*))?(?:\+(?P<build_metadata>.+))?$"
  34. )
  35. match = version_pattern.match(version_str)
  36. if not match:
  37. raise ValueError(f"Unexpected version string: {version_str}")
  38. return (
  39. int(match.group("major")),
  40. int(match.group("minor")),
  41. int(match.group("patch")),
  42. match.group("pre_release"),
  43. )
  44. v1_infos = parse_version(version1)
  45. v2_infos = parse_version(version2)
  46. for v1_info, v2_info in zip(v1_infos, v2_infos):
  47. if v1_info is None and v2_info is None:
  48. continue
  49. if v1_info is None or (v2_info is not None and v1_info < v2_info):
  50. return -1
  51. if v2_info is None or (v1_info is not None and v1_info > v2_info):
  52. return 1
  53. return 0
  54. def check_installation_using_pip(pkg):
  55. """check_installation_using_pip"""
  56. out = _check_output(["pip", "list", "--format", "json"])
  57. out = out.rstrip()
  58. lst = json.loads(out)
  59. return any(ele["name"] == pkg for ele in lst)
  60. def uninstall_package_using_pip(pkg):
  61. """uninstall_package_using_pip"""
  62. return _check_call([sys.executable, "-m", "pip", "uninstall", "-y", pkg])
  63. def install_packages_using_pip(
  64. pkgs, editable=False, req_files=None, cons_files=None, no_deps=False, pip_flags=None
  65. ):
  66. """install_packages_using_pip"""
  67. args = [sys.executable, "-m", "pip", "install"]
  68. if editable:
  69. args.append("-e")
  70. if req_files is not None:
  71. for req_file in req_files:
  72. args.append("-r")
  73. args.append(req_file)
  74. if cons_files is not None:
  75. for cons_file in cons_files:
  76. args.append("-c")
  77. args.append(cons_file)
  78. if isinstance(pkgs, str):
  79. pkgs = [pkgs]
  80. args.extend(pkgs)
  81. if pip_flags is not None:
  82. args.extend(pip_flags)
  83. return _check_call(args)
  84. def install_external_deps(repo_name, repo_root):
  85. """install paddle repository custom dependencies"""
  86. def get_gcc_version():
  87. return subprocess.check_output(["gcc", "--version"]).decode("utf-8").split()[2]
  88. if repo_name == "PaddleDetection":
  89. if os.path.exists(os.path.join(repo_root, "ppdet", "ext_op")):
  90. """Install custom op for rotated object detection"""
  91. if (
  92. PLATFORM == "Linux"
  93. and _compare_version(get_gcc_version(), "8.2.0") >= 0
  94. and "gpu" in get_device_type()
  95. and (
  96. paddle.is_compiled_with_cuda()
  97. and not paddle.is_compiled_with_rocm()
  98. )
  99. ):
  100. with switch_working_dir(os.path.join(repo_root, "ppdet", "ext_op")):
  101. args = [sys.executable, "setup.py", "install"]
  102. _check_call(args)
  103. else:
  104. logging.warning(
  105. "The custom operators in PaddleDetection for Rotated Object Detection is only supported when using CUDA, GCC>=8.2.0 and Paddle>=2.0.1, "
  106. "your environment does not meet these requirements, so we will skip the installation of custom operators under PaddleDetection/ppdet/ext_ops, "
  107. "which means you can not train the Rotated Object Detection models."
  108. )
  109. def install_deps_using_pip():
  110. """install requirements"""
  111. current_file_path = os.path.dirname(os.path.abspath(__file__))
  112. deps_path = os.path.join(current_file_path, "requirements.txt")
  113. args = [sys.executable, "-m", "pip", "install", "-r", deps_path]
  114. return _check_call(args)
  115. def clone_repo_using_git(url, branch=None):
  116. """clone_repo_using_git"""
  117. args = ["git", "clone", "--depth", "1"]
  118. if isinstance(url, str):
  119. url = [url]
  120. args.extend(url)
  121. if branch is not None:
  122. args.extend(["-b", branch])
  123. return _check_call(args)
  124. def fetch_repo_using_git(branch, url, depth=1):
  125. """fetch_repo_using_git"""
  126. args = ["git", "fetch", url, branch, "--depth", str(depth)]
  127. _check_call(args)
  128. def reset_repo_using_git(pointer, hard=True):
  129. """reset_repo_using_git"""
  130. args = ["git", "reset", "--hard", pointer]
  131. return _check_call(args)
  132. def remove_repo_using_rm(name):
  133. """remove_repo_using_rm"""
  134. if os.path.exists(name):
  135. if PLATFORM == "Windows":
  136. return _check_call(["rmdir", "/S", "/Q", name], shell=True)
  137. else:
  138. return _check_call(["rm", "-rf", name])
  139. def build_wheel_using_pip(pkg, dst_dir="./", with_deps=False, pip_flags=None):
  140. """build_wheel_using_pip"""
  141. args = [sys.executable, "-m", "pip", "wheel", "--wheel-dir", dst_dir]
  142. if not with_deps:
  143. args.append("--no-deps")
  144. if pip_flags is not None:
  145. args.extend(pip_flags)
  146. args.append(pkg)
  147. return _check_call(args)
  148. @contextlib.contextmanager
  149. def mute():
  150. """mute"""
  151. with open(os.devnull, "w") as f:
  152. with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
  153. yield
  154. @contextlib.contextmanager
  155. def switch_working_dir(new_wd):
  156. """switch_working_dir"""
  157. cwd = os.getcwd()
  158. os.chdir(new_wd)
  159. try:
  160. yield
  161. finally:
  162. os.chdir(cwd)
  163. def _build_dep_spec_pep508_grammar():
  164. # Refer to https://peps.python.org/pep-0508/
  165. grammar = """
  166. wsp = ' ' | '\t'
  167. version_cmp = wsp* <'<=' | '<' | '!=' | '==' | '>=' | '>' | '~=' | '==='>
  168. version = wsp* <(letterOrDigit | '-' | '_' | '.' | '*' | '+' | '!')+>
  169. version_one = version_cmp:op version:v wsp* -> (op, v)
  170. version_many = version_one:v1 (wsp* ',' version_one)*:v2 -> [v1] + v2
  171. versionspec = ('(' version_many:v ')' ->v) | version_many
  172. urlspec = '@' wsp* <uri_reference>
  173. marker_op = version_cmp | (wsp* 'in') | (wsp* 'not' wsp+ 'in')
  174. python_str_c = (wsp | letter | digit | '(' | ')' | '.' | '{' | '}' |
  175. '-' | '_' | '*' | '#' | ':' | ';' | ',' | '/' | '?' |
  176. '[' | ']' | '!' | '~' | '`' | '@' | '$' | '%' | '^' |
  177. '&' | '=' | '+' | '|' | '<' | '>' )
  178. dquote = '"'
  179. squote = '\\''
  180. comment = '#' <anything*>:s end -> s
  181. python_str = (squote <(python_str_c | dquote)*>:s squote |
  182. dquote <(python_str_c | squote)*>:s dquote) -> s
  183. env_var = ('python_version' | 'python_full_version' |
  184. 'os_name' | 'sys_platform' | 'platform_release' |
  185. 'platform_system' | 'platform_version' |
  186. 'platform_machine' | 'platform_python_implementation' |
  187. 'implementation_name' | 'implementation_version' |
  188. 'extra' # ONLY when defined by a containing layer
  189. )
  190. marker_var = wsp* (env_var | python_str)
  191. marker_expr = marker_var:l marker_op:o marker_var:r -> (o, l, r)
  192. | wsp* '(' marker:m wsp* ')' -> m
  193. marker_and = marker_expr:l wsp* 'and' marker_expr:r -> ('and', l, r)
  194. | marker_expr:m -> m
  195. marker_or = marker_and:l wsp* 'or' marker_and:r -> ('or', l, r)
  196. | marker_and:m -> m
  197. marker = marker_or
  198. quoted_marker = ';' wsp* marker
  199. identifier_end = letterOrDigit | (('-' | '_' | '.' )* letterOrDigit)
  200. identifier = <letterOrDigit identifier_end* >
  201. name = identifier
  202. extras_list = identifier:i (wsp* ',' wsp* identifier)*:ids -> [i] + ids
  203. extras = '[' wsp* extras_list?:e wsp* ']' -> e
  204. name_req = (name:n wsp* extras?:e wsp* versionspec?:v wsp* quoted_marker?:m
  205. -> (n, e or [], v or [], m))
  206. url_req = (name:n wsp* extras?:e wsp* urlspec:v (wsp+ | end) quoted_marker?:m
  207. -> (n, e or [], v, m))
  208. specification = wsp* (url_req | name_req):s wsp* comment? -> s
  209. # The result is a tuple - name, list-of-extras,
  210. # list-of-version-constraints-or-a-url, marker-ast or None
  211. uri_reference = <uri | relative_ref>
  212. uri = scheme ':' hier_part ('?' query )? ('#' fragment)?
  213. hier_part = ('//' authority path_abempty) | path_absolute | path_rootless | path_empty
  214. absolute_uri = scheme ':' hier_part ('?' query )?
  215. relative_ref = relative_part ('?' query )? ('#' fragment )?
  216. relative_part = '//' authority path_abempty | path_absolute | path_noscheme | path_empty
  217. scheme = letter (letter | digit | '+' | '-' | '.')*
  218. authority = (userinfo '@' )? host (':' port )?
  219. userinfo = (unreserved | pct_encoded | sub_delims | ':')*
  220. host = ip_literal | ipv4_address | reg_name
  221. port = digit*
  222. ip_literal = '[' (ipv6_address | ipvfuture) ']'
  223. ipvfuture = 'v' hexdig+ '.' (unreserved | sub_delims | ':')+
  224. ipv6_address = (
  225. (h16 ':'){6} ls32
  226. | '::' (h16 ':'){5} ls32
  227. | (h16 )? '::' (h16 ':'){4} ls32
  228. | ((h16 ':')? h16 )? '::' (h16 ':'){3} ls32
  229. | ((h16 ':'){0,2} h16 )? '::' (h16 ':'){2} ls32
  230. | ((h16 ':'){0,3} h16 )? '::' h16 ':' ls32
  231. | ((h16 ':'){0,4} h16 )? '::' ls32
  232. | ((h16 ':'){0,5} h16 )? '::' h16
  233. | ((h16 ':'){0,6} h16 )? '::' )
  234. h16 = hexdig{1,4}
  235. ls32 = (h16 ':' h16) | ipv4_address
  236. ipv4_address = dec_octet '.' dec_octet '.' dec_octet '.' dec_octet
  237. nz = ~'0' digit
  238. dec_octet = (
  239. digit # 0-9
  240. | nz digit # 10-99
  241. | '1' digit{2} # 100-199
  242. | '2' ('0' | '1' | '2' | '3' | '4') digit # 200-249
  243. | '25' ('0' | '1' | '2' | '3' | '4' | '5') )# %250-255
  244. reg_name = (unreserved | pct_encoded | sub_delims)*
  245. path = (
  246. path_abempty # begins with '/' or is empty
  247. | path_absolute # begins with '/' but not '//'
  248. | path_noscheme # begins with a non-colon segment
  249. | path_rootless # begins with a segment
  250. | path_empty ) # zero characters
  251. path_abempty = ('/' segment)*
  252. path_absolute = '/' (segment_nz ('/' segment)* )?
  253. path_noscheme = segment_nz_nc ('/' segment)*
  254. path_rootless = segment_nz ('/' segment)*
  255. path_empty = pchar{0}
  256. segment = pchar*
  257. segment_nz = pchar+
  258. segment_nz_nc = (unreserved | pct_encoded | sub_delims | '@')+
  259. # non-zero-length segment without any colon ':'
  260. pchar = unreserved | pct_encoded | sub_delims | ':' | '@'
  261. query = (pchar | '/' | '?')*
  262. fragment = (pchar | '/' | '?')*
  263. pct_encoded = '%' hexdig
  264. unreserved = letter | digit | '-' | '.' | '_' | '~'
  265. reserved = gen_delims | sub_delims
  266. gen_delims = ':' | '/' | '?' | '#' | '(' | ')?' | '@'
  267. sub_delims = '!' | '$' | '&' | '\\'' | '(' | ')' | '*' | '+' | ',' | ';' | '='
  268. hexdig = digit | 'a' | 'A' | 'b' | 'B' | 'c' | 'C' | 'd' | 'D' | 'e' | 'E' | 'f' | 'F'
  269. """
  270. compiled = makeGrammar(grammar, {})
  271. return compiled
  272. _pep508_grammar = None
  273. def to_dep_spec_pep508(s):
  274. """to_dep_spec_pep508"""
  275. global _pep508_grammar
  276. if _pep508_grammar is None:
  277. _pep508_grammar = _build_dep_spec_pep508_grammar()
  278. parsed = _pep508_grammar(s)
  279. return parsed.specification()
  280. def env_marker_ast2expr(marker_ast):
  281. """env_marker_ast2expr"""
  282. MARKER_VARS = (
  283. "python_version",
  284. "python_full_version",
  285. "os_name",
  286. "sys_platform",
  287. "platform_release",
  288. "platform_system",
  289. "platform_version",
  290. "platform_machine",
  291. "platform_python_implementation",
  292. "implementation_name",
  293. "implementation_version",
  294. "extra", # ONLY when defined by a containing layer
  295. )
  296. o, l, r = marker_ast
  297. if isinstance(l, tuple):
  298. l = env_marker_ast2expr(l)
  299. else:
  300. assert isinstance(l, str)
  301. if l not in MARKER_VARS:
  302. l = repr(l)
  303. if isinstance(r, tuple):
  304. r = env_marker_ast2expr(r)
  305. else:
  306. assert isinstance(r, str)
  307. if r not in MARKER_VARS:
  308. r = repr(r)
  309. return f"{l} {o} {r}"