To be run in Jupyter to generate ../exercises/*.ipynb from ./*.ipynb


In [4]:
import json, os, re
from IPython.core.display import display, HTML

In [5]:
def convert(code):
    converted = []
    for line in code:
        assert 'todo' not in line.lower()
        m = re.match('^\s*(?:#|//|<!-- )--snip', line)
        if m:
            break
        m = re.match(r'^(\s*)(.*?)\s+(?:#|//)([^ @].*)$', line)
        converted.append((m.group(1) + m.group(3) + '\n') if m else line)
    return converted

In [6]:
SOURCE = '.'
DESTINATION = '../exercises'
NOTE_FMT = '### NOTE: This file is auto-generated from "%s".\n\n'
LINK_FMT = ('<li><a target="_blank" href="%s">%s</a> (%d bytes) &#8680; '
            '<a target="_blank" href="%s">%s</a> (%d bytes)</li>')
if not os.path.exists(DESTINATION):
    os.mkdir(DESTINATION)
display(HTML('<pre>'))
for name in sorted(os.listdir(SOURCE)):
    if not name.endswith('.ipynb') or name.startswith('_'):
        continue
    path = os.path.join(SOURCE, name)
    nb = json.load(open(path))
    for cell in nb['cells']:
        if cell['cell_type'] == 'code':
            cell['source'] = convert(cell['source'])
        if 'outputs' in cell: cell['outputs'] = []
        if 'execution_count' in cell: cell['execution_count'] = None
#     nb['cells'][0]['source'].insert(0, NOTE_FMT % os.path.abspath(path))
    path2 = os.path.join(DESTINATION, name)
    json.dump(nb, open(path2, 'w'))
    display(HTML(LINK_FMT % (path, path, os.path.getsize(path),
                             path2, path2, os.path.getsize(path2))))


  • ./0_colab.ipynb (158505 bytes) ⇨ ../exercises/0_colab.ipynb (44058 bytes)
  • ./1_data.ipynb (313427 bytes) ⇨ ../exercises/1_data.ipynb (48333 bytes)
  • ./2_keras.ipynb (145294 bytes) ⇨ ../exercises/2_keras.ipynb (41355 bytes)
  • ./3_eager.ipynb (5521526 bytes) ⇨ ../exercises/3_eager.ipynb (5393264 bytes)
  • ./4_predict.ipynb (37134 bytes) ⇨ ../exercises/4_predict.ipynb (25363 bytes)
  • ./5_cloud.ipynb (16185 bytes) ⇨ ../exercises/5_cloud.ipynb (10331 bytes)