Exemple #1
0
def _exporter():
    exporter = HTMLExporter(Config())
    exporter.exclude_input_prompt = True
    exporter.exclude_output_prompt = True
    exporter.template_file = 'jekyll.tpl'
    exporter.template_path.append(str(Path(__file__).parent))
    return exporter
Exemple #2
0
    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)
Exemple #3
0
 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)
Exemple #4
0
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 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
__all__ = ['HandleLinksPreprocessor', 'read_nb', 'convert_nb', 'convert_all']


class HandleLinksPreprocessor(Preprocessor):
    "A preprocesser that replaces all the .ipynb by .html in links. "

    def preprocess_cell(self, cell, resources, index):
        if 'source' in cell and cell.cell_type == "markdown":
            cell.source = re.sub(r"\((.*)\.ipynb(.*)\)", r"(\1.html\2)",
                                 cell.source).replace('¶', '')

        return cell, resources


exporter = HTMLExporter(Config())
exporter.exclude_input_prompt = True
exporter.exclude_output_prompt = True
#Loads the template to deal with hidden cells.
exporter.template_file = 'jekyll.tpl'
path = Path(__file__).parent
exporter.template_path.append(str(path))
#Preprocesser that converts the .ipynb links in .html
exporter.register_preprocessor(HandleLinksPreprocessor, enabled=True)

__all__ = ['convert_nb', 'convert_all']


def read_nb(fname):
    with open(fname, 'r') as f:
        return nbformat.reads(f.read(), as_version=4)
Exemple #7
0
    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)
import os.path, re, nbformat, jupyter_contrib_nbextensions
from nbconvert.preprocessors import Preprocessor
from nbconvert import HTMLExporter
from traitlets.config import Config
from pathlib import Path

__all__ = ['read_nb', 'convert_nb', 'convert_all']

exporter = HTMLExporter(Config())
exporter.exclude_input_prompt=True
exporter.exclude_output_prompt=True
#Loads the template to deal with hidden cells.
exporter.template_file = 'jekyll.tpl'
path = Path(__file__).parent
exporter.template_path.append(str(path))

def read_nb(fname):
    "Read the notebook in `fname`."
    with open(fname,'r') as f: return nbformat.reads(f.read(), as_version=4)

def convert_nb(fname, dest_path='.'):
    "Convert a notebook `fname` to html file in `dest_path`."
    from .gen_notebooks import remove_undoc_cells, remove_code_cell_jupyter_widget_state_elem
    nb = read_nb(fname)
    nb['cells'] = remove_undoc_cells(nb['cells'])
    nb['cells'] = remove_code_cell_jupyter_widget_state_elem(nb['cells'])
    fname = Path(fname).absolute()
    dest_name = fname.with_suffix('.html').name
    meta = nb['metadata']
    meta_jekyll = meta['jekyll'] if 'jekyll' in meta else {'title': fname.with_suffix('').name}
    meta_jekyll['nb_path'] = f'{fname.parent.name}/{fname.name}'