check_imports.py 6.3 KB

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