Debian Codegraph @

dev/tools/docs/build_tutorials.py

raw ◀ ▶
1 Debian patch touch this file
1
2
3 import os
4 import shutil
5 import glob
6 import codecs
7
8 from nbformat import NotebookNode
9 from nbformat.v4 import reads
10 from nbconvert.preprocessors import ExecutePreprocessor
11 from nbconvert.exporters.notebook import NotebookExporter
12 from nbconvert.exporters.rst import RSTExporter
13
14 from brian2.utils.stringtools import deindent, indent
15
16
17 src_dir = os.path.abspath('../../../tutorials')
18 target_dir = os.path.abspath('../../../docs_sphinx/resources/tutorials')
19
20 # Start from scratch to avoid left-over files due to renamed tutorials, changed
21 # cell numbers, etc.
22 if os.path.exists(target_dir):
23 shutil.rmtree(target_dir)
24 os.mkdir(target_dir)
25
26 tutorials = []
27 for fname in sorted(glob.glob1(src_dir, '*.ipynb')):
28 basename = fname[:-6]
29 output_ipynb_fname = os.path.join(target_dir, fname)
30 output_rst_fname = os.path.join(target_dir, basename + '.rst')
31
32 print('Running', fname)
33 with open(os.path.join(src_dir, fname), 'r') as f:
34 notebook = reads(f.read())
35
36 # The first line of the tutorial file should give the title
37 title = notebook.cells[0]['source'].split('\n')[0].strip('# ')
38 tutorials.append((basename, title))
39
40 # Execute the notebook
41 preprocessor = ExecutePreprocessor(timeout=None)
42 preprocessor.allow_errors = True
43 notebook, _ = preprocessor.preprocess(notebook,
44 {'metadata': {'path': src_dir}})
45
46 print('Saving notebook and converting to RST')
47 exporter = NotebookExporter()
48 output, _ = exporter.from_notebook_node(notebook)
49 with codecs.open(output_ipynb_fname, 'w', encoding='utf-8') as f:
50 f.write(output)
51
52 # Insert a note about ipython notebooks with a download link
53 note = deindent('''
54 .. only:: html
55
•56 .. |launchbinder| image:: file:///usr/share/doc/python-brian-doc/docs/badge.svg
57 .. _launchbinder: https://mybinder.org/v2/gh/brian-team/brian2-binder/master?filepath=tutorials/{tutorial}.ipynb
58
59 .. note::
60 This tutorial is a static non-editable version. You can launch an
61 interactive, editable version without installing any local files
62 using the Binder service (although note that at some times this
63 may be slow or fail to open): |launchbinder|_
64
65 Alternatively, you can download a copy of the notebook file
66 to use locally: :download:`{tutorial}.ipynb`
67
68 See the :doc:`tutorial overview page <index>` for more details.
69
70 '''.format(tutorial=basename))
71 notebook.cells.insert(1, NotebookNode(cell_type='raw', metadata={},
72 source=note))
73 exporter = RSTExporter()
74 output, resources = exporter.from_notebook_node(notebook,
75 resources={'unique_key': basename+'_image'})
76 with codecs.open(output_rst_fname, 'w', encoding='utf-8') as f:
77 f.write(output)
78
79 for image_name, image_data in resources['outputs'].items():
80 with open(os.path.join(target_dir, image_name), 'wb') as f:
81 f.write(image_data)
82
83 print('Generating index.rst')
84
85 text = '''
86 ..
87 This is a generated file, do not edit directly.
88 (See dev/tools/docs/build_tutorials.py)
89
90 Tutorials
91 =========
92
93 The tutorial consists of a series of `Jupyter Notebooks`_ [#]_.
94
95 .. only:: html
96
97 You can quickly view these using the first links below. To use them interactively - allowing you
98 to edit and run the code - there are two options. The easiest option is to click
99 on the "Launch Binder" link, which will open up an interactive version in the
100 browser without having to install Brian locally. This uses the
101 `mybinder.org <http://mybinder.org>`_ service. Occasionally, this
102 service will be down or running slowly. The other option is to download the
103 notebook file and run it locally, which requires you to have Brian installed.
104
105 For more information about how to use Jupyter Notebooks, see the
106 `Jupyter Notebook documentation`_.
107
108 .. toctree::
109 :maxdepth: 1
110 :titlesonly:
111
112 '''
113 for tutorial, _ in tutorials:
114 text += ' ' + tutorial + '\n'
115 text += '''
116 .. only:: html
117
118 Interactive notebooks and files
119 -------------------------------
120 '''
121 for tutorial, _ in tutorials:
122 text += indent(deindent('''
•123 .. |launchbinder{tutid}| image:: file:///usr/share/doc/python-brian-doc/docs/badge.svg
124 .. _launchbinder{tutid}: https://mybinder.org/v2/gh/brian-team/brian2-binder/master?filepath=tutorials/{tutorial}.ipynb
125 '''.format(tutorial=tutorial, tutid=tutorial.replace('-', ''))))
126
127 text += '\n'
128 for tutorial, title in tutorials:
129 text += ' * |launchbinder{tutid}|_ :download:`{title} <{tutorial}.ipynb>`\n'.format(title=title,
130 tutorial=tutorial, tutid=tutorial.replace('-', ''))
131 text += '''
132
133 .. _`Jupyter Notebooks`: http://jupyter-notebook-beginner-guide.readthedocs.org/en/latest/what_is_jupyter.html
134 .. _`Jupyter`: http://jupyter.org/
135 .. _`Jupyter Notebook documentation`: http://jupyter.readthedocs.org/
136
137 .. [#] Formerly known as "IPython Notebooks".
138 '''
139 with open(os.path.join(target_dir, 'index.rst'), 'w') as f:
140 f.write(text)