Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import io, sys
- from IPython.nbformat import current
- from IPython.config import Config
- from IPython.nbconvert import HTMLExporter
- def loadNotebook(filename):
- """Load notebook from file."""
- with io.open(filename, 'r', encoding='utf-8') as f:
- nb = current.read(f, 'json')
- return nb
- def split_into_units(nb):
- """Split notebook into units for edX exporter."""
- indexes = []
- cells = nb.worksheets[0].cells
- for (i, cell) in enumerate(cells):
- if cell.cell_type == 'heading' and cell.level == 1:
- indexes.append(i)
- separated_cells = [cells[i:j] for i, j in zip(indexes, indexes[1:]+[None])]
- worksheets = map(lambda cells: current.new_worksheet(name=cells[0].source, cells=cells), separated_cells)
- units = map(lambda worksheet: current.new_notebook(name=worksheet.name, worksheets=[worksheet]), worksheets)
- return units
- def export_units(units, folder):
- """Export units into separate html files and save into folder."""
- output_files = []
- exportHtml = HTMLExporter(config=Config({'HTMLExporter':{'default_template':'basic'}}))
- for unit in units:
- (body, resources) = exportHtml.from_notebook_node(unit)
- name = folder + '/' + unit.metadata.name + '.html'
- name = list(name)
- for (i,c) in enumerate(name):
- if c == ' ': name[i] = '_'
- name = "".join(name)
- output_files.append(name)
- with io.open(name, 'w', encoding='utf-8') as f:
- f.write(body)
- return output_files
- def converter(notebook_file, output_folder):
- """
- Export given notebook into separated units.
- Input
- -----
- notebook_file : str
- A relative path to notebook file.
- output_folder : str
- A relative path to a target folder. All created units will
- be saved there. Folder must exist.
- """
- nb = loadNotebook(notebook_file)
- units = split_into_units(nb)
- names = export_units(units, output_folder)
- return names
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement