Caffe2 - Python API
A deep learning, cross platform ML framework
jupyter_notebook_config.py
1 # Configuration file for a jupyter-notebook.
2 # Put this script into ~/.jupyter/ in order to get the post_save_hook implemented below.
3 # If you already have one, merge the content.
4 
5 import os
6 from subprocess import check_call
7 
8 def post_save(model, os_path, contents_manager):
9  """post-save hook for converting notebooks to .py scripts"""
10  if model['type'] != 'notebook':
11  return # only do this for notebooks
12 
13  notebook_dir, notebook_file_name = os.path.split(os_path)
14  check_call(
15  ['jupyter', 'nbconvert', '--to', 'script', notebook_file_name],
16  cwd=notebook_dir,
17  )
18  py_name = os.path.splitext(notebook_file_name)[0] + ".py"
19  full_py_name = os.path.join(notebook_dir, py_name)
20 
21  # Create py_gen/ dir if it doesn't exist and move the file there
22  new_dir = os.path.join(notebook_dir, 'py_gen')
23  if not os.path.exists(new_dir):
24  os.makedirs(new_dir)
25  new_py_location = os.path.join(new_dir, py_name)
26  os.rename(full_py_name, new_py_location)
27  full_py_name = new_py_location
28 
29  with open(full_py_name, 'r') as f:
30  data = f.read()
31  lines = data.split('\n')
32  good_lines = []
33  for line in lines:
34  if ("get_ipython().magic" not in line
35  and "get_ipython().run_line_magic" not in line):
36  good_lines.append(line)
37  # Update the file with do not edit preamble
38  with open(full_py_name, 'w') as f:
39  f.write("#########################################################\n")
40  f.write("#\n")
41  f.write("# DO NOT EDIT THIS FILE. IT IS GENERATED AUTOMATICALLY. #\n")
42  f.write("# PLEASE LOOK INTO THE README FOR MORE INFORMATION. #\n")
43  f.write("#\n")
44  f.write("#########################################################\n")
45  f.write("\n")
46 
47  for line in good_lines:
48  f.write(line + '\n')
49 
50 
51 c.FileContentsManager.post_save_hook = post_save