copy figures as well

website
Jake VanderPlas 2017-08-14 13:26:42 -07:00
parent 12a9c394cc
commit db6e9e8da6
1 changed files with 32 additions and 11 deletions

View File

@ -4,12 +4,13 @@ creates pages which wrap them and link together.
"""
import os
import nbformat
import shutil
PAGEFILE = """title: {title}
slug: {slug}
Template: page
{{% notebook notebooks/{notebook_file} cells[2:] %}}
{{% notebook notebooks/{notebook_file} cells[{cells}] %}}
"""
@ -24,38 +25,58 @@ PAGE_DEST_DIR = abspath_from_here('content', 'pages')
def copy_notebooks():
nblist = sorted(os.listdir(NB_SOURCE_DIR))
nblist = sorted(nb for nb in os.listdir(NB_SOURCE_DIR)
if nb.endswith('.ipynb'))
name_map = {nb: nb.rsplit('.', 1)[0] + '.html'
for nb in nblist}
figsource = abspath_from_here('..', 'notebooks', 'figures')
figdest = abspath_from_here('content', 'figures')
if os.path.exists(figdest):
shutil.rmtree(figdest)
shutil.copytree(figsource, figdest)
figurelist = os.listdir(abspath_from_here('content', 'figures'))
figure_map = {os.path.join('figures', fig) : os.path.join('/figures', fig)
for fig in figurelist}
for nb in nblist:
base, ext = os.path.splitext(nb)
if ext != '.ipynb':
continue
print('-', nb)
content = nbformat.read(os.path.join(NB_SOURCE_DIR, nb),
as_version=4)
title = content.cells[2].source
if not title.startswith('#'):
raise ValueError('title not found in third cell')
title = title.lstrip('#').strip()
# put nav below title
content.cells[1], content.cells[2] = content.cells[2], content.cells[1]
if nb == 'Index.ipynb':
cells = '1:'
title = 'Python Data Science Handbook'
else:
cells = '2:'
# put nav below title
title = content.cells[2].source
if not title.startswith('#') or len(title.splitlines()) > 1:
raise ValueError('title not found in third cell')
title = title.lstrip('#').strip()
content.cells[1], content.cells[2] = content.cells[2], content.cells[1]
for cell in content.cells:
if cell.cell_type == 'markdown':
for nbname, htmlname in name_map.items():
if nbname in cell.source:
cell.source = cell.source.replace(nbname, htmlname)
for figname, newfigname in figure_map.items():
if figname in cell.source:
cell.source = cell.source.replace(figname, newfigname)
nbformat.write(content, os.path.join(NB_DEST_DIR, nb))
pagefile = os.path.join(PAGE_DEST_DIR, base + '.md')
with open(pagefile, 'w') as f:
f.write(PAGEFILE.format(title=title,
slug=base.lower(),
notebook_file=nb))
notebook_file=nb,
cells=cells))
if __name__ == '__main__':
copy_notebooks()