Advertisement
Guest User

converter.py

a guest
Dec 19th, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. import io, sys
  2. from IPython.nbformat import current
  3. from IPython.config import Config
  4. from IPython.nbconvert import HTMLExporter
  5.  
  6.  
  7.  
  8. def loadNotebook(filename):
  9.     """Load notebook from file."""
  10.     with io.open(filename, 'r', encoding='utf-8') as f:
  11.         nb = current.read(f, 'json')
  12.     return nb
  13.  
  14.  
  15. def split_into_units(nb):
  16.     """Split notebook into units for edX exporter."""
  17.     indexes = []
  18.     cells = nb.worksheets[0].cells
  19.     for (i, cell) in enumerate(cells):
  20.         if cell.cell_type == 'heading' and cell.level == 1:
  21.             indexes.append(i)
  22.  
  23.     separated_cells = [cells[i:j] for i, j in zip(indexes, indexes[1:]+[None])]
  24.  
  25.     worksheets = map(lambda cells: current.new_worksheet(name=cells[0].source, cells=cells), separated_cells)
  26.     units = map(lambda worksheet: current.new_notebook(name=worksheet.name, worksheets=[worksheet]), worksheets)
  27.     return units
  28.  
  29.  
  30. def export_units(units, folder):
  31.     """Export units into separate html files and save into folder."""
  32.     output_files = []
  33.     exportHtml = HTMLExporter(config=Config({'HTMLExporter':{'default_template':'basic'}}))
  34.     for unit in units:
  35.         (body, resources) = exportHtml.from_notebook_node(unit)
  36.         name = folder + '/' + unit.metadata.name + '.html'
  37.         name = list(name)
  38.         for (i,c) in enumerate(name):
  39.             if c == ' ': name[i] = '_'
  40.         name = "".join(name)
  41.         output_files.append(name)
  42.         with io.open(name, 'w', encoding='utf-8') as f:
  43.             f.write(body)
  44.     return output_files
  45.  
  46.  
  47.  
  48. def converter(notebook_file, output_folder):
  49.     """
  50.    Export given notebook into separated units.
  51.  
  52.    Input
  53.    -----
  54.    notebook_file : str
  55.        A relative path to notebook file.
  56.  
  57.    output_folder : str
  58.        A relative path to a target folder. All created units will
  59.        be saved there. Folder must exist.
  60.    """
  61.     nb = loadNotebook(notebook_file)
  62.     units = split_into_units(nb)
  63.     names = export_units(units, output_folder)
  64.  
  65.     return names
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement