1#!/usr/bin/env python 2 3# Licensed to the Apache Software Foundation (ASF) under one 4# or more contributor license agreements. See the NOTICE file 5# distributed with this work for additional information 6# regarding copyright ownership. The ASF licenses this file 7# to you under the Apache License, Version 2.0 (the 8# "License"); you may not use this file except in compliance 9# with the License. You may obtain a copy of the License at 10# 11# http://www.apache.org/licenses/LICENSE-2.0 12# 13# Unless required by applicable law or agreed to in writing, 14# software distributed under the License is distributed on an 15# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16# KIND, either express or implied. See the License for the 17# specific language governing permissions and limitations 18# under the License. 19 20 21""" 22Convert jupyter notebook into the markdown format. The notebook outputs will be 23removed. 24 25It is heavily adapted from https://gist.github.com/decabyte/0ed87372774cf5d34d7e 26""" 27from __future__ import print_function 28 29import sys 30import io 31import os 32import argparse 33import nbformat 34 35 36def remove_outputs(nb): 37 """Removes the outputs cells for a jupyter notebook.""" 38 for cell in nb.cells: 39 if cell.cell_type == 'code': 40 cell.outputs = [] 41 42 43def clear_notebook(old_ipynb, new_ipynb): 44 with open(old_ipynb, 'r') as f: 45 nb = nbformat.read(f, nbformat.NO_CONVERT) 46 47 remove_outputs(nb) 48 49 with open(new_ipynb, 'w', encoding='utf8') as f: 50 nbformat.write(nb, f, nbformat.NO_CONVERT) 51 52 53def main(): 54 parser = argparse.ArgumentParser( 55 description="Jupyter Notebooks to markdown" 56 ) 57 58 parser.add_argument("notebook", nargs=1, help="The notebook to be converted.") 59 parser.add_argument("-o", "--output", help="output markdown file") 60 args = parser.parse_args() 61 62 old_ipynb = args.notebook[0] 63 new_ipynb = 'tmp.ipynb' 64 md_file = args.output 65 print(md_file) 66 if not md_file: 67 md_file = os.path.splitext(old_ipynb)[0] + '.md' 68 69 70 clear_notebook(old_ipynb, new_ipynb) 71 os.system('jupyter nbconvert ' + new_ipynb + ' --to markdown --output ' + md_file) 72 with open(md_file, 'a') as f: 73 f.write('<!-- INSERT SOURCE DOWNLOAD BUTTONS -->') 74 os.system('rm ' + new_ipynb) 75 76if __name__ == '__main__': 77 main() 78