|
| 1 | +import os |
| 2 | +import glob |
| 3 | +import ast |
| 4 | +import importlib.util |
| 5 | +import micropip |
| 6 | +import asyncio |
| 7 | + |
| 8 | +PARENT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 9 | +ROOT_DIR = os.path.dirname(PARENT_DIR) |
| 10 | + |
| 11 | +PY_FILES_DIR = os.path.join(PARENT_DIR, 'py_files') |
| 12 | +SKIP_FILES = [ |
| 13 | + 'short_path.py', |
| 14 | + 'inflation_history.py' |
| 15 | +] |
| 16 | + |
| 17 | +def get_imported_libraries(file_path): |
| 18 | + """Extracts all imported libraries from a Python file.""" |
| 19 | + with open(file_path, "r", encoding="utf-8") as file: |
| 20 | + tree = ast.parse(file.read(), filename=file_path) |
| 21 | + |
| 22 | + imports = set() |
| 23 | + |
| 24 | + for node in ast.walk(tree): |
| 25 | + if isinstance(node, ast.Import): |
| 26 | + for alias in node.names: |
| 27 | + imports.add(alias.name.split('.')[0]) # Get the top-level package |
| 28 | + elif isinstance(node, ast.ImportFrom): |
| 29 | + if node.module: |
| 30 | + imports.add(node.module.split('.')[0]) |
| 31 | + |
| 32 | + return sorted(imports) |
| 33 | + |
| 34 | + |
| 35 | +def is_library_installed(library_name): |
| 36 | + """Checks if a given library is installed.""" |
| 37 | + return importlib.util.find_spec(library_name) is not None |
| 38 | + |
| 39 | + |
| 40 | +async def install_missing_libraries(file_path, previously_installed): |
| 41 | + """Finds missing libraries and installs them using micropip.""" |
| 42 | + for skip_file in SKIP_FILES: |
| 43 | + if file_path.endswith(skip_file): |
| 44 | + return |
| 45 | + print(f"Installing missing libraries for file: {file_path}") |
| 46 | + imported_libraries = get_imported_libraries(file_path) |
| 47 | + |
| 48 | + missing_libraries = [] |
| 49 | + for lib in imported_libraries: |
| 50 | + if lib not in previously_installed and not is_library_installed(lib): |
| 51 | + missing_libraries.append(lib) |
| 52 | + |
| 53 | + if len(missing_libraries) == 0: |
| 54 | + print(f"All required libraries are already installed in {file_path}") |
| 55 | + return |
| 56 | + |
| 57 | + for lib in missing_libraries: |
| 58 | + print(f"Installing missing libraries: {lib}") |
| 59 | + await micropip.install(lib) |
| 60 | + previously_installed.add(lib) |
| 61 | + |
| 62 | + |
| 63 | +async def main(): |
| 64 | + lectures_py = list(glob.glob(PY_FILES_DIR + '/*.py')) |
| 65 | + previously_installed = set() |
| 66 | + for file in lectures_py: |
| 67 | + await install_missing_libraries(file, previously_installed) |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + asyncio.run(main()) |
0 commit comments