-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor #1
Open
szabadkai
wants to merge
22
commits into
balabit:master
Choose a base branch
from
szabadkai:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
refactor #1
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
4ad60c9
First Tests and Classes
szabadkai 3395275
First Tests and Classes
szabadkai 8105b03
First Tests and Classes
szabadkai fe3901c
test for write header
szabadkai c7dc7d5
Notebook class introduced
szabadkai 78741e3
Formater class implementeed
szabadkai b12c69a
Formater class implementeed
szabadkai d03b46a
py import
szabadkai b74cf07
tests revised
szabadkai 23512c2
tests extended
szabadkai 2b89edd
fit to the old ui
szabadkai f329fb3
testfiles regenerated with the original py-s
szabadkai 04d4f19
.ide removed
szabadkai 28871e0
files rearranged
szabadkai 50746b2
files rearranged
szabadkai 2da8faa
files rearranged
szabadkai 90ea9ee
files rearranged
szabadkai a3e2bd2
.idea rm
szabadkai 4a7676d
read patch
szabadkai 511b4c8
Notebook format patch
szabadkai eb5c17b
reed_py extracted to a separate class
szabadkai efc6019
ReadPy class extracted
szabadkai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
.idea | ||
*.pyc |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import abc | ||
import json | ||
import os | ||
|
||
|
||
class Formater(): | ||
__metaclass__ = abc.ABCMeta | ||
|
||
@abc.abstractmethod | ||
def output(self, notebook, out_path): | ||
"""Outputs the notebook data in the desired form""" | ||
return | ||
|
||
@staticmethod | ||
@abc.abstractmethod | ||
def construct_output_path(input_path): | ||
return | ||
|
||
|
||
class ToNotebook(Formater): | ||
dry_run = None | ||
overwrite = None | ||
|
||
def __init__(self, overwrite=False, dry_run=False): | ||
self.overwrite = overwrite | ||
self.dry_run = dry_run | ||
|
||
def output(self, notebook, out_path): | ||
output = notebook.to_dict() | ||
self.write_py_data_to_notebook(output, out_path) | ||
|
||
@staticmethod | ||
def construct_output_path(input_path): | ||
input_headless, ext = os.path.splitext(input_path) | ||
return input_headless + ".ipynb" | ||
|
||
@staticmethod | ||
def write_py_data_to_notebook(output, out_file_path): | ||
with open(out_file_path, 'w') as outfile: | ||
json.dump(output, outfile) | ||
|
||
|
||
class ToPy(Formater): | ||
def __init__(self, overwrite=False, dry_run=False,): | ||
self.overwrite = overwrite | ||
self.dry_run = dry_run | ||
|
||
def output(self, notebook, out_path): | ||
with open(out_path, 'w') as output: | ||
self.add_header(output, str(notebook.notebook_format)) | ||
for cell in notebook.cells: | ||
output.write(cell.generate_field_output()) | ||
|
||
@staticmethod | ||
def construct_output_path(input_path): | ||
input_headless, ext = os.path.splitext(input_path) | ||
return input_headless + ".py" | ||
|
||
@staticmethod | ||
def add_header(output, notebook_format): | ||
assert isinstance(output, file) | ||
assert isinstance(notebook_format, str) | ||
output.write('# -*- coding: utf-8 -*-\n') | ||
output.write('# <nbformat>' + notebook_format + '</nbformat>\n') |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import json | ||
import os | ||
from ReadPy import ReadPy | ||
|
||
|
||
class Notebook(object): | ||
notebook_format = None | ||
cells = [] | ||
metadata = None | ||
nbformat_minor = None | ||
|
||
def read(self, path_to_file): | ||
input_headless, ext = os.path.splitext(path_to_file) | ||
if ext == ".ipynb": | ||
self.read_notebook(path_to_file) | ||
elif ext == ".py": | ||
self.read_py(path_to_file) | ||
|
||
def read_notebook(self, path_to_file): | ||
with open(path_to_file, 'r') as notebook: | ||
notebook_data = json.load(notebook) | ||
self.notebook_format = notebook_data["nbformat"] | ||
assert "cells" in notebook_data.keys(), "Nbformat is " + str(notebook_data['nbformat']) \ | ||
+ ", try the old converter script." | ||
for cell in notebook_data["cells"]: | ||
self.cells.append(Cell(cell)) | ||
|
||
@staticmethod | ||
def read_py(path_to_file): | ||
reader = ReadPy() | ||
reader.read(path_to_file) | ||
|
||
def to_dict(self): | ||
cells = {'metadata': self.metadata, | ||
'nbformat': self.notebook_format, | ||
'nbformat_minor': self.nbformat_minor, | ||
'cells': []} | ||
for cell in self.cells: | ||
cells['cells'].append(cell.to_dict()) | ||
return cells | ||
|
||
|
||
class Cell(object): | ||
def __init__(self, cell): | ||
self.type = cell['cell_type'] | ||
self.source = cell["source"] | ||
|
||
def generate_field_output(self): | ||
output = '\n# <' + self.type + 'cell' + '>\n\n' | ||
for item in self.source: | ||
if self.type == "code": | ||
output += item | ||
else: | ||
output += "# " + item | ||
return output + "\n" | ||
|
||
def to_dict(self): | ||
return {'cell_type': self.type, 'source': self.source} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import os | ||
import fnmatch | ||
from Notebook import Notebook | ||
|
||
|
||
class NotebookConverter(object): | ||
def convert_all(self, directory, formater): | ||
for root, dirnames, filenames in os.walk(directory): | ||
for filename in fnmatch.filter(filenames, '*.ipynb'): | ||
filename = os.path.abspath(os.path.join(root, filename)) | ||
self.convert(filename, formater) | ||
|
||
@staticmethod | ||
def convert(input_file_path, formater): | ||
output_file_path = formater.construct_output_path(input_file_path) | ||
if not os.path.exists(output_file_path) or formater.overwrite: | ||
nb = Notebook() | ||
nb.read(input_file_path) | ||
if not formater.dry_run: | ||
formater.output(nb, output_file_path) | ||
print "Created file: {}".format(output_file_path) | ||
|
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
from app.Notebook import Cell | ||
|
||
|
||
class ReadPy(object): | ||
current_cell = None | ||
execution_count = 1 | ||
_outputcells = [] | ||
|
||
def read(self, path_to_file): | ||
skip_one_line = False | ||
with open(path_to_file, 'r') as lines: | ||
self.add_descriptive_data(lines.readlines()) | ||
lines.seek(0) | ||
for line in lines: | ||
if skip_one_line: | ||
skip_one_line = False | ||
elif self.is_first_line_of_cell(line): | ||
self.close_cell() | ||
if self.current_cell == 'code': | ||
self.execution_count += 1 | ||
self.open_cell(line, self.execution_count) | ||
skip_one_line = True | ||
elif self.current_cell.type in ('markdown', 'code'): | ||
self.append_line_to_source(line) | ||
self.close_last_cell() | ||
return self._outputcells | ||
|
||
def close_cell(self): | ||
if self.current_cell.type in ('markdown', 'code'): | ||
if len(self.current_cell.source) > 1: | ||
del self.current_cell.source[-1:] | ||
self.current_cell.source[-1] = self.current_cell.source[-1].rstrip('\n') | ||
self._outputcells.append(self.current_cell) | ||
|
||
def close_last_cell(self): | ||
if self.current_cell.type in ['markdown', 'code']: | ||
self.current_cell.source[-1] = self.current_cell.source[-1].rstrip('\n') | ||
self._outputcells.append(self.current_cell) | ||
|
||
def open_cell(self, line, execution_count): | ||
if '<markdowncell>' in line: | ||
self.current_cell = Cell({'cell_type': 'markdown', 'metadata': {}, 'source':[]}) | ||
else: | ||
self.current_cell = Cell({'cell_type': 'code', | ||
'execution_count': execution_count, | ||
'metadata': {'collapsed': False}, | ||
'outputs': []}) | ||
|
||
def append_line_to_source(self, row): | ||
if self.current_cell.type == 'markdown': | ||
self.current_cell.source.append(row.lstrip("# ")) | ||
elif self.current_cell.type == 'code': | ||
self.current_cell.source.append(row) | ||
|
||
@staticmethod | ||
def is_first_line_of_cell(line): | ||
if line == '# <markdowncell>\n' or line == '# <codecell>\n': | ||
return True | ||
return False | ||
|
||
def add_descriptive_data(self, lines): | ||
self.metadata = self.create_metadata() | ||
self.notebook_format = self.read_nb_format_from_py(lines) | ||
self.nbformat_minor = 0 | ||
|
||
@staticmethod | ||
def create_metadata(): | ||
kernelspec = {'display_name': 'Python 2', | ||
'language': 'python', | ||
'name': 'python2'} | ||
language_info = {'codemirror_mode': {'name': 'ipython', 'version': 2}, | ||
'file_extension': '.py', | ||
'mimetype': 'text/x-python', | ||
'name': 'python', | ||
'nbconvert_exporter': 'python', | ||
'pygments_lexer': 'ipython2', | ||
'version': '2.7.10'} | ||
metadata = {'kernelspec': kernelspec, | ||
'language_info': language_info} | ||
return metadata | ||
|
||
@staticmethod | ||
def read_nb_format_from_py(lines): | ||
if '<nbformat>' in lines[1]: | ||
nbformat = lines[1].split('>')[1].split('<')[0] | ||
if "." in nbformat: | ||
nbformat = float(nbformat) | ||
else: | ||
nbformat = int(nbformat) | ||
return nbformat | ||
else: | ||
raise IOError("No or not suitable ( line[1]: "+lines[1]+") nbformat in supported lines") |
Empty file.
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
""" | ||
This script converts a .py file to Ipython v4 notebook format. The .py file | ||
must be a result of an Ipython -> .py conversion using the notebook_v4_to_py.py | ||
script or the automatic post-hook save in Ipyhon 3 based on that script. | ||
In this way the version controlled .py files can be converted back to Ipython | ||
notebook format. | ||
|
||
Call this script with argument "-f" to create an .ipynb file from a .py file: | ||
|
||
python py_to_notebook_v4.py -f filename.py | ||
|
||
Call the script with argument "--overwrite" to overwrite existing .ipynb files. | ||
|
||
Call the script with argument "--dry-run" to simulate (print) what would happen. | ||
|
||
Date: 07. August 2015. | ||
############################################################################# | ||
|
||
This script is released under the MIT License | ||
|
||
Copyright (c) 2015 Balabit SA | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of | ||
this software and associated documentation files (the "Software"), to deal in | ||
the Software without restriction, including without limitation the rights to use, | ||
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the | ||
Software, and to permit persons to whom the Software is furnished to do so, | ||
subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, | ||
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | ||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | ||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN | ||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | ||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
""" | ||
from app.NotebookConverter import NotebookConverter | ||
from app.Formatter import ToNotebook | ||
|
||
if __name__ == '__main__': | ||
import argparse | ||
|
||
parser = argparse.ArgumentParser(description=__doc__) | ||
parser.add_argument('-w', '--overwrite', action='store_true', help='Overwrite existing py files', default=False) | ||
parser.add_argument('-f', '--file', help='Specify an Ipython notebook if you only want to convert one. ' | ||
'(This will overwrite default.)') | ||
parser.add_argument('--dry-run', action='store_true', help='Only prints what would happen', default=False) | ||
args = parser.parse_args() | ||
py2nb = NotebookConverter() | ||
fm = ToNotebook() | ||
|
||
if args.file is not None: | ||
py2nb.convert(args.file, ToNotebook(overwrite=args.overwrite, dry_run=args.dry_run)) | ||
else: | ||
py2nb.convert_all('.', ToNotebook(overwrite=args.overwrite, dry_run=args.dry_run)) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The read related functions should probably be extracted to helper classes. The Notebook class would become only the representation.