utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 contextlib
  15. import json
  16. import os
  17. import platform
  18. import subprocess
  19. import sys
  20. import lazy_paddle as paddle
  21. from parsley import makeGrammar
  22. from ..utils import logging
  23. from ..utils.env import get_device_type
  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 clone_repo_using_git(url, branch=None):
  110. """clone_repo_using_git"""
  111. args = ["git", "clone", "--depth", "1"]
  112. if isinstance(url, str):
  113. url = [url]
  114. args.extend(url)
  115. if branch is not None:
  116. args.extend(["-b", branch])
  117. return _check_call(args)
  118. def fetch_repo_using_git(branch, url, depth=1):
  119. """fetch_repo_using_git"""
  120. args = ["git", "fetch", url, branch, "--depth", str(depth)]
  121. _check_call(args)
  122. def reset_repo_using_git(pointer, hard=True):
  123. """reset_repo_using_git"""
  124. args = ["git", "reset", "--hard", pointer]
  125. return _check_call(args)
  126. def remove_repo_using_rm(name):
  127. """remove_repo_using_rm"""
  128. if os.path.exists(name):
  129. if PLATFORM == "Windows":
  130. return _check_call(["rmdir", "/S", "/Q", name], shell=True)
  131. else:
  132. return _check_call(["rm", "-rf", name])
  133. def build_wheel_using_pip(pkg, dst_dir="./", with_deps=False, pip_flags=None):
  134. """build_wheel_using_pip"""
  135. args = [sys.executable, "-m", "pip", "wheel", "--wheel-dir", dst_dir]
  136. if not with_deps:
  137. args.append("--no-deps")
  138. if pip_flags is not None:
  139. args.extend(pip_flags)
  140. args.append(pkg)
  141. return _check_call(args)
  142. @contextlib.contextmanager
  143. def mute():
  144. """mute"""
  145. with open(os.devnull, "w") as f:
  146. with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
  147. yield
  148. @contextlib.contextmanager
  149. def switch_working_dir(new_wd):
  150. """switch_working_dir"""
  151. cwd = os.getcwd()
  152. os.chdir(new_wd)
  153. try:
  154. yield
  155. finally:
  156. os.chdir(cwd)
  157. def _build_dep_spec_pep508_grammar():
  158. # Refer to https://peps.python.org/pep-0508/
  159. grammar = """
  160. wsp = ' ' | '\t'
  161. version_cmp = wsp* <'<=' | '<' | '!=' | '==' | '>=' | '>' | '~=' | '==='>
  162. version = wsp* <(letterOrDigit | '-' | '_' | '.' | '*' | '+' | '!')+>
  163. version_one = version_cmp:op version:v wsp* -> (op, v)
  164. version_many = version_one:v1 (wsp* ',' version_one)*:v2 -> [v1] + v2
  165. versionspec = ('(' version_many:v ')' ->v) | version_many
  166. urlspec = '@' wsp* <uri_reference>
  167. marker_op = version_cmp | (wsp* 'in') | (wsp* 'not' wsp+ 'in')
  168. python_str_c = (wsp | letter | digit | '(' | ')' | '.' | '{' | '}' |
  169. '-' | '_' | '*' | '#' | ':' | ';' | ',' | '/' | '?' |
  170. '[' | ']' | '!' | '~' | '`' | '@' | '$' | '%' | '^' |
  171. '&' | '=' | '+' | '|' | '<' | '>' )
  172. dquote = '"'
  173. squote = '\\''
  174. comment = '#' <anything*>:s end -> s
  175. python_str = (squote <(python_str_c | dquote)*>:s squote |
  176. dquote <(python_str_c | squote)*>:s dquote) -> s
  177. env_var = ('python_version' | 'python_full_version' |
  178. 'os_name' | 'sys_platform' | 'platform_release' |
  179. 'platform_system' | 'platform_version' |
  180. 'platform_machine' | 'platform_python_implementation' |
  181. 'implementation_name' | 'implementation_version' |
  182. 'extra' # ONLY when defined by a containing layer
  183. )
  184. marker_var = wsp* (env_var | python_str)
  185. marker_expr = marker_var:l marker_op:o marker_var:r -> (o, l, r)
  186. | wsp* '(' marker:m wsp* ')' -> m
  187. marker_and = marker_expr:l wsp* 'and' marker_expr:r -> ('and', l, r)
  188. | marker_expr:m -> m
  189. marker_or = marker_and:l wsp* 'or' marker_and:r -> ('or', l, r)
  190. | marker_and:m -> m
  191. marker = marker_or
  192. quoted_marker = ';' wsp* marker
  193. identifier_end = letterOrDigit | (('-' | '_' | '.' )* letterOrDigit)
  194. identifier = <letterOrDigit identifier_end* >
  195. name = identifier
  196. extras_list = identifier:i (wsp* ',' wsp* identifier)*:ids -> [i] + ids
  197. extras = '[' wsp* extras_list?:e wsp* ']' -> e
  198. name_req = (name:n wsp* extras?:e wsp* versionspec?:v wsp* quoted_marker?:m
  199. -> (n, e or [], v or [], m))
  200. url_req = (name:n wsp* extras?:e wsp* urlspec:v (wsp+ | end) quoted_marker?:m
  201. -> (n, e or [], v, m))
  202. specification = wsp* (url_req | name_req):s wsp* comment? -> s
  203. # The result is a tuple - name, list-of-extras,
  204. # list-of-version-constraints-or-a-url, marker-ast or None
  205. uri_reference = <uri | relative_ref>
  206. uri = scheme ':' hier_part ('?' query )? ('#' fragment)?
  207. hier_part = ('//' authority path_abempty) | path_absolute | path_rootless | path_empty
  208. absolute_uri = scheme ':' hier_part ('?' query )?
  209. relative_ref = relative_part ('?' query )? ('#' fragment )?
  210. relative_part = '//' authority path_abempty | path_absolute | path_noscheme | path_empty
  211. scheme = letter (letter | digit | '+' | '-' | '.')*
  212. authority = (userinfo '@' )? host (':' port )?
  213. userinfo = (unreserved | pct_encoded | sub_delims | ':')*
  214. host = ip_literal | ipv4_address | reg_name
  215. port = digit*
  216. ip_literal = '[' (ipv6_address | ipvfuture) ']'
  217. ipvfuture = 'v' hexdig+ '.' (unreserved | sub_delims | ':')+
  218. ipv6_address = (
  219. (h16 ':'){6} ls32
  220. | '::' (h16 ':'){5} ls32
  221. | (h16 )? '::' (h16 ':'){4} ls32
  222. | ((h16 ':')? h16 )? '::' (h16 ':'){3} ls32
  223. | ((h16 ':'){0,2} h16 )? '::' (h16 ':'){2} ls32
  224. | ((h16 ':'){0,3} h16 )? '::' h16 ':' ls32
  225. | ((h16 ':'){0,4} h16 )? '::' ls32
  226. | ((h16 ':'){0,5} h16 )? '::' h16
  227. | ((h16 ':'){0,6} h16 )? '::' )
  228. h16 = hexdig{1,4}
  229. ls32 = (h16 ':' h16) | ipv4_address
  230. ipv4_address = dec_octet '.' dec_octet '.' dec_octet '.' dec_octet
  231. nz = ~'0' digit
  232. dec_octet = (
  233. digit # 0-9
  234. | nz digit # 10-99
  235. | '1' digit{2} # 100-199
  236. | '2' ('0' | '1' | '2' | '3' | '4') digit # 200-249
  237. | '25' ('0' | '1' | '2' | '3' | '4' | '5') )# %250-255
  238. reg_name = (unreserved | pct_encoded | sub_delims)*
  239. path = (
  240. path_abempty # begins with '/' or is empty
  241. | path_absolute # begins with '/' but not '//'
  242. | path_noscheme # begins with a non-colon segment
  243. | path_rootless # begins with a segment
  244. | path_empty ) # zero characters
  245. path_abempty = ('/' segment)*
  246. path_absolute = '/' (segment_nz ('/' segment)* )?
  247. path_noscheme = segment_nz_nc ('/' segment)*
  248. path_rootless = segment_nz ('/' segment)*
  249. path_empty = pchar{0}
  250. segment = pchar*
  251. segment_nz = pchar+
  252. segment_nz_nc = (unreserved | pct_encoded | sub_delims | '@')+
  253. # non-zero-length segment without any colon ':'
  254. pchar = unreserved | pct_encoded | sub_delims | ':' | '@'
  255. query = (pchar | '/' | '?')*
  256. fragment = (pchar | '/' | '?')*
  257. pct_encoded = '%' hexdig
  258. unreserved = letter | digit | '-' | '.' | '_' | '~'
  259. reserved = gen_delims | sub_delims
  260. gen_delims = ':' | '/' | '?' | '#' | '(' | ')?' | '@'
  261. sub_delims = '!' | '$' | '&' | '\\'' | '(' | ')' | '*' | '+' | ',' | ';' | '='
  262. hexdig = digit | 'a' | 'A' | 'b' | 'B' | 'c' | 'C' | 'd' | 'D' | 'e' | 'E' | 'f' | 'F'
  263. """
  264. compiled = makeGrammar(grammar, {})
  265. return compiled
  266. _pep508_grammar = None
  267. def to_dep_spec_pep508(s):
  268. """to_dep_spec_pep508"""
  269. global _pep508_grammar
  270. if _pep508_grammar is None:
  271. _pep508_grammar = _build_dep_spec_pep508_grammar()
  272. parsed = _pep508_grammar(s)
  273. return parsed.specification()
  274. def env_marker_ast2expr(marker_ast):
  275. """env_marker_ast2expr"""
  276. MARKER_VARS = (
  277. "python_version",
  278. "python_full_version",
  279. "os_name",
  280. "sys_platform",
  281. "platform_release",
  282. "platform_system",
  283. "platform_version",
  284. "platform_machine",
  285. "platform_python_implementation",
  286. "implementation_name",
  287. "implementation_version",
  288. "extra", # ONLY when defined by a containing layer
  289. )
  290. o, l, r = marker_ast
  291. if isinstance(l, tuple):
  292. l = env_marker_ast2expr(l)
  293. else:
  294. assert isinstance(l, str)
  295. if l not in MARKER_VARS:
  296. l = repr(l)
  297. if isinstance(r, tuple):
  298. r = env_marker_ast2expr(r)
  299. else:
  300. assert isinstance(r, str)
  301. if r not in MARKER_VARS:
  302. r = repr(r)
  303. return f"{l} {o} {r}"