File: jupyter_notebook.py

package info (click to toggle)
python-pweave 0.30.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,068 kB
  • sloc: python: 30,281; makefile: 167
file content (67 lines) | stat: -rw-r--r-- 2,170 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import nbformat


class PwebNotebookFormatter(object):

    def __init__(self, executed, *, kernel = "python3", language = "python",
                 mimetype = "text/markdown", source = None, theme = None,
                 figdir = None, wd = None):

        self.notebook = {"metadata" : {
                "kernel_info" : {
                    "name" : kernel
                },
            "language_info": {
                # if language_info is defined, its name field is required.
                "name": language
            }
        },
        "nbformat": 4,
        "nbformat_minor": 0,
        "cells": [ ]
        }

        self.execution_count = 1
        self.file_ext = "ipynb"
        self.executed = executed
        self.mimetype = mimetype

        if mimetype == "text/markdown":
            self.doc_cell_type = "markdown"
        else:
            self.doc_cell_type = "raw"

    def setexecuted(self, executed):
        self.executed = executed

    def format(self):
        for chunk in self.executed:
            if chunk["type"] == "doc":
                self.notebook["cells"].append(
                    {
                        "cell_type": self.doc_cell_type,
                        "metadata": {
                            "format" : self.mimetype
                        },
                        "source": chunk["content"],
                    }
                )
            if chunk["type"] == "code":
                self.notebook["cells"].append(
                    {
                        "cell_type": "code",
                        "execution_count" : self.execution_count,
                        "metadata": {
                            "collapsed": False,
                            "autoscroll": "auto",
                            "options" : chunk["options"]
                        },
                        "source": chunk["content"].lstrip(),
                        "outputs" : chunk["result"]
                    }
                )
                self.execution_count +=1
        self.notebook = nbformat.from_dict(self.notebook)

    def getformatted(self):
        return nbformat.writes(self.notebook)