Skip to content

Instantly share code, notes, and snippets.

@brianjo
Forked from chsasank/ipynb_to_gallery.py
Created June 17, 2021 15:06
Show Gist options
  • Select an option

  • Save brianjo/7be6783f4a2d1a4c3eeb15b0dafa2bc5 to your computer and use it in GitHub Desktop.

Select an option

Save brianjo/7be6783f4a2d1a4c3eeb15b0dafa2bc5 to your computer and use it in GitHub Desktop.

Revisions

  1. @chsasank chsasank revised this gist Jun 25, 2019. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions ipynb_to_gallery.py
    Original file line number Diff line number Diff line change
    @@ -34,6 +34,7 @@ def convert_ipynb_to_gallery(file_name):
    source = ''.join(cell['source'])
    python_file = python_file + '\n' * 2 + source

    python_file = python_file.replace("\n%", "\n# %")
    open(file_name.replace('.ipynb', '.py'), 'w').write(python_file)

    if __name__ == '__main__':
  2. @chsasank chsasank revised this gist Mar 1, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion ipynb_to_gallery.py
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@
    Usage: python ipynb_to_gallery.py <notebook.ipynb>
    Dependencies:
    pypandoc: install using pip install pypandoc
    pypandoc: install using `pip install pypandoc`
    """
    import pypandoc as pdoc
    import json
  3. @chsasank chsasank created this gist Mar 1, 2017.
    41 changes: 41 additions & 0 deletions ipynb_to_gallery.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    """Convert jupyter notebook to sphinx gallery notebook styled examples.
    Usage: python ipynb_to_gallery.py <notebook.ipynb>
    Dependencies:
    pypandoc: install using pip install pypandoc
    """
    import pypandoc as pdoc
    import json

    def convert_ipynb_to_gallery(file_name):
    python_file = ""

    nb_dict = json.load(open(file_name))
    cells = nb_dict['cells']

    for i, cell in enumerate(cells):
    if i == 0:
    assert cell['cell_type'] == 'markdown', \
    'First cell has to be markdown'

    md_source = ''.join(cell['source'])
    rst_source = pdoc.convert_text(md_source, 'rst', 'md')
    python_file = '"""\n' + rst_source + '\n"""'
    else:
    if cell['cell_type'] == 'markdown':
    md_source = ''.join(cell['source'])
    rst_source = pdoc.convert_text(md_source, 'rst', 'md')
    commented_source = '\n'.join(['# ' + x for x in
    rst_source.split('\n')])
    python_file = python_file + '\n\n\n' + '#' * 70 + '\n' + \
    commented_source
    elif cell['cell_type'] == 'code':
    source = ''.join(cell['source'])
    python_file = python_file + '\n' * 2 + source

    open(file_name.replace('.ipynb', '.py'), 'w').write(python_file)

    if __name__ == '__main__':
    import sys
    convert_ipynb_to_gallery(sys.argv[-1])