check_imports.py 6.2 KB

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