forked from facebookarchive/tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorials_to_script_converter.py
More file actions
60 lines (51 loc) · 1.96 KB
/
tutorials_to_script_converter.py
File metadata and controls
60 lines (51 loc) · 1.96 KB
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
import os
from os import listdir
from subprocess import check_call
def convert_notebook(notebook_path):
# Generate .py file from a notebook
notebook_dir, notebook_file_name = os.path.split(notebook_path)
check_call(
['jupyter', 'nbconvert', '--to', 'script', notebook_file_name],
cwd=notebook_dir,
)
py_name = os.path.splitext(notebook_file_name)[0] + ".py"
full_py_name = os.path.join(notebook_dir, py_name)
# Create py_gen/ dir if it doesn't exist and move the file there
new_dir = os.path.join(notebook_dir, 'py_gen')
if not os.path.exists(new_dir):
os.makedirs(new_dir)
new_py_location = os.path.join(new_dir, py_name)
os.rename(full_py_name, new_py_location)
full_py_name = new_py_location
with open(full_py_name, 'r') as f:
data = f.read()
lines = data.split('\n')
good_lines = []
for line in lines:
if ("get_ipython().magic" not in line
and "get_ipython().run_line_magic" not in line):
good_lines.append(line)
# Update the file with do not edit preamble
with open(full_py_name, 'w') as f:
f.write("#########################################################\n")
f.write("#\n")
f.write("# DO NOT EDIT THIS FILE. IT IS GENERATED AUTOMATICALLY. #\n")
f.write("# PLEASE LOOK INTO THE README FOR MORE INFORMATION. #\n")
f.write("#\n")
f.write("#########################################################\n")
f.write("\n")
for line in good_lines:
f.write(line + '\n')
def main():
tutorials_folder = os.path.dirname(os.path.realpath(__file__))
print("tutorials_folder: ", tutorials_folder)
files = [
os.path.join(tutorials_folder, f)
for f in listdir(tutorials_folder)
if os.path.isfile(os.path.join(tutorials_folder, f))
and f.endswith('ipynb')
]
for f in files:
convert_notebook(f)
if __name__ == '__main__':
main()