|
| 1 | +# Testing script to check whether the lectures added in |
| 2 | +# wasm_compatible.yml are compatible with WASM. |
| 3 | +# This is a soft-check check based on the imports present. |
| 4 | +# It is still recommended to test the lecture on the |
| 5 | +# https://github.com/QuantEcon/project.lecture-wasm |
| 6 | + |
| 7 | +import os |
| 8 | +import yaml |
| 9 | +import jupytext |
| 10 | + |
| 11 | +from pyodide.code import find_imports |
| 12 | + |
| 13 | +# This is the list of imports (libraries) that are not supported |
| 14 | +# WASM pyodide kernel in Jupyterlite. |
| 15 | +UNSUPPORTED_LIBS = { |
| 16 | + 'quantecon', |
| 17 | + 'numba', |
| 18 | +} |
| 19 | + |
| 20 | +CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 21 | +ROOT_DIR = os.path.dirname(CURRENT_DIR) |
| 22 | +LECTURES_DIR = os.path.join(ROOT_DIR, "lectures") |
| 23 | +CONFIG_FILE = os.path.join(ROOT_DIR, "wasm_compatible.yml") |
| 24 | + |
| 25 | + |
| 26 | +def get_wasm_compatible_files(): |
| 27 | + """ |
| 28 | + Get the list of lectures names from the config file. |
| 29 | + """ |
| 30 | + # Load the YAML configuration |
| 31 | + with open(CONFIG_FILE, "r") as file: |
| 32 | + config = yaml.safe_load(file) |
| 33 | + |
| 34 | + return config.get("lectures", []) |
| 35 | + |
| 36 | + |
| 37 | +def convert_md_to_py_string(md_file_path): |
| 38 | + """ |
| 39 | + Convert a .md(myst) file to Python code string without creating a .py file. |
| 40 | + |
| 41 | + Args: |
| 42 | + md_file_path (str): Path to the Markdown file (.md) |
| 43 | + |
| 44 | + Returns: |
| 45 | + str: Python code as a string |
| 46 | + """ |
| 47 | + # Read the markdown file as a Jupytext notebook |
| 48 | + with open(md_file_path, 'r', encoding='utf-8') as md_file: |
| 49 | + notebook = jupytext.read(md_file) |
| 50 | + |
| 51 | + # Convert the notebook to Python script format |
| 52 | + py_code = jupytext.writes(notebook, fmt="py") |
| 53 | + |
| 54 | + return py_code |
| 55 | + |
| 56 | + |
| 57 | +def test_compatibility(): |
| 58 | + file_names = get_wasm_compatible_files() |
| 59 | + for file_name in file_names: |
| 60 | + py_string = convert_md_to_py_string(os.path.join(LECTURES_DIR, file_name + ".md")) |
| 61 | + file_imports = find_imports(py_string) |
| 62 | + for file_import in file_imports: |
| 63 | + if file_import in UNSUPPORTED_LIBS: |
| 64 | + error = 'import `{}` in lecture `{}` is not supported by WASM'.format(file_import, file_name) |
| 65 | + raise ValueError(error) |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + test_compatibility() |
0 commit comments