Skip to content

Instantly share code, notes, and snippets.

@cgabard

cgabard/cipyn.py Secret

Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgabard/4ac80ef17084255cf199 to your computer and use it in GitHub Desktop.
Save cgabard/4ac80ef17084255cf199 to your computer and use it in GitHub Desktop.
Convert IPython notebook to zds markdown
#!/usr/bin/env python3
import json
import sys
import base64
__N_IMG = 0
def handle_heading(c, write):
write("#" * c["level"] + " " + "".join(c["source"]) + "\n")
def handle_markdown(c, write):
write("".join(c["source"]))
def handle_code(c, write):
write("```{}\n".format(c["language"]))
write("".join(c["input"]))
write("\n```\n")
lo = c["outputs"]
if len(lo):
outp = lo[0]
if outp["output_type"] == "display_data" and "png" in outp:
global __N_IMG
png_data = base64.b64decode(outp["png"])
ifn = "Image{}.png".format(__N_IMG)
with open(ifn, "wb") as f:
f.write(png_data)
write("\n**Sortie:**\n\n")
write("![]({})\n".format(ifn))
__N_IMG += 1
elif "text" in outp:
write("\n**Sortie:** \n`")
write("```text\n")
write("".join(outp["text"]))
write("\n```\n")
else:
print("Output type '{}' not supported".format(outp["output_type"]))
def conv_ipython_notebook(filename_to_conv, output_filename):
with open(filename_to_conv) as fjson:
odc_ipy = json.load(fjson)
vmajor = odc_ipy["nbformat"]
vminor = odc_ipy["nbformat_minor"]
if vmajor != 3 or vminor != 0:
print("Warning : this source file is from iPython Notebook {}.{}. This script is designed to support iPython Notebbok {}.{}.".format(vmajor, vminor, 3, 0))
data = []
write = lambda tx : data.append(tx)
hh = {"markdown": handle_markdown,
"code": handle_code,
"heading": handle_heading,
}
ws = odc_ipy["worksheets"][0]
for c in ws["cells"]:
hh[c["cell_type"]](c, write)
write("\n\n")
output = "".join(data)
with open(output_filename, "w") as f:
f.write(output)
if __name__ == "__main__":
conv_ipython_notebook(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment