Python nbformat.NotebookNode() Examples

The following are 13 code examples of nbformat.NotebookNode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module nbformat , or try the search function .
Example #1
Source File: exporter.py    From pipelines with Apache License 2.0 6 votes vote down vote up
def generate_html_from_notebook(self, nb: NotebookNode) -> Text:
        """Converts a provided NotebookNode to HTML.

        Args:
            nb: NotebookNode that should be converted to HTML.

        Returns:
            HTML from converted NotebookNode as a string.

        """
        # HTML generator and exporter object
        html_exporter = HTMLExporter()
        template_file = "templates/{}.tpl".format(self.template_type.value)
        html_exporter.template_file = str(Path.cwd() / template_file)
        # Output generator
        self.ep.preprocess(nb, {"metadata": {"path": Path.cwd()}}, self.km)
        # Export all html and outputs
        body, _ = html_exporter.from_notebook_node(nb, resources={})
        return body 
Example #2
Source File: _notebook.py    From podoc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read(self, notebook, context=None):
        assert isinstance(notebook, nbformat.NotebookNode)
        self.resources = {}  # Dictionary {filename: data}.
        context = context or {}
        # Get the unique key for image names: basename of the output file, if it exists.
        self._unique_key = op.basename(context.get('output', None) or '')
        self._unique_key = self._unique_key or op.basename(context.get('path', None) or '')
        self._unique_key = op.splitext(self._unique_key)[0] or None
        # Create the output tree.
        self.tree = ASTNode('root')
        # Language of the notebook.
        m = notebook.metadata
        # NOTE: if no language is available in the metadata, use Python
        # by default.
        self.language = m.get('language_info', {}).get('name', 'python')

        # NOTE: for performance reasons, we parse the Markdown of all cells at once
        # to reduce the overhead of calling pandoc.
        self._markdown_tree = []
        self._read_all_markdown(notebook.cells)

        for cell_index, cell in enumerate(notebook.cells):
            getattr(self, 'read_{}'.format(cell.cell_type))(cell, cell_index)

        return self.tree 
Example #3
Source File: latex.py    From bookbook with MIT License 6 votes vote down vote up
def combine_notebooks(notebook_files: Sequence[Path]) -> NotebookNode:
    combined_nb = new_notebook()

    count = 0
    for filename in notebook_files:
        count += 1
        log.debug('Adding notebook: %s', filename)
        nbname = filename.stem
        nb = nbformat.read(str(filename), as_version=4)

        try:
            combined_nb.cells.extend(add_sec_label(nb.cells[0], nbname))
        except NoHeader:
            raise NoHeader("Failed to find header in " + filename)

        combined_nb.cells.extend(nb.cells[1:])

        if not combined_nb.metadata:
            combined_nb.metadata = nb.metadata.copy()

    log.info('Combined %d files' % count)
    return combined_nb 
Example #4
Source File: exporter.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_notebook_node(self, nb, resources=None, **kw):
        """
        Convert a notebook from a notebook node instance.

        Parameters
        ----------
        nb : :class:`~nbformat.NotebookNode`
          Notebook node (dict-like with attr-access)
        resources : dict
          Additional resources that can be accessed read/write by
          preprocessors and filters.
        `**kw`
          Ignored

        """
        nb_copy = copy.deepcopy(nb)
        resources = self._init_resources(resources)

        if 'language' in nb['metadata']:
            resources['language'] = nb['metadata']['language'].lower()

        # Preprocess
        nb_copy, resources = self._preprocess(nb_copy, resources)

        return nb_copy, resources 
Example #5
Source File: server.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def generate_notebook_from_arguments(
        self,
        arguments: dict,
        source: Text,
        visualization_type: Text
    ) -> NotebookNode:
        """Generates a NotebookNode from provided arguments.

        Args:
            arguments: JSON object containing provided arguments.
            source: Path or path pattern to be used as data reference for
            visualization.
            visualization_type: Name of visualization to be generated.

        Returns:
                NotebookNode that contains all parameters from a post request.
        """
        nb = new_notebook()
        nb.cells.append(exporter.create_cell_from_args(arguments))
        nb.cells.append(new_code_cell('source = "{}"'.format(source)))
        if visualization_type == "custom":
            code = arguments.get("code", [])
            nb.cells.append(exporter.create_cell_from_custom_code(code))
        else:
            visualization_file = str(Path.cwd() / "types/{}.py".format(visualization_type))
            nb.cells.append(exporter.create_cell_from_file(visualization_file))
        
        return nb 
Example #6
Source File: exporter.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def create_cell_from_args(variables: dict) -> NotebookNode:
    """Creates NotebookNode object containing dict of provided variables.

    Args:
        variables: Arguments that need to be injected into a NotebookNode.

    Returns:
        NotebookNode with provided arguments as variables.

    """
    return new_code_cell("variables = {}".format(repr(variables))) 
Example #7
Source File: exporter.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def create_cell_from_file(filepath: Text) -> NotebookNode:
    """Creates a NotebookNode object with provided file as code in node.

    Args:
        filepath: Path to file that should be used.

    Returns:
        NotebookNode with specified file as code within node.

    """
    with open(filepath, 'r') as f:
        code = f.read()	

    return new_code_cell(code) 
Example #8
Source File: exporter.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def create_cell_from_custom_code(code: list) -> NotebookNode:
    """Creates a NotebookNode object with provided list as code in node.

    Args:
        code: list representing lines of code to be run.

    Returns:
        NotebookNode with specified file as code within node.

    """
    cell = new_code_cell("\n".join(code))
    cell.get("metadata")["hide_logging"] = False
    return cell 
Example #9
Source File: latex.py    From bookbook with MIT License 5 votes vote down vote up
def new_latex_cell(source=''):
    return NotebookNode(
        cell_type='raw',
        metadata=NotebookNode(raw_mimetype='text/latex'),
        source=source,
    ) 
Example #10
Source File: latex.py    From bookbook with MIT License 5 votes vote down vote up
def add_sec_label(cell: NotebookNode, nbname) -> Sequence[NotebookNode]:
    """Adds a Latex \\label{} under the chapter heading.

    This takes the first cell of a notebook, and expects it to be a Markdown
    cell starting with a level 1 heading. It inserts a label with the notebook
    name just underneath this heading.
    """
    assert cell.cell_type == 'markdown', cell.cell_type
    lines = cell.source.splitlines()
    if lines[0].startswith('# '):
        header_lines = 1
    elif len(lines) > 1 and lines[1].startswith('==='):
        header_lines = 2
    else:
        raise NoHeader

    header = '\n'.join(lines[:header_lines])
    intro_remainder = '\n'.join(lines[header_lines:]).strip()
    res = [
        new_markdown_cell(header),
        new_latex_cell('\label{sec:%s}' % nbname)
    ]
    res[0].metadata = cell.metadata
    if intro_remainder:
        res.append(new_markdown_cell(intro_remainder))
    return res 
Example #11
Source File: latex.py    From bookbook with MIT License 5 votes vote down vote up
def export(combined_nb: NotebookNode, output_file: Path, pdf=False,
           template_file=None):
    resources = {}
    resources['unique_key'] = 'combined'
    resources['output_files_dir'] = 'combined_files'

    log.info('Converting to %s', 'pdf' if pdf else 'latex')
    exporter = MyLatexPDFExporter() if pdf else MyLatexExporter()
    if template_file is not None:
        exporter.template_file = str(template_file)
    writer = FilesWriter(build_directory=str(output_file.parent))
    output, resources = exporter.from_notebook_node(combined_nb, resources)
    writer.write(output, resources, notebook_name=output_file.stem) 
Example #12
Source File: myst.py    From jupytext with MIT License 5 votes vote down vote up
def from_nbnode(value):
    """Recursively convert NotebookNode to dict."""
    if isinstance(value, nbf.NotebookNode):
        return {k: from_nbnode(v) for k, v in value.items()}
    return value 
Example #13
Source File: base.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def export(exporter, nb, **kw):
    """
    Export a notebook object using specific exporter class.
    
    Parameters
    ----------
    exporter : :class:`~nbconvert.exporters.exporter.Exporter` class or instance
      Class or instance of the exporter that should be used.  If the
      method initializes its own instance of the class, it is ASSUMED that
      the class type provided exposes a constructor (``__init__``) with the same
      signature as the base Exporter class.
    nb : :class:`~nbformat.NotebookNode`
        The notebook to export.
    config : config (optional, keyword arg)
        User configuration instance.
    resources : dict (optional, keyword arg)
        Resources used in the conversion process.

    Returns
    -------
    tuple
        output : str
            The resulting converted notebook.
        resources : dictionary
            Dictionary of resources used prior to and during the conversion 
            process.
    """
    
    #Check arguments
    if exporter is None:
        raise TypeError("Exporter is None")
    elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
        raise TypeError("exporter does not inherit from Exporter (base)")
    if nb is None:
        raise TypeError("nb is None")
    
    #Create the exporter
    resources = kw.pop('resources', None)
    if isinstance(exporter, Exporter):
        exporter_instance = exporter
    else:
        exporter_instance = exporter(**kw)
    
    #Try to convert the notebook using the appropriate conversion function.
    if isinstance(nb, NotebookNode):
        output, resources = exporter_instance.from_notebook_node(nb, resources)
    elif isinstance(nb, string_types):
        output, resources = exporter_instance.from_filename(nb, resources)
    else:
        output, resources = exporter_instance.from_file(nb, resources)
    return output, resources