public
Last active

downgrade v3 ipython notebooks to v2

  • Download Gist
downgradenb.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
"""Simple utility script for semi-gracefully downgrading v3 notebooks to v2"""
 
import io
import os
import sys
 
from IPython.nbformat import current
 
def heading_to_md(cell):
"""turn heading cell into corresponding markdown"""
cell.cell_type = "markdown"
level = cell.pop('level', 1)
cell.source = '#'*level + ' ' + cell.source
 
def raw_to_md(cell):
"""let raw passthrough as markdown"""
cell.cell_type = "markdown"
 
def downgrade(nb):
"""downgrade a v3 notebook to v2"""
if nb.nbformat != 3:
return nb
nb.nbformat = 2
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'heading':
heading_to_md(cell)
elif cell.cell_type == 'raw':
raw_to_md(cell)
return nb
 
def downgrade_ipynb(fname):
base, ext = os.path.splitext(fname)
newname = base+'.v2'+ext
print "downgrading %s -> %s" % (fname, newname)
with io.open(fname, 'r', encoding='utf8') as f:
nb = current.read(f, 'json')
nb = downgrade(nb)
with open(newname, 'w') as f:
current.write(nb, f, 'json')
 
if __name__ == '__main__':
map(downgrade_ipynb, sys.argv[1:])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.