check_imports.py 6.1 KB

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