|
| 1 | +# Copyright 2024 The PyMC Labs Developers |
| 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 | +""" |
| 15 | +This is a simple script that converts the jupyter notebooks into markdown |
| 16 | +for easier (and cleaner) parsing for the codespell check. Whitelisted words |
| 17 | +are maintained within this directory in the `codespeel-whitelist.txt`. For |
| 18 | +more information on this pre-commit hook please visit the github homepage |
| 19 | +for the project: https://github.com/codespell-project/codespell. |
| 20 | +""" |
| 21 | + |
| 22 | +import argparse |
| 23 | +import os |
| 24 | +from glob import glob |
| 25 | + |
| 26 | +import nbformat |
| 27 | +from nbconvert import MarkdownExporter |
| 28 | + |
| 29 | + |
| 30 | +def notebook_to_markdown(pattern: str, output_dir: str) -> None: |
| 31 | + """ |
| 32 | + Utility to convert jupyter notebook to markdown files. |
| 33 | +
|
| 34 | + :param pattern: |
| 35 | + str that is a glob appropriate pattern to search |
| 36 | + :param output_dir: |
| 37 | + str directory to save the markdown files to |
| 38 | + """ |
| 39 | + for f_name in glob(pattern, recursive=True): |
| 40 | + with open(f_name, "r", encoding="utf-8") as f: |
| 41 | + nb = nbformat.read(f, as_version=4) |
| 42 | + |
| 43 | + markdown_exporter = MarkdownExporter() |
| 44 | + (body, _) = markdown_exporter.from_notebook_node(nb) |
| 45 | + |
| 46 | + os.makedirs(output_dir, exist_ok=True) |
| 47 | + |
| 48 | + output_file = os.path.join( |
| 49 | + output_dir, os.path.splitext(os.path.basename(f_name))[0] + ".md" |
| 50 | + ) |
| 51 | + |
| 52 | + with open(output_file, "w", encoding="utf-8") as f: |
| 53 | + f.write(body) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + parser = argparse.ArgumentParser() |
| 58 | + parser.add_argument( |
| 59 | + "-p", |
| 60 | + "--pattern", |
| 61 | + help="the glob appropriate pattern to search for jupyter notebooks", |
| 62 | + default="docs/**/*.ipynb", |
| 63 | + ) |
| 64 | + parser.add_argument( |
| 65 | + "-t", |
| 66 | + "--tempdir", |
| 67 | + help="temporary directory to save the converted notebooks", |
| 68 | + default="tmp_markdown", |
| 69 | + ) |
| 70 | + args = parser.parse_args() |
| 71 | + notebook_to_markdown(args.pattern, args.tempdir) |
0 commit comments