當前位置: 首頁>>代碼示例>>Python>>正文


Python nbformat.NotebookNode方法代碼示例

本文整理匯總了Python中nbformat.NotebookNode方法的典型用法代碼示例。如果您正苦於以下問題:Python nbformat.NotebookNode方法的具體用法?Python nbformat.NotebookNode怎麽用?Python nbformat.NotebookNode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在nbformat的用法示例。


在下文中一共展示了nbformat.NotebookNode方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: generate_html_from_notebook

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:kubeflow,項目名稱:pipelines,代碼行數:21,代碼來源:exporter.py

示例2: read

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:podoc,項目名稱:podoc,代碼行數:27,代碼來源:_notebook.py

示例3: combine_notebooks

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:takluyver,項目名稱:bookbook,代碼行數:24,代碼來源:latex.py

示例4: from_notebook_node

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:27,代碼來源:exporter.py

示例5: generate_notebook_from_arguments

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:kubeflow,項目名稱:pipelines,代碼行數:30,代碼來源:server.py

示例6: create_cell_from_args

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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))) 
開發者ID:kubeflow,項目名稱:pipelines,代碼行數:13,代碼來源:exporter.py

示例7: create_cell_from_file

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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) 
開發者ID:kubeflow,項目名稱:pipelines,代碼行數:16,代碼來源:exporter.py

示例8: create_cell_from_custom_code

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:kubeflow,項目名稱:pipelines,代碼行數:15,代碼來源:exporter.py

示例9: new_latex_cell

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
def new_latex_cell(source=''):
    return NotebookNode(
        cell_type='raw',
        metadata=NotebookNode(raw_mimetype='text/latex'),
        source=source,
    ) 
開發者ID:takluyver,項目名稱:bookbook,代碼行數:8,代碼來源:latex.py

示例10: add_sec_label

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:takluyver,項目名稱:bookbook,代碼行數:28,代碼來源:latex.py

示例11: export

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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) 
開發者ID:takluyver,項目名稱:bookbook,代碼行數:15,代碼來源:latex.py

示例12: from_nbnode

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:mwouts,項目名稱:jupytext,代碼行數:7,代碼來源:myst.py

示例13: export

# 需要導入模塊: import nbformat [as 別名]
# 或者: from nbformat import NotebookNode [as 別名]
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 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:53,代碼來源:base.py


注:本文中的nbformat.NotebookNode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。