##// END OF EJS Templates
Adding nbformat subpackage.
Brian E. Granger -
Show More
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
@@ -0,0 +1,45 b''
1 from base64 import encodestring, decodestring
2
3
4 def base64_decode(self, nb):
5 """Base64 encode all bytes objects in the notebook."""
6 for ws in nb['worksheets']:
7 for cell in ws['cells']:
8 if cell['cell_type'] == 'code':
9 if cell.get('image/png',''):
10 cell['image/png'] = bytes(decodestring(cell['image/png']))
11 return nb
12
13
14 def base64_encode(self, nb):
15 """Base64 decode all binary objects in the notebook."""
16 for ws in nb['worksheets']:
17 for cell in ws['cells']:
18 if cell['cell_type'] == 'code':
19 if cell.get('image/png',''):
20 cell['image/png'] = unicode(encodestring(cell['image/png']))
21 return nb
22
23
24 class NotebookReader(object):
25
26 def reads(self, s, **kwargs):
27 """Read a notebook from a string."""
28 raise NotImplementedError("loads must be implemented in a subclass")
29
30 def read(self, fp, **kwargs):
31 """Read a notebook from a file like object"""
32 return self.loads(fp.read(), **kwargs)
33
34
35 class NotebookWriter(object):
36
37 def writes(self, nb, **kwargs):
38 """Write a notebook to a string."""
39 raise NotImplementedError("loads must be implemented in a subclass")
40
41 def write(self, nb, fp, **kwargs):
42 """Write a notebook to a file like object"""
43 return fp.write(self.dumps(nb,**kwargs))
44
45
@@ -0,0 +1,76 b''
1 """The basic dict based notebook format."""
2
3 import uuid
4
5
6 def new_code_cell(input=None, prompt_number=None, output_text=None, output_png=None,
7 output_html=None, output_svg=None, output_latex=None, output_json=None,
8 output_javascript=None):
9 """Create a new code cell with input and output"""
10 cell = {}
11 cell['cell_type'] = 'code'
12 if input is not None:
13 cell['input'] = unicode(input)
14 if prompt_number is not None:
15 cell['prompt_number'] = int(prompt_number)
16
17 output = {}
18 if output_text is not None:
19 output['text/plain'] = unicode(output_text)
20 if output_png is not None:
21 output['image/png'] = bytes(output_png)
22 if output_html is not None:
23 output['text/html'] = unicode(output_html)
24 if output_svg is not None:
25 output['image/svg+xml'] = unicode(output_svg)
26 if output_latex is not None:
27 output['text/latex'] = unicode(output_latex)
28 if output_json is not None:
29 output['application/json'] = unicode(output_json)
30 if output_javascript is not None:
31 output['application/javascript'] = unicode(output_javascript)
32
33 cell['output'] = output
34 return cell
35
36
37 def new_text_cell(text=None):
38 """Create a new text cell."""
39 cell = {}
40 if text is not None:
41 cell['text'] = unicode(text)
42 cell['cell_type'] = 'text'
43 return cell
44
45
46 def new_worksheet(name=None, cells=None):
47 """Create a worksheet by name with with a list of cells."""
48 ws = {}
49 if name is not None:
50 ws['name'] = unicode(name)
51 else:
52 ws['name'] = u''
53 if cells is None:
54 ws['cells'] = []
55 else:
56 ws['cells'] = list(cells)
57 return ws
58
59
60 def new_notebook(name=None, id=None, worksheets=None):
61 """Create a notebook by name, id and a list of worksheets."""
62 nb = {}
63 if name is not None:
64 nb['name'] = unicode(name)
65 else:
66 nb['name'] = u''
67 if id is None:
68 nb['id'] = unicode(uuid.uuid4())
69 else:
70 nb['id'] = unicode(id)
71 if worksheets is None:
72 nb['worksheets'] = []
73 else:
74 nb['worksheets'] = list(worksheets)
75 return nb
76
@@ -0,0 +1,38 b''
1 """Read and write notebooks in JSON format."""
2
3 from base64 import encodestring
4 from .base import NotebookReader, NotebookWriter, base64_decode
5 import json
6
7
8 class BytesEncoder(json.JSONEncoder):
9 def default(self, obj):
10 if isinstance(obj, bytes):
11 return unicode(encodestring(bytes))
12 return json.JSONEncoder.default(self, obj)
13
14
15 class JSONReader(NotebookReader):
16
17 def reads(s, **kwargs):
18 nb = json.loads(s, **kwargs)
19 nb = base64_decode(nb)
20 return nb
21
22
23 class JSONWriter(NotebookWriter):
24
25 def writes(nb, **kwargs):
26 kwargs['cls'] = BytesEncoder
27 kwargs['indent'] = 4
28 return json.dumps(nb, **kwargs)
29
30
31 _reader = JSONReader()
32 _writer = JSONWriter()
33
34 reads = _reader.reads
35 read = _reader.read
36 write = _writer.write
37 writes = _writer.writes
38
@@ -0,0 +1,46 b''
1 """Read and write notebooks as regular .py files."""
2
3 from .base import NotebookReader, NotebookWriter
4 from .nbdict import new_code_cell, new_worksheet, new_notebook
5
6
7 class PyReader(NotebookReader):
8
9 def reads(s, **kwargs):
10 lines = s.splitlines()
11 cells = []
12 cell_lines = []
13 for line in lines:
14 if line.startswith('# <codecell>'):
15 code = '\n'.join(cell_lines)
16 code = code.strip('\n')
17 if code:
18 cells.append(new_code_cell(input=code))
19 cell_lines = []
20 else:
21 cell_lines.append(line)
22 ws = new_worksheet(cells=cells)
23 nb = new_notebook(worksheets=[ws])
24 return nb
25
26
27 class PyWriter(NotebookWriter):
28
29 def writes(nb, **kwargs):
30 lines = []
31 for ws in nb['worksheets']:
32 for cell in ws['cells']:
33 if cell['cell_type'] == 'code':
34 input = cell['input']
35 lines.extend(input.splitlines())
36 lines.extend(['','# <codecell>',''])
37 return ''.join(lines)
38
39
40 _reader = PyReader()
41 _writer = PyWriter()
42
43 reads = _reader.reads
44 read = _reader.read
45 write = _writer.write
46 writes = _writer.writes
@@ -0,0 +1,48 b''
1 """Read and write notebook files as XML."""
2
3 from xml.etree import ElementTree as ET
4
5 from .base import NotebookReader, NotebookWriter
6 from .nbdict import new_code_cell, new_worksheet, new_notebook
7
8
9 class XMLReader(NotebookReader):
10
11 def reads(s, **kwargs):
12 pass
13
14
15 class XMLWriter(NotebookWriter):
16
17 def writes(nb, **kwargs):
18 nb_e = ET.Element('notebook')
19 name_e = ET.SubElement(nb_e, 'name')
20 name_e.text = nb.get('name','')
21 id_e = ET.SubElement(nb_e, 'id')
22 id_e.text = nb.get('id','')
23 for ws in nb['worksheets']:
24 ws_e = ET.SubElement(nb_e, 'worksheet')
25 ws_name_e = ET.SubElement(ws_e, 'name')
26 ws_name_e.text = ws.get('name','')
27 for cell in ws['cells']:
28 cell_type = cell['cell_type']
29 if cell_type == 'code':
30 output = cell['output']
31 cell_e = ET.SubElement(ws_e, 'cell')
32 input_e = ET.SubElement(cell_e, 'input')
33 input_e.text = cell.get('input','')
34 output_e = ET.SubElement(cell_e, 'output')
35 text_e = ET.SubElement(output_e, 'text')
36 text_e.text = cell.output
37 elif cell_type == 'text':
38 pass
39
40
41
42 _reader = XMLReader()
43 _writer = XMLWriter()
44
45 reads = _reader.reads
46 read = _reader.read
47 write = _writer.write
48 writes = _writer.writes
General Comments 0
You need to be logged in to leave comments. Login now