#!/bin/env python import os import subprocess import shutil import nbformat ################################################################ class NotFoundNotebooks(Exception): "Could not find the notebooks to treat" ################################################################ def mergeNotebooks(notebook_files, add_cell_number=False, select_cells=None): "Merges several notebooks in a single one named: talk.ipynb" print("Merging notebooks {0}".format(notebook_files)) notebooks = [nbformat.read(f, as_version=4) for f in notebook_files] if len(notebooks) == 0: raise NotFoundNotebooks cells = notebooks[0]['cells'] for n in notebooks[1:]: cells += n['cells'] if select_cells is None: select_cells = set(range(0, len(cells))) select_cells = set(select_cells) discard_cells = set(range(0, len(cells))) - select_cells new_cells = [] for cell_number, c in enumerate(cells): if cell_number in discard_cells: continue # print(c) new_cells.append(c) if add_cell_number: new_cell = nbformat.notebooknode.NotebookNode() new_cell['cell_type'] = 'markdown' new_cell['source'] = 'Cell number {0}'.format(cell_number) new_cell['metadata'] = {} new_cells.append(new_cell) # print(new_cells) notebooks[0]['cells'] = new_cells nbformat.write(notebooks[0], 'talk.ipynb') ################################################################ def launchSlideServer(options=""): " Launch the HTTP server for reveal slides " reveal_path = './reveal.js' dir_name = os.path.dirname(__file__) slides_config_file = os.path.join(dir_name, 'slides_config.py') cmd = ('jupyter nbconvert --to=slides --config {1} --post serve ' + '--ServePostProcessor.open_in_browser=False --reveal-prefix={0} {2} ' + 'talk.ipynb').format(reveal_path, slides_config_file, options) print cmd subprocess.call(cmd, shell=True) ################################################################ def generateHTML(options=""): " Launch the HTTP server for reveal slides " reveal_path = './reveal.js' dir_name = os.path.dirname(__file__) slides_config_file = os.path.join(dir_name, 'slides_config.py') cmd = ('jupyter nbconvert --to=slides --config {1} --reveal-prefix={0} {2} ' + 'talk.ipynb').format(reveal_path, slides_config_file, options) print cmd subprocess.call(cmd, shell=True) ################################################################ def executeNotebook(filename, options=""): " Request the execution of all cells " print 'execute notebook: ', filename dir_name = os.path.dirname(__file__) slides_config_file = os.path.join(dir_name, 'slides_execute_config.py') subprocess.call('jupyter nbconvert --to=notebook --output tmp.ipynb --config' + ' {0} {1}'.format(slides_config_file, filename), shell=True) shutil.move('tmp.ipynb', filename) subprocess.call('jupyter trust {0}'.format(filename), shell=True) ################################################################