Skip to content

Commit 9984ec1

Browse files
committed
🧹 Housekeeping
1 parent c59f723 commit 9984ec1

File tree

5 files changed

+134
-126
lines changed

5 files changed

+134
-126
lines changed

p2j/j2p.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import sys
2+
import json
3+
from p2j.utils import _check_files
4+
5+
6+
def jupyter2python(source_filename: str, target_filename: str, overwrite: bool = False):
7+
"""Convert Jupyter notebooks to Python scripts
8+
9+
Args:
10+
source_filename (str): Path to Jupyter notebook.
11+
target_filename (str): Path to name of Python script. Optional.
12+
overwrite (bool): Whether to overwrite an existing Python script.
13+
with_markdown (bool, optional): Whether to include markdown. Defaults to False.
14+
"""
15+
16+
target_filename = _check_files(
17+
source_filename, target_filename, overwrite, conversion="j2p")
18+
19+
# Check if source file exists and read
20+
try:
21+
with open(source_filename, "r", encoding="utf-8") as infile:
22+
myfile = json.load(infile)
23+
except FileNotFoundError:
24+
print("Source file not found. Specify a valid source file.")
25+
sys.exit(1)
26+
27+
final = ["".join(["# " + line.lstrip() for line in cell["source"] if not line.strip() == ""])
28+
if cell["cell_type"] == "markdown" else "".join(cell["source"])
29+
for cell in myfile["cells"]]
30+
final = "\n\n".join(final)
31+
final = final.replace("<br>", "")
32+
33+
with open(target_filename, "a", encoding="utf-8") as outfile:
34+
outfile.write(final)
35+
print("Python script {} written.".format(target_filename))

p2j/main.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import argparse
2+
from p2j.p2j import python2jupyter
3+
from p2j.j2p import jupyter2python
4+
5+
6+
def main():
7+
8+
parser = argparse.ArgumentParser(
9+
description="Convert a Python script to Jupyter notebook and vice versa",
10+
usage="p2j myfile.py")
11+
parser.add_argument("source_filename",
12+
help="Python script to parse")
13+
parser.add_argument("-r", "--reverse",
14+
action="store_true",
15+
help="To convert Jupyter to Python scripto")
16+
parser.add_argument("-t", "--target_filename",
17+
help="Target filename of Jupyter notebook. If not specified, " +
18+
"it will use the filename of the Python script and append .ipynb")
19+
parser.add_argument("-o", "--overwrite",
20+
action="store_true",
21+
help="Flag whether to overwrite existing target file.")
22+
args = parser.parse_args()
23+
24+
if args.reverse:
25+
python2jupyter(source_filename=args.source_filename,
26+
target_filename=args.target_filename,
27+
overwrite=args.overwrite)
28+
else:
29+
jupyter2python(source_filename=args.source_filename,
30+
target_filename=args.target_filename,
31+
overwrite=args.overwrite)
32+
33+
34+
if __name__ == "__main__":
35+
main()

p2j/p2j.py

+11-114
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
"""
22
This module translates .py files to .ipynb and vice versa
33
"""
4+
from typing import Optional
45
import os
56
import sys
67
import json
7-
import argparse
8+
9+
from p2j.utils import _check_files
810

911
# Path to directory
1012
HERE = os.path.abspath(os.path.dirname(__file__))
@@ -15,7 +17,7 @@
1517
TWELVE_SPACES = "{:<12}".format("")
1618

1719

18-
def p2j(source_filename, target_filename, overwrite):
20+
def python2jupyter(source_filename: str, target_filename: str, overwrite: bool = False):
1921
"""Convert Python scripts to Jupyter notebooks.
2022
2123
Args:
@@ -26,21 +28,21 @@ def p2j(source_filename, target_filename, overwrite):
2628

2729
target_filename = _check_files(
2830
source_filename, target_filename, overwrite, conversion="p2j")
29-
31+
3032
# Check if source file exists and read
3133
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]
3436
except FileNotFoundError:
3537
print("Source file not found. Specify a valid source file.")
3638
sys.exit(1)
3739

3840
# 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:
4042
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:
4244
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:
4446
MISC = json.load(file)
4547

4648
# Initialise variables
@@ -158,111 +160,6 @@ def p2j(source_filename, target_filename, overwrite):
158160
final.update(MISC)
159161

160162
# 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:
162164
json.dump(final, outfile, indent=1, ensure_ascii=False)
163165
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()

p2j/utils.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import os
2+
import sys
3+
4+
5+
def _check_files(source_file: str, target_file: str, overwrite: bool, conversion: str):
6+
"""File path checking
7+
8+
Check if
9+
1) Name of source file is valid.
10+
2) Target file already exists. If not, create.
11+
12+
Does not check if source file exists. That will be done
13+
together when opening the file.
14+
"""
15+
16+
if conversion == "p2j":
17+
expected_src_file_ext = ".py"
18+
expected_tgt_file_ext = ".ipynb"
19+
else:
20+
expected_src_file_ext = ".ipynb"
21+
expected_tgt_file_ext = ".py"
22+
23+
file_base = os.path.splitext(source_file)[0]
24+
file_ext = os.path.splitext(source_file)[-1]
25+
26+
if file_ext != expected_src_file_ext:
27+
print("Wrong file type specified. Expected {} ".format(expected_src_file_ext) +
28+
"extension but got {} instead.".format(file_ext))
29+
sys.exit(1)
30+
31+
# Check if target file is specified and exists. If not specified, create
32+
if target_file is None:
33+
target_file = file_base + expected_tgt_file_ext
34+
if not overwrite and os.path.isfile(target_file):
35+
# FileExistsError
36+
print("File {} exists. ".format(target_file) +
37+
"Add -o flag to overwrite this file, " +
38+
"or specify a different target filename using -t.")
39+
sys.exit(1)
40+
41+
return target_file

setup.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
from setuptools import setup
66

77
# Package meta-data.
8-
VERSION = "1.3.2"
8+
VERSION = "1.3.3"
99
DESCRIPTION = "p2j: Convert Python scripts to Jupyter notebook with minimal intervention"
1010

1111
# Import the README and use it as the long-description.
12-
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
12+
# Note: this will only work if README.md is present in your MANIFEST.in file!
1313
HERE = os.path.abspath(os.path.dirname(__file__))
1414
try:
15-
with io.open(os.path.join(HERE, 'README.md'), encoding='utf-8') as f:
16-
LONG_DESCRIPTION = '\n' + f.read()
15+
with io.open(os.path.join(HERE, "README.md"), encoding="utf-8") as f:
16+
LONG_DESCRIPTION = "\n" + f.read()
1717
except FileNotFoundError:
1818
LONG_DESCRIPTION = DESCRIPTION
1919

@@ -30,19 +30,19 @@
3030
python_requires=">=3.6.0",
3131
license="MIT",
3232
entry_points={
33-
'console_scripts': [
34-
'p2j=p2j.p2j:main',
33+
"console_scripts": [
34+
"p2j=p2j.main:main",
3535
],
3636
},
3737
classifiers=[
3838
# Trove classifiers
3939
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
40-
'License :: OSI Approved :: MIT License',
41-
'Programming Language :: Python',
42-
'Programming Language :: Python :: 3',
43-
'Programming Language :: Python :: 3.6'
40+
"License :: OSI Approved :: MIT License",
41+
"Programming Language :: Python",
42+
"Programming Language :: Python :: 3",
43+
"Programming Language :: Python :: 3.6"
4444
],
45-
keywords='convert python jupyter notebook script',
46-
packages=['p2j'],
45+
keywords="convert python jupyter notebook script",
46+
packages=["p2j"],
4747
include_package_data=True
4848
)

0 commit comments

Comments
 (0)