-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathipynb_generator.py
More file actions
241 lines (204 loc) · 7.87 KB
/
ipynb_generator.py
File metadata and controls
241 lines (204 loc) · 7.87 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#coding:utf-8
"""
http://hplgit.github.io/doconce/doc/pub/ipynb/ipynb_generator.html
https://github.com/hplgit/doconce/blob/master/doc/src/ipynb/ipynb_generator.py
"""
import re
from logging import getLogger, StreamHandler, NullHandler, Formatter, DEBUG
logger = getLogger(__name__)
# handler = NullHandler()
handler = StreamHandler()
formatter = Formatter('%(levelname)s:%(name)s:%(message)s')
handler.setLevel(DEBUG)
handler.setFormatter(formatter)
logger.setLevel(DEBUG)
logger.addHandler(handler)
def preprocess(text):
retval = []
isinside = False
for line in text.splitlines():
tmp = line.strip()
if tmp.startswith('```'):
if tmp[3: ] == '':
if isinside:
isinside = False
retval.append(line)
retval.append('<!--- --->')
else:
isinside = True
retval.append('<!---raw--->')
retval.append(line)
else:
if isinside:
raise SyntaxError(
"Wrong syntax. A code block starts in the other block.")
isinside = True
retval.append('<!---{:s}--->'.format(tmp[3: ]))
retval.append(line)
else:
retval.append(line)
return '\n'.join(retval)
def readmd(text):
delimiter = re.compile(r'<!---\s*([a-zA-Z0-9]+)?\s*--->')
cell_type, language = 'markdown', None
cells = []
for line in text.splitlines():
m = delimiter.search(line)
if m is not None:
if m is not None:
shortname = m.group(1)
if shortname is None:
cell_type = 'markdown'
language = None
elif shortname == 'raw':
cell_type = 'raw'
language = None
else:
cell_type = 'code'
language = shortname
cells.append([cell_type, language, []])
else:
raise SyntaxError(
'Wrong syntax of cell delimiter: \n{s}'.format(line))
else:
if len(cells) == 0:
cells.append([cell_type, language, []]) ## the first line
if cell_type == 'markdown':
cells[-1][2].append(line)
elif cell_type in ('code', 'raw'):
if not line.lstrip().startswith('```'):
cells[-1][2].append(line)
else:
raise SyntaxError(
'line\n {:s}\nhas not beggining cell delimiter [{}]'.format(line, cell_type))
return cells
def translatenb(cells, nbversion=4):
if nbversion == 3:
return translatenb_v3(cells)
elif nbversion == 4:
return translatenb_v4(cells)
else:
raise ValueError(
'nbversion [{}] must be either 3 or 4'.format(nbversion))
def translatenb_v3(cells):
from nbformat.v3 import (
new_code_cell, new_text_cell, new_worksheet,
new_notebook, new_metadata, new_author)
from nbformat.v3 import new_text_cell
nb = new_worksheet()
for cell_type, language, block in cells:
block = '\n'.join(block)
if cell_type == 'markdown':
nb.cells.append(
new_text_cell(u'markdown', source=block))
elif cell_type == 'code':
nb.cells.append(new_code_cell(input=block))
elif cell_type == 'raw':
nb.cells.append(new_text_cell('raw', source=block))
else:
raise ValueError('Wrong cell_type was given [{}]'.format(cell_type))
nb = new_notebook(worksheets=[nb], metadata=new_metadata())
# upgrade notebook to v4
from nbformat.v4 import upgrade
nb = upgrade(nb)
import nbformat.v4.nbjson as nbjson
return nbjson.writes(nb)
def translatenb_v4(cells):
from nbformat.v4 import (
new_code_cell, new_markdown_cell, new_notebook)
from nbformat.v4.nbbase import new_raw_cell
nb_cells = []
for cell_type, language, block in cells:
block = '\n'.join(block)
if cell_type == 'markdown':
if block != "":
nb_cells.append(
new_markdown_cell(source=block))
elif cell_type == 'code':
nb_cells.append(new_code_cell(source=block))
elif cell_type == 'raw':
nb_cells.append(new_raw_cell(source=block))
else:
raise ValueError('Wrong cell_type was given [{}]'.format(cell_type))
nb = new_notebook(cells=nb_cells)
from nbformat import writes
return writes(nb, version=4)
def executenb(text, nbversion=4, timeout=600, kernel_name='python3', run_path='.', outputname=None):
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors.execute import CellExecutionError
nb = nbformat.reads(text, as_version=nbversion)
ep = ExecutePreprocessor(timeout=timeout, kernel_name=kernel_name)
try:
out = ep.preprocess(nb, {'metadata': {'path': run_path}})
except CellExecutionError:
msg = 'Error executing the notebook.'
if outputname is not None:
msg += ' See notebook "{:s}" for the traceback.'.format(outputname)
logger.error(msg)
raise
finally:
return nbformat.writes(nb)
if __name__ == "__main__":
def main(text, filename=None, execute=True, timeout=600, preproc=True):
if preproc:
text = preprocess(text)
# print(text)
cells = readmd(text)
# print(cells)
output = translatenb(cells)
if execute:
output = executenb(output, timeout=timeout, outputname=filename)
if filename is not None:
with open(filename, 'w') as fout:
fout.write(output)
return output
text = """## Test of Jupyter Notebook generator
This is a generated file using `misc/ipynb_generator.py`.
## Math
This is a test notebook.
$$y'=ky$$
```python
import numpy as np
print(np.exp(1.0))
```
The above is a Python code for the following:
```python
print(np.log(1.0))
```
## Text
This is the footer notes for this generated notebook.
"""
import argparse
parser = argparse.ArgumentParser(description='Generate Jupyter notebooks from markdown files.')
parser.add_argument('filenames', metavar='FILENAME', type=str, nargs='*', help='markdown filenames')
parser.add_argument('--noexec', '-n', action='store_true', help='save notebooks without execution')
parser.add_argument('--nooverwrite', action='store_true', help='avoid to overwrite an existing file')
parser.add_argument('--suffix', action='store', type=str, default='.ipynb', help='suffix for the output')
parser.add_argument('--prefix', action='store', type=str, help='prefix for the output')
parser.add_argument('--timeout', action='store', type=int, default=600, help='timeout for the execution')
parser.add_argument('--nopreproc', action='store_true', help='skip preprocessing')
args = parser.parse_args()
filenames = args.filenames
execute = not args.noexec
overwrite = not args.nooverwrite
suffix = args.suffix
prefix = args.prefix
timeout = args.timeout
preproc = not args.nopreproc
if len(filenames) == 0:
print(main(text, timeout=timeout))
import sys
sys.exit(0)
import os.path
for filename in filenames:
with open(filename, 'r') as fin:
text = fin.read()
header, tail = os.path.split(filename)
root, ext = os.path.splitext(tail)
outputname = '{:s}{:s}'.format(root, suffix)
outputname = os.path.join(header if prefix is None else prefix, outputname)
if not overwrite and os.path.isfile(outputname):
raise RuntimeError(
'An output file [{}] already exists'.format(outputname))
main(text, outputname, execute, timeout, preproc=preproc)