1
1
"""
2
2
This module translates .py files to .ipynb and vice versa
3
3
"""
4
+ from typing import Optional
4
5
import os
5
6
import sys
6
7
import json
7
- import argparse
8
+
9
+ from p2j .utils import _check_files
8
10
9
11
# Path to directory
10
12
HERE = os .path .abspath (os .path .dirname (__file__ ))
15
17
TWELVE_SPACES = "{:<12}" .format ("" )
16
18
17
19
18
- def p2j (source_filename , target_filename , overwrite ):
20
+ def python2jupyter (source_filename : str , target_filename : str , overwrite : bool = False ):
19
21
"""Convert Python scripts to Jupyter notebooks.
20
22
21
23
Args:
@@ -26,21 +28,21 @@ def p2j(source_filename, target_filename, overwrite):
26
28
27
29
target_filename = _check_files (
28
30
source_filename , target_filename , overwrite , conversion = "p2j" )
29
-
31
+
30
32
# Check if source file exists and read
31
33
try :
32
- with open (source_filename , 'r' , encoding = ' utf-8' ) as infile :
33
- data = [l .rstrip (' \n ' ) for l in infile ]
34
+ with open (source_filename , "r" , encoding = " utf-8" ) as infile :
35
+ data = [l .rstrip (" \n " ) for l in infile ]
34
36
except FileNotFoundError :
35
37
print ("Source file not found. Specify a valid source file." )
36
38
sys .exit (1 )
37
39
38
40
# Read JSON files for .ipynb template
39
- with open (HERE + ' /templates/cell_code.json' , encoding = ' utf-8' ) as file :
41
+ with open (HERE + " /templates/cell_code.json" , encoding = " utf-8" ) as file :
40
42
CODE = json .load (file )
41
- with open (HERE + ' /templates/cell_markdown.json' , encoding = ' utf-8' ) as file :
43
+ with open (HERE + " /templates/cell_markdown.json" , encoding = " utf-8" ) as file :
42
44
MARKDOWN = json .load (file )
43
- with open (HERE + ' /templates/metadata.json' , encoding = ' utf-8' ) as file :
45
+ with open (HERE + " /templates/metadata.json" , encoding = " utf-8" ) as file :
44
46
MISC = json .load (file )
45
47
46
48
# Initialise variables
@@ -158,111 +160,6 @@ def p2j(source_filename, target_filename, overwrite):
158
160
final .update (MISC )
159
161
160
162
# Write JSON to target file
161
- with open (target_filename , 'w' , encoding = ' utf-8' ) as outfile :
163
+ with open (target_filename , "w" , encoding = " utf-8" ) as outfile :
162
164
json .dump (final , outfile , indent = 1 , ensure_ascii = False )
163
165
print ("Notebook {} written." .format (target_filename ))
164
-
165
-
166
- def _check_files (source_file , target_file , overwrite , conversion ):
167
- """File path checking
168
-
169
- Check if
170
- 1) Name of source file is valid.
171
- 2) Target file already exists. If not, create.
172
-
173
- Does not check if source file exists. That will be done
174
- together when opening the file.
175
- """
176
-
177
- if conversion == "p2j" :
178
- expected_src_file_ext = ".py"
179
- expected_tgt_file_ext = ".ipynb"
180
- else :
181
- expected_src_file_ext = ".ipynb"
182
- expected_tgt_file_ext = ".py"
183
-
184
- file_base = os .path .splitext (source_file )[0 ]
185
- file_ext = os .path .splitext (source_file )[- 1 ]
186
-
187
- if file_ext != expected_src_file_ext :
188
- print ("Wrong file type specified. Expected {} " .format (expected_src_file_ext ) +
189
- "extension but got {} instead." .format (file_ext ))
190
- sys .exit (1 )
191
-
192
- # Check if target file is specified and exists. If not specified, create
193
- if target_file is None :
194
- target_file = file_base + expected_tgt_file_ext
195
- if not overwrite and os .path .isfile (target_file ):
196
- # FileExistsError
197
- print ("File {} exists. " .format (target_file ) +
198
- "Add -o flag to overwrite this file, " +
199
- "or specify a different target filename using -t." )
200
- sys .exit (1 )
201
-
202
- return target_file
203
-
204
-
205
- def j2p (source_filename , target_filename , overwrite ):
206
- """Convert Jupyter notebooks to Python scripts
207
-
208
- Args:
209
- source_filename (str): Path to Jupyter notebook.
210
- target_filename (str): Path to name of Python script. Optional.
211
- overwrite (bool): Whether to overwrite an existing Python script.
212
- with_markdown (bool, optional): Whether to include markdown. Defaults to False.
213
- """
214
-
215
- target_filename = _check_files (
216
- source_filename , target_filename , overwrite , conversion = "j2p" )
217
-
218
- # Check if source file exists and read
219
- try :
220
- with open (source_filename , 'r' , encoding = 'utf-8' ) as infile :
221
- myfile = json .load (infile )
222
- except FileNotFoundError :
223
- print ("Source file not found. Specify a valid source file." )
224
- sys .exit (1 )
225
-
226
- final = ['' .join (["# " + line .lstrip () for line in cell ["source" ] if not line .strip () == "" ])
227
- if cell ["cell_type" ] == "markdown" else '' .join (cell ["source" ])
228
- for cell in myfile ['cells' ]]
229
- final = '\n \n ' .join (final )
230
- final = final .replace ("<br>" , "" )
231
-
232
- with open (target_filename , "a" , encoding = 'utf-8' ) as outfile :
233
- outfile .write (final )
234
- print ("Python script {} written." .format (target_filename ))
235
-
236
-
237
- def main ():
238
- """Parse arguments and perform file checking"""
239
-
240
- # Get source and target filenames
241
- parser = argparse .ArgumentParser (
242
- description = "Convert a Python script to Jupyter notebook and vice versa" ,
243
- usage = "p2j myfile.py" )
244
- parser .add_argument ('source_filename' ,
245
- help = 'Python script to parse' )
246
- parser .add_argument ('-r' , '--reverse' ,
247
- action = 'store_true' ,
248
- help = "To convert Jupyter to Python scripto" )
249
- parser .add_argument ('-t' , '--target_filename' ,
250
- help = "Target filename of Jupyter notebook. If not specified, " +
251
- "it will use the filename of the Python script and append .ipynb" )
252
- parser .add_argument ('-o' , '--overwrite' ,
253
- action = 'store_true' ,
254
- help = 'Flag whether to overwrite existing target file. Defaults to false' )
255
- args = parser .parse_args ()
256
-
257
- if args .reverse :
258
- j2p (source_filename = args .source_filename ,
259
- target_filename = args .target_filename ,
260
- overwrite = args .overwrite )
261
- else :
262
- p2j (source_filename = args .source_filename ,
263
- target_filename = args .target_filename ,
264
- overwrite = args .overwrite )
265
-
266
-
267
- if __name__ == "__main__" :
268
- main ()
0 commit comments