def notebook_to_html(notebook_path, output_path): '''Convert a Jupyter/IPython notebook to an HTML file Parameters ---------- notebook_path: str output_path: str Output ------ None ''' with open(notebook_path, 'r') as fp: notebook = nbformat.read(fp, nbformat.NO_CONVERT) # Instantiate the exporter html_exporter = HTMLExporter() # html_exporter.template_file = 'basic' # Exclude code cells from the HTML output html_exporter.exclude_input = True # Generate HTML (body, resources) = html_exporter.from_notebook_node(notebook) # print("Resources:", resources.keys()) # print("Metadata:", resources['metadata'].keys()) # print("Inlining:", resources['inlining'].keys()) # print("Extension:", resources['output_extension']) with open(output_path, 'w') as fp: fp.write(body)
def get(self, path=None): if path: path += '.ipynb' # when used as a jupyter server extension, we don't use the extension # if the handler got a notebook_path argument, always serve that notebook_path = self.notebook_path or path model = self.contents_manager.get(path=notebook_path) if 'content' in model: notebook = model['content'] else: raise tornado.web.HTTPError(404, 'file not found') # Fetch kernel name from the notebook metadata kernel_name = notebook.metadata.get('kernelspec', {}).get( 'name', self.kernel_manager.default_kernel_name) # Launch kernel and execute notebook kernel_id = yield tornado.gen.maybe_future( self.kernel_manager.start_kernel(kernel_name=kernel_name)) km = self.kernel_manager.get_kernel(kernel_id) result = executenb(notebook, km=km) # render notebook to html resources = {'kernel_id': kernel_id, 'base_url': self.base_url} exporter = HTMLExporter(template_file='voila.tpl', template_path=self.template_path, config=self.exporter_config) if self.strip_sources: exporter.exclude_input = True exporter.exclude_output_prompt = True exporter.exclude_input_prompt = True # Filtering out empty cells. def filter_empty_code_cells(cell): return ( cell.cell_type != 'code' or # keep non-code cells (cell.outputs and not exporter.exclude_output ) # keep cell if output not excluded and not empty or not exporter.exclude_input # keep cell if input not excluded ) result.cells = list(filter(filter_empty_code_cells, result.cells)) html, resources = exporter.from_notebook_node(result, resources=resources) # Compose reply self.set_header('Content-Type', 'text/html') self.write(html)
def to_html(self, path): html_exporter = HTMLExporter() html_exporter.template_data_paths = html_exporter.template_data_paths + [ os.path.dirname(__file__) ] html_exporter.template_file = "index.html.j2" html_exporter.exclude_input_prompt = True html_exporter.exclude_output_prompt = True html_exporter.exclude_input = True html_exporter.allow_errors = False html_exporter.log_level = "CRITICAL" (body, resources) = html_exporter.from_notebook_node(self.nb) # images will be embedded as base64, so we shouldn't need the resources with open(path, "w") as f: f.write(body)
def nb_to_html(nb, exclude_input=True, exclude_prompts=True): """ convert notebook to html @input nb : notebook @input exclude_input (bool default:True) : exclude input cells from output @input exclude_prompts (bool default:True) : exclude prompts from ouput @returns string : html body """ html_exporter = HTMLExporter() html_exporter.exclude_input = exclude_input html_exporter.exclude_input_prompt = exclude_prompts html_exporter.exclude_output_prompt = exclude_prompts (body, _) = html_exporter.from_notebook_node(nb) return body
def convert_to_html(result_notebook: Path) -> Path: """ :param result_notebook: The path to the result notebook :return: Path with output extension """ print(f"Running conversion to HTML for {result_notebook}") with result_notebook.open() as f: notebook = nbformat.read(f, as_version=4) html_exporter = HTMLExporter() html_exporter.exclude_input = True (body, resources) = html_exporter.from_notebook_node(notebook) write_file = FilesWriter() write_file.build_directory = str(result_notebook.parent) write_file.write(output=body, resources=resources, notebook_name=str(result_notebook.stem)) return result_notebook.with_suffix(resources['output_extension'])
def generate_notebook(template_notebook: Path, notebook_params: Dict, result_notebook: Path) -> Path: print(f"Writing report to {result_notebook}") papermill.execute_notebook(input_path=str(template_notebook), output_path=str(result_notebook), parameters=notebook_params, progress_bar=False) print(f"Running conversion to HTML for {result_notebook}") with result_notebook.open() as f: notebook = nbformat.read(f, as_version=4) html_exporter = HTMLExporter() html_exporter.exclude_input = True (body, resources) = html_exporter.from_notebook_node(notebook) write_file = FilesWriter() write_file.build_directory = str(result_notebook.parent) write_file.write(output=body, resources=resources, notebook_name=str(result_notebook.stem)) return result_notebook.with_suffix(resources['output_extension'])
def notebook_to_report(self, version=4, template_path=None): """The method transforms a notebook into a HTML file. By default, the title of the report is the name of the file without underscores. This can be modified by adding a custom key `title` to the metadata of the notebook. Args: version (int, default: 4): the version of the notebook (as_version parameter from nbformat.read) template_path (str, default: None): the full path to the template folder. By default, the template is the default one.""" html_exporter = HTMLExporter() if template_path: try: template_path = Path(template_path) loader = jinja2.FileSystemLoader(str(template_path.parent)) html_exporter.extra_loaders = [loader] html_exporter.template_file = template_path.name html_exporter.exclude_input = True html_exporter.exclude_input_prompt = True html_exporter.exclude_output_prompt = True except FileNotFoundError as e: raise e try: with self.temporary_notebook.open() as notebook_file: notebook = nbformat.read(notebook_file, as_version=version) if "title" in notebook["metadata"].keys(): title = notebook["metadata"]["title"] else: title = self.title resources = dict(metadata=dict(name=title)) (body, _) = html_exporter.from_notebook_node(notebook, resources=resources) self.report_path.write_text(body) self.temporary_notebook.unlink() except FileNotFoundError as e: raise e
def get(self, path=None): if path: path += '.ipynb' # when used as a jupyter server extension, we don't use the extension # if the handler got a notebook_path argument, always serve that notebook_path = self.notebook_path or path # generate a list of nbextensions that are enabled for the classical notebook # a template can use that to load classical notebook extensions, but does not have to notebook_config = self.config_manager.get('notebook') # except for the widget extension itself, since voila has its own load_extensions = notebook_config.get('load_extensions', {}) if "jupyter-js-widgets/extension" in load_extensions: load_extensions["jupyter-js-widgets/extension"] = False nbextensions = [ name for name, enabled in load_extensions.items() if enabled ] model = self.contents_manager.get(path=notebook_path) if 'content' in model: notebook = model['content'] else: raise tornado.web.HTTPError(404, 'file not found') # Fetch kernel name from the notebook metadata kernel_name = notebook.metadata.get('kernelspec', {}).get( 'name', self.kernel_manager.default_kernel_name) # Launch kernel and execute notebook kernel_id = yield tornado.gen.maybe_future( self.kernel_manager.start_kernel(kernel_name=kernel_name)) km = self.kernel_manager.get_kernel(kernel_id) result = executenb(notebook, km=km) # render notebook to html resources = { 'kernel_id': kernel_id, 'base_url': self.base_url, 'nbextensions': nbextensions } exporter = HTMLExporter(template_file='voila.tpl', template_path=self.nbconvert_template_paths, config=self.exporter_config) if self.strip_sources: exporter.exclude_input = True exporter.exclude_output_prompt = True exporter.exclude_input_prompt = True # Filtering out empty cells. def filter_empty_code_cells(cell): return ( cell.cell_type != 'code' or # keep non-code cells (cell.outputs and not exporter.exclude_output ) # keep cell if output not excluded and not empty or not exporter.exclude_input # keep cell if input not excluded ) result.cells = list(filter(filter_empty_code_cells, result.cells)) html, resources = exporter.from_notebook_node(result, resources=resources) # Compose reply self.set_header('Content-Type', 'text/html') self.write(html)