-
Notifications
You must be signed in to change notification settings - Fork 454
/
Copy pathgenfeatured.py
73 lines (58 loc) · 2.24 KB
/
genfeatured.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
65
66
67
68
69
70
71
72
73
import sys
import os
import os.path as op
import re
from util import get_recipe_number, get_recipe_name
current_dir = op.dirname(os.path.abspath(__file__))
code_dir = op.join(current_dir, '../')
featured_dir = op.join(code_dir, 'featured/')
site_dir = op.join(current_dir, '../../ipython-books.github.io')
index_path = op.join(site_dir, 'index.html')
def get_title(notebook_filename):
return get_recipe_name(op.join(featured_dir, notebook_filename))
def get_snippet(name):
with open(index_path, 'r') as f:
contents = f.read()
start = contents.index('<!-- BEGIN {0} -->'.format(name))
end = contents.index('<!-- END {0} -->'.format(name))
return contents[start:end]
def get_navbar():
return get_snippet('NAVBAR')
def get_footer():
return get_snippet('FOOTER')
NAVBAR = get_navbar()
FOOTER = get_footer()
def transform_featured(notebook_filename):
notebook_filename = op.basename(notebook_filename)
number = int(notebook_filename[:2])
notebook_basename = op.basename(notebook_filename)
input_path = op.realpath(op.join(featured_dir, notebook_filename))
output_path = op.realpath(op.join(site_dir,
'featured-{0:02d}'.format(number)))
# Get the recipe's title.
title = get_title(input_path)
# Generate the nbconvert command.
command = ('ipython nbconvert {f} --to html '
'--template featured.tpl --output {of}').format(
f=input_path,
of=output_path)
os.system(command)
output_path += '.html'
# Replace the templates: title, navbar, footer.
with open(output_path, 'r') as f:
contents = f.read()
contents = contents.replace('%TITLE%', title)
contents = contents.replace('%NAVBAR%', NAVBAR)
contents = contents.replace('%FOOTER%', FOOTER)
with open(output_path, 'w') as f:
f.write(contents)
def main():
if len(sys.argv) == 1:
for nb in sorted([x for x in os.listdir(featured_dir)
if x.endswith('.ipynb')]):
print(nb)
transform_featured(nb)
else:
transform_featured(sys.argv[1])
if __name__ == '__main__':
main()