How to use the nbformat.from_dict function in nbformat

To help you get started, we’ve selected a few nbformat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jupyter / jupyter-sphinx / tests / test_execute.py View on Github external
def test_image_mimetype_uri(doctree):
    # tests the image uri paths on conversion to docutils image nodes
    priority =  ['image/png', 'image/jpeg', 'text/latex', 'text/plain']
    output_dir = '/_build/jupyter_execute'
    img_locs = ['/_build/jupyter_execute/docs/image_1.png','/_build/jupyter_execute/image_2.png']

    cells = [
        {'outputs':
            [{'data': {'image/png': 'Vxb6L1wAAAABJRU5ErkJggg==\n', 'text/plain': '<figure size="">'}, 'metadata': {'filenames': {'image/png': img_locs[0]}}, 'output_type': 'display_data'}]
        },
        {'outputs':
            [{'data': {'image/png': 'iVBOJggg==\n', 'text/plain': '<figure size="">'}, 'metadata': {'filenames': {'image/png': img_locs[1]}}, 'output_type': 'display_data'}]
        }]

    for index, cell in enumerate(cells):
        cell = from_dict(cell)
        output_node = cell_output_to_nodes(cell["outputs"], priority, True, output_dir, None)
        assert output_node[0].attributes['uri'] == img_locs[index]
</figure></figure>
github fastai / fastai / fastai / gen_doc / gen_notebooks.py View on Github external
def write_nb(nb, nb_path, mode='w'):
    with open(nb_path, mode) as f: f.write(nbformat.writes(nbformat.from_dict(nb), version=4))
github dean0x7d / pybinding / docs / _ext / nbexport.py View on Github external
def write_markdown(self, text):
        if self.nb.cells[-1].cell_type != "markdown":
            self.nb.cells.append(nbformat.from_dict({
                "cell_type": "markdown",
                "metadata": {},
                "source": []
            }))

        self.nb.cells[-1].source.append(
            text.replace("\n", "\n" + " " * self.indent)
        )
github jupyter / nbdime / nbdime / merging / decisions.py View on Github external
for key in path:
                parent = resolved
                resolved = resolved[key]   # Should raise if key missing
                last_key = key
            diffs = resolve_action(resolved, md)
            if line:
                diffs = push_path(line, diffs)
            clear_all_flag = md.action == "clear_all"
    # Apply the last collection of diffs, if present (same as above)
    if prev_path is not None:
        if parent is None:
            merged = patch(resolved, diffs)
        else:
            parent[last_key] = patch(resolved, diffs)

    merged = nbformat.from_dict(merged)
    return merged
github dalejung / nbx / nbx / nbmanager / tagged_gist / gistnbmanager.py View on Github external
def save_notebook(self, model, name='', path=''):
        """Save the notebook model and return the model with no content."""
        path = path.strip('/')

        if 'content' not in model:
            raise web.HTTPError(400, u'No notebook JSON data provided')

        if not path:
            raise web.HTTPError(400, u'We require path for saving.')

        nb = nbformat.from_dict(model['content'])

        gist = self._get_gist(name, path)
        if gist is None:
            tags = parse_tags(name)
            if path:
                tags.append(path)
            content = nbformat.writes(nb, version=nbformat.NO_CONVERT)
            gist = self.gisthub.create_gist(name, tags, content)

        # One checkpoint should always exist
        #if self.notebook_exists(name, path) and not self.list_checkpoints(name, path):
        #    self.create_checkpoint(name, path)

        new_path = model.get('path', path).strip('/')
        new_name = model.get('name', name)
github materialsproject / MPContribs / mpcontribs-portal / mpcontribs / portal / views.py View on Github external
def export_notebook(nb, cid):
    nb = nbformat.from_dict(nb)
    html_exporter = HTMLExporter()
    html_exporter.template_file = "basic"
    return html_exporter.from_notebook_node(nb)
github fastai / fastai_dev / dev / local / notebook / export2html.py View on Github external
def execute_nb(nb, mod=None, metadata=None, show_doc_only=True, name=None):
    "Execute `nb` (or only the `show_doc` cells) with `metadata`"
    nb['cells'].insert(0, _import_show_doc_cell(mod, name))
    ep_cls = ExecuteShowDocPreprocessor if show_doc_only else ExecutePreprocessor
    ep = ep_cls(timeout=600, kernel_name='python3')
    metadata = metadata or {}
    pnb = nbformat.from_dict(nb)
    ep.preprocess(pnb, metadata)
    return pnb
github jupyter / notebook / notebook / services / contents / filemanager.py View on Github external
"""Save the file model and return the model with no content."""
        path = path.strip('/')

        if 'type' not in model:
            raise web.HTTPError(400, u'No file type provided')
        if 'content' not in model and model['type'] != 'directory':
            raise web.HTTPError(400, u'No file content provided')

        os_path = self._get_os_path(path)
        self.log.debug("Saving %s", os_path)

        self.run_pre_save_hook(model=model, path=path)

        try:
            if model['type'] == 'notebook':
                nb = nbformat.from_dict(model['content'])
                self.check_and_sign(nb, path)
                self._save_notebook(os_path, nb)
                # One checkpoint should always exist for notebooks.
                if not self.checkpoints.list_checkpoints(path):
                    self.create_checkpoint(path)
            elif model['type'] == 'file':
                # Missing format will be handled internally by _save_file.
                self._save_file(os_path, model['content'], model.get('format'))
            elif model['type'] == 'directory':
                self._save_directory(os_path, model, path)
            else:
                raise web.HTTPError(400, "Unhandled contents type: %s" % model['type'])
        except web.HTTPError:
            raise
        except Exception as e:
            self.log.error(u'Error while saving file: %s %s', path, e, exc_info=True)