check_imports.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. # TODO: Less verbose
  15. import ast
  16. import pathlib
  17. import re
  18. import sys
  19. import traceback
  20. from collections import deque
  21. from stdlib_list import stdlib_list
  22. sys.path.append(str(pathlib.Path(__file__).parent.parent))
  23. from setup import DEP_SPECS, REQUIRED_DEPS
  24. # NOTE: We do not use `importlib.metadata.packages_distributions` here because
  25. # 1. It is supported only in Python 3.10+.
  26. # 2. It requires the packages to be installed, but we are doing a static check.
  27. MOD_TO_DEP = {
  28. "aiohttp": "aiohttp",
  29. "baidubce": "bce-python-sdk",
  30. "chardet": "chardet",
  31. "chinese_calendar": "chinese-calendar",
  32. "colorlog": "colorlog",
  33. "decord": "decord",
  34. "einops": "einops",
  35. "faiss": "faiss-cpu",
  36. "fastapi": "fastapi",
  37. "filelock": "filelock",
  38. "filetype": "filetype",
  39. "ftfy": "ftfy",
  40. "GPUtil": "GPUtil",
  41. "imagesize": "imagesize",
  42. "jinja2": "Jinja2",
  43. "joblib": "joblib",
  44. "langchain": "langchain",
  45. "langchain_community": "langchain-community",
  46. "langchain_core": "langchain-core",
  47. "langchain_openai": "langchain-openai",
  48. "lxml": "lxml",
  49. "matplotlib": "matplotlib",
  50. "numpy": "numpy",
  51. "openai": "openai",
  52. "cv2": "opencv-contrib-python",
  53. "openpyxl": "openpyxl",
  54. "packaging": "packaging",
  55. "pandas": "pandas",
  56. "PIL": "pillow",
  57. "premailer": "premailer",
  58. "prettytable": "prettytable",
  59. "cpuinfo": "py-cpuinfo",
  60. "pyclipper": "pyclipper",
  61. "pycocotools": "pycocotools",
  62. "pydantic": "pydantic",
  63. "fitz": "PyMuPDF",
  64. "yaml": "PyYAML",
  65. "regex": "regex",
  66. "requests": "requests",
  67. "ruamel.yaml": "ruamel.yaml",
  68. "skimage": "scikit-image",
  69. "sklearn": "scikit-learn",
  70. "shapely": "shapely",
  71. "soundfile": "soundfile",
  72. "starlette": "starlette",
  73. "tokenizers": "tokenizers",
  74. "tqdm": "tqdm",
  75. "typing_extensions": "typing-extensions",
  76. "ujson": "ujson",
  77. "uvicorn": "uvicorn",
  78. "yarl": "yarl",
  79. }
  80. assert (
  81. set(MOD_TO_DEP.values()) == DEP_SPECS.keys()
  82. ), f"`MOD_TO_DEP` should be updated to match `DEP_SPECS`. Symmetric difference: {set(MOD_TO_DEP.values()) ^ DEP_SPECS.keys()}"
  83. MOD_PATTERN = re.compile(
  84. rf"^(?:{'|'.join([re.escape(mod) for mod in MOD_TO_DEP])})(?=\.|$)"
  85. )
  86. STDLIB_MODS = set(stdlib_list())
  87. SPECIAL_KNOWN_MODS = {
  88. "paddle",
  89. "paddleseg",
  90. "paddleclas",
  91. "paddledet",
  92. "paddlets",
  93. "paddlenlp",
  94. "paddlespeech",
  95. "parl",
  96. "paddlemix",
  97. "paddle3d",
  98. "paddlevideo",
  99. }
  100. MANUALLY_MANAGED_OPTIONAL_HEAVY_MODS = {"paddle_custom_device", "ultra_infer"}
  101. def check(file_path):
  102. # TODO:
  103. # 1. Handle more cases, e.g., `from ruamel import yaml`.
  104. # 2. Find unused dependencies.
  105. # 3. Better output format.
  106. with open(file_path, "r", encoding="utf-8") as f:
  107. file_contents = f.read()
  108. try:
  109. tree = ast.parse(file_contents)
  110. except Exception:
  111. print(
  112. f"Failed to parse the source code in `{file_path}` into an AST node:\n{traceback.format_exc()}"
  113. )
  114. return False
  115. # 1. Never import unknown modules
  116. # 2. Don't import optional third-party modules at the top level
  117. unknown_modules_found = False
  118. top_level_imports_found = False
  119. q = deque()
  120. for child in ast.iter_child_nodes(tree):
  121. q.append((child, 1))
  122. while q:
  123. node, level = q.popleft()
  124. mods = set()
  125. if isinstance(node, ast.Import):
  126. for alias in node.names:
  127. mod = alias.name
  128. mods.add(mod)
  129. elif isinstance(node, ast.ImportFrom):
  130. if node.module and node.level == 0:
  131. mod = node.module
  132. mods.add(mod)
  133. for mod in mods:
  134. pos = f"{file_path}:{node.lineno}:{node.col_offset}"
  135. tl = mod.split(".")[0]
  136. if tl == "paddlex" or tl in SPECIAL_KNOWN_MODS or tl in STDLIB_MODS:
  137. continue
  138. elif tl in MANUALLY_MANAGED_OPTIONAL_HEAVY_MODS:
  139. if level == 1:
  140. print(
  141. f"{pos}: Module of a manually managed heavy dependency imported at the top level: {mod}"
  142. )
  143. top_level_imports_found = True
  144. elif match_ := MOD_PATTERN.match(mod):
  145. if level == 1:
  146. dep = MOD_TO_DEP[match_.group(0)]
  147. if dep not in REQUIRED_DEPS:
  148. print(
  149. f"{pos}: Module of an optional dependency imported at the top level: {mod}"
  150. )
  151. top_level_imports_found = True
  152. else:
  153. print(f"{pos}: Unknown module imported: {mod}")
  154. unknown_modules_found = True
  155. for child in ast.iter_child_nodes(node):
  156. q.append((child, level + 1))
  157. return unknown_modules_found | (top_level_imports_found << 1)
  158. def main():
  159. files = sys.argv[1:]
  160. flag = 0
  161. for file in files:
  162. ret = check(file)
  163. flag |= ret
  164. if flag:
  165. if flag & 1:
  166. curr_script_path = pathlib.Path(__file__)
  167. curr_script_path = curr_script_path.relative_to(
  168. curr_script_path.parent.parent
  169. )
  170. print(
  171. f"If a new dependency should be added, please update `setup.py` and `{curr_script_path}`."
  172. )
  173. if (flag >> 1) & 1:
  174. print(
  175. "Please put the imports from optional dependencies and manually managed heavy dependencies inside a conditional body or within a function body."
  176. )
  177. sys.exit(1)
  178. if __name__ == "__main__":
  179. main()