update mkipynb to notebook version 4
[PyX.git] / www / mkipynb.py
blob3861b9a9211ddfcee772c6db0ca4efa25d0e5ae2
1 import base64, os, re, sys
2 import IPython.nbformat.v4 as nbf
4 filename = os.path.splitext(sys.argv[1])[0]
6 try:
7 title, description = open("{}.txt".format(filename), encoding="utf-8").read().split('\n\n', 1)
8 except IOError:
9 title, description = filename, ""
10 description = description.replace("...", "").replace("'''", "**").replace("''", "*")
11 bendpattern = re.compile("^!+", re.MULTILINE)
12 bendcode = '<img src="http://pyx.sourceforge.net/bend.png" align="left">'
13 description = re.sub(bendpattern, lambda m: bendcode*(m.end()-m.start()), description)
14 code = open("{}.py".format(filename), encoding="utf-8").read()
15 code = re.sub('\.writeEPSfile\(("[a-z]+")?\)\n.*writePDFfile\(("[a-z]+")?\)\n.*writeSVGfile\(("[a-z]+")?\)\n', "", code)
17 print(description)
19 nb = nbf.new_notebook()
20 cells = []
21 cells.append(nbf.new_markdown_cell(source="# " + title))
22 cells.append(nbf.new_code_cell(source=code, execution_count=1,
23 outputs=[nbf.new_output(output_type=u'execute_result', execution_count=1,
24 data={'image/png': base64.encodebytes(open("{}.png".format(filename), "rb").read()).decode("ascii"),
25 'image/svg+xml': open("{}.svg".format(filename), "r", encoding="utf-8").read()})]))
26 cells.append(nbf.new_markdown_cell(source=description))
27 nb = nbf.new_notebook(cells=cells, metadata={'language': 'python'})
28 open("{}.ipynb".format(filename), "w").write(nbf.writes(nb))