prevent double call of _cleanup, which harms usefiles (and is a bad idea in general)
[PyX.git] / www / mkipynb.py
blobe738c4740a3f1d7d7ead17cf6d2fa24dac38cfe4
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 nb = nbf.new_notebook()
18 cells = []
19 cells.append(nbf.new_markdown_cell(source="# " + title))
20 cells.append(nbf.new_code_cell(source=code, execution_count=1,
21 outputs=[nbf.new_output(output_type=u'execute_result', execution_count=1,
22 data={'image/png': base64.encodebytes(open("{}.png".format(filename), "rb").read()).decode("ascii"),
23 'image/svg+xml': open("{}.svg".format(filename), "r", encoding="utf-8").read()})]))
24 cells.append(nbf.new_markdown_cell(source=description))
25 nb = nbf.new_notebook(cells=cells, metadata={'language': 'python'})
26 open("{}.ipynb".format(filename), "w").write(nbf.writes(nb))