-
Notifications
You must be signed in to change notification settings - Fork 3
/
generate_notebooks.py
executable file
·64 lines (51 loc) · 2.18 KB
/
generate_notebooks.py
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
import os
import sys
import glob
import shutil
import nbformat as nbf
from nbformat.v4 import reads, writes, new_markdown_cell, new_code_cell, new_notebook
from nbconvert.exporters.notebook import NotebookExporter
import codecs
note = '''
### Quickstart
To run the code below:
1. Click on the cell to select it.
2. Press `SHIFT+ENTER` on your keyboard or press the play button (<button class='fa fa-play icon-play btn btn-xs btn-default'></button>) in the toolbar above.
Feel free to create new cells using the plus button (<button class='fa fa-plus icon-plus btn btn-xs btn-default'></button>), or pressing `SHIFT+ENTER` while this cell is selected.
<div class="alert alert-warning" role="alert" style="margin: 10px">
<p>**WARNING**</p>
<p>Don't rely on this server for anything you want to last - your server will be *deleted after 10 minutes of inactivity*.</p>
</div>
'''
if not os.path.exists('tutorials'):
os.mkdir('tutorials')
for notebook in glob.glob('_tutorials/*.ipynb'):
with open(notebook, 'r') as f:
content = reads(f.read())
# Insert a note about Jupyter notebooks at the top with a download link
content.cells.insert(1, new_markdown_cell(note))
(path, filename) = os.path.split(notebook) #[-1]
with open('tutorials/' + filename, 'w') as f:
nbf.write(content, f)
shutil.rmtree('_tutorials')
magic = '''%matplotlib notebook\n'''
if not os.path.exists('examples'):
os.mkdir('examples')
for root, subfolders, files in os.walk('_examples'):
for file in files:
if not file.endswith('.py'):
continue
example = os.path.join(root, file)
with open(example, 'r') as f:
code = f.read()
(base, ext) = os.path.splitext(os.path.split(example)[-1])
# Create blank notebook
content = new_notebook()
content['cells'] = [new_markdown_cell(note),
new_code_cell(magic + code)]
if not os.path.exists(root[1:]):
os.mkdir(root[1:])
exporter = NotebookExporter()
output, _ = exporter.from_notebook_node(content)
codecs.open(''.join([root[1:], '/', base, '.ipynb']), 'w', encoding='utf-8').write(output)
shutil.rmtree('_examples')