Skip to content

Commit

Permalink
fixed some linting errors detected by pylint
Browse files Browse the repository at this point in the history
  • Loading branch information
g-raffy committed Nov 8, 2023
1 parent 2f94262 commit fea4922
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 33 deletions.
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
"python.defaultInterpreterPath": "pymusco.venv/bin/python",
"pylint.args": [
"--disable=C0301",
"--disable=C0114",
"--disable=C0115",
"--disable=C0116",
"--generated-members=cv2.*"
],
"flake8.args": [
"--per-file-ignores=\"__init__.py:F401\""
]
}
12 changes: 5 additions & 7 deletions src/pymusco/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def dict_raise_on_duplicates(ordered_pairs):

def load_commented_json(commented_json_file_path):
uncommented_json_contents = ''
with open(commented_json_file_path, 'rt') as file:
with open(commented_json_file_path, 'rt', encoding='utf-8') as file:

for line in file.readlines():
uncommented_line = re.sub('//.*$', '', line)
Expand Down Expand Up @@ -229,11 +229,9 @@ def load_orchestra(orchestra_file_path):
return dict_to_orchestra(load_commented_json(orchestra_file_path))


"""
class Clef(Enum):
TREBLE = 1
BASS = 2
"""
# class Clef(Enum):
# TREBLE = 1
# BASS = 2


class Track(object):
Expand Down Expand Up @@ -525,7 +523,7 @@ def find_page_number(page_contents_id: int, pdf_reader: PyPDF2.PdfReader):
# print('looking for page with id %d' % page_contents_id)
for page_index in range(len(pdf_reader.pages)):
page_object = pdf_reader.pages[page_index]
assert isinstance(page_object, PyPDF2._page.PageObject)
assert isinstance(page_object, PyPDF2._page.PageObject) # pylint: disable=protected-access
# at this point, a page_object of the table of contents (with 23 links) looks like :
# {'/Contents': IndirectObject(196, 0), '/Parent': IndirectObject(203, 0), '/Type': '/Page', '/Resources': IndirectObject(195, 0), '/MediaBox': [0, 0, 612, 792], '/Annots': [IndirectObject(171, 0), IndirectObject(172, 0), IndirectObject(173, 0), IndirectObject(174, 0), IndirectObject(175, 0), IndirectObject(176, 0), IndirectObject(177, 0), IndirectObject(178, 0), IndirectObject(179, 0), IndirectObject(180, 0), IndirectObject(181, 0), IndirectObject(182, 0), IndirectObject(183, 0), IndirectObject(184, 0), IndirectObject(185, 0), IndirectObject(186, 0), IndirectObject(187, 0), IndirectObject(188, 0), IndirectObject(189, 0), IndirectObject(190, 0), IndirectObject(191, 0), IndirectObject(192, 0), IndirectObject(193, 0)]}
# while a normal page_object looks like
Expand Down
30 changes: 15 additions & 15 deletions src/pymusco/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def is_locked(filepath):
print("Trying to open %s." % filepath)
buffer_size = 8
# Opening file in append mode and read the first 8 characters.
file_object = open(filepath, 'a', buffer_size)
file_object = open(filepath, 'a', buffer_size) # pylint: disable=unspecified-encoding
if file_object:
print("%s is not locked." % filepath)
locked = False
Expand Down Expand Up @@ -123,7 +123,7 @@ def get_image_file_paths(self):


class StubContents(PdfContents):
def __init__(self, image_file_paths, toc, title, stamp_descs=[], page_info_line_y_pos=2.7):
def __init__(self, image_file_paths, toc, title, stamp_descs=None, page_info_line_y_pos=2.7):
"""
creates a pdf file from a set of pages (either)
Expand All @@ -135,7 +135,7 @@ def __init__(self, image_file_paths, toc, title, stamp_descs=[], page_info_line_
self.image_file_paths = image_file_paths
self.toc = toc
self._title = title
self._stamp_descs = stamp_descs
self._stamp_descs = stamp_descs if stamp_descs is not None else []
self.page_footers = {}
self.page_to_section = {}
self.page_info_line_y_pos = page_info_line_y_pos
Expand Down Expand Up @@ -192,7 +192,7 @@ def images_to_pdf(pdf_contents, dst_pdf_file_path):
tmp_dir.mkdir(parents=True, exist_ok=True)

latex_file_path = tmp_dir / 'stub.tex'
with open(latex_file_path, 'w') as latex_file:
with open(latex_file_path, 'w', encoding='utf-8') as latex_file:
page_to_footers = pdf_contents.get_page_footers()
page_to_section = pdf_contents.get_sections()
has_toc = len(page_to_section) > 0
Expand Down Expand Up @@ -307,7 +307,7 @@ def images_to_pdf(pdf_contents, dst_pdf_file_path):
check_pdf(dst_pdf_file_path)


def scan_to_stub(src_scanned_pdf_file_path, dst_stub_pdf_file_path, toc, title, orchestra, stamp_descs=[], page_info_line_y_pos=1.0):
def scan_to_stub(src_scanned_pdf_file_path, dst_stub_pdf_file_path, toc, title, orchestra, stamp_descs=None, page_info_line_y_pos=1.0):
"""
creates musical score stub from a musical score raw scan :
- adds a table of contents
Expand All @@ -330,7 +330,7 @@ def scan_to_stub(src_scanned_pdf_file_path, dst_stub_pdf_file_path, toc, title,
try:
track = Track(track_id, orchestra) # noqa:F841 @UnusedVariable pylint: disable=unused-variable
except KeyError as e: # noqa:F841 pylint: disable=unused-variable
raise Exception("Failed to identify track id '%s'. Either its syntax is incorrect or the related instrument in not yet registered in the orchestra." % (track_id))
raise KeyError("Failed to identify track id '%s'. Either its syntax is incorrect or the related instrument in not yet registered in the orchestra." % (track_id)) from e

# tmp_dir = tempfile.mkdtemp()
tmp_dir = Path('/tmp/pymusco')
Expand All @@ -345,11 +345,11 @@ def scan_to_stub(src_scanned_pdf_file_path, dst_stub_pdf_file_path, toc, title,
print('page_index = %d' % page_index)
page = pdf_reader.pages[page_index]
# image_file_path = extract_pdf_page_main_image(page, image_dir=tmp_dir, image_name=('page%03d' % page_index))
image_file_path = extract_pdf_page(page, image_dir=tmp_dir, image_name=('page%03d' % page_index))
image_file_path = extract_pdf_page(page, image_dir=tmp_dir, image_name='page%03d' % page_index)

scanned_image_file_paths.append(image_file_path)
# break

stamp_descs = stamp_descs if stamp_descs is not None else []
images_to_pdf(StubContents(image_file_paths=scanned_image_file_paths, toc=toc, title=title, stamp_descs=stamp_descs, page_info_line_y_pos=page_info_line_y_pos), dst_stub_pdf_file_path)


Expand All @@ -369,7 +369,7 @@ def stub_to_print(src_stub_file_path, dst_print_file_path, track_selector, orche
print(track_to_print_count)
dst_print_file_path.parent.mkdir(parents=True, exist_ok=True)

with open(dst_print_file_path, 'wb') as print_file, open(dst_print_file_path.with_suffix('.log'), 'wt') as log_file:
with open(dst_print_file_path, 'wb') as print_file, open(dst_print_file_path.with_suffix('.log'), 'wt', encoding='utf-8') as log_file:
print_pdf = PyPDF2.PdfWriter()
log_file.write("contents of print file %s :\n\n" % dst_print_file_path)
with open(src_stub_file_path, 'rb') as stub_file:
Expand Down Expand Up @@ -435,7 +435,7 @@ def stub_to_print(src_stub_file_path, dst_print_file_path, track_selector, orche
print_pdf.write(print_file)


def split_double_pages(src_scanned_pdf_file_path, dst_scanned_pdf_file_path, split_pos=[0.5]):
def split_double_pages(src_scanned_pdf_file_path, dst_scanned_pdf_file_path, split_pos=[0.5]): # pylint: disable=dangerous-default-value
"""
:param list(float) split_pos: where to split the pages (ratio of the width of the double page). If this list contains more than one element, the positions are used sequencially and in a cyclic way
"""
Expand Down Expand Up @@ -520,14 +520,14 @@ def pdf_is_readable_by_pypdf2(src_pdf_path):
with open(src_pdf_path, 'rb') as src_pdf_file:
try:
src_pdf = PyPDF2.PdfReader(src_pdf_file)
num_pages = len(src_pdf.pages) # noqa:F841
num_pages = len(src_pdf.pages) # noqa:F841 pylint: disable=unused-variable
return True
except NotImplementedError as error:
if error.message == "only algorithm code 1 and 2 are supported":
if str(error) == "only algorithm code 1 and 2 are supported":
return False
else:
raise error
except PyPDF2.utils.PdfReadError as error: # noqa:F841
except PyPDF2.errors.PdfReadError as error: # noqa:F841 pylint: disable=unused-variable
return False


Expand Down Expand Up @@ -555,7 +555,7 @@ def merge_pdf(dst_pdf_path, src_pdf_paths):


def pdftk_is_available():
completed_process = subprocess.run(['pdftk'], stdout=subprocess.PIPE)
completed_process = subprocess.run(['pdftk'], stdout=subprocess.PIPE, check=False)
return completed_process.returncode == 0


Expand All @@ -581,6 +581,6 @@ def remove_unneeded_pdf_password(src_pdf_path, dst_pdf_path):
assert pdftk_is_available(), 'the pdftk command is missing. Please install it as it is required.'

command = ['pdftk', src_pdf_path, 'input_pw', '', 'output', dst_pdf_path]
completed_process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
completed_process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
assert completed_process.returncode == 0, "command failed : %s" % command
# pdftk ./215-avengers-age-of-ultron/avengers-the-age-of-ultron-main-theme---piccolo.pdf input_pw '' output ~/toto/unsecured.pdf
8 changes: 4 additions & 4 deletions src/pymusco/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def extract_pdf_stream_image(pdf_stream, image_dir, image_name):
CCITT_group = 4
else:
CCITT_group = 3
data = pdf_stream._data # sorry, getData() does not work for CCITTFaxDecode
data = pdf_stream._data # sorry, getData() does not work for CCITTFaxDecode pylint: disable=protected-access
img_size = len(data)
tiff_header = tiff_header_for_CCITT(width, height, img_size, CCITT_group)
saved_image_file_path = (image_dir / image_name).with_suffix('.tiff')
Expand Down Expand Up @@ -392,14 +392,14 @@ def check_pdf(src_pdf_file_path):
CCITT_group = 4
else:
CCITT_group = 3
data = pdf_stream._data # sorry, getData() does not work for CCITTFaxDecode
data = pdf_stream._data # sorry, getData() does not work for CCITTFaxDecode pylint: disable=protected-access
img_size = len(data)
tiff_header = tiff_header_for_CCITT(width, height, img_size, CCITT_group) # @UnusedVariable
tiff_header = tiff_header_for_CCITT(width, height, img_size, CCITT_group) # pylint: disable=unused-variable
else:
try:
data = pdf_stream.getData()
# on corrupt file, gives : raise utils.PdfReadError("Unable to find 'endstream' marker after stream at byte %s." % utils.hexStr(stream.tell()))
except NotImplementedError as e:
except NotImplementedError as e: # pylint: disable=unused-variable
continue
except AssertionError as e:
_, _, tb = sys.exc_info()
Expand Down
12 changes: 6 additions & 6 deletions src/pymusco/piece.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def dict_to_stamp_desc(stamp_desc_as_dict, piece_desc_file_path):
else:
abs_stamp_file_path = piece_desc_file_path.parent.resolve() / stamp_file_path
if not abs_stamp_file_path.exists():
raise Exception("The stamp file '%s' is missing (file not found)." % (abs_stamp_file_path))
raise FileNotFoundError("The stamp file '%s' is missing (file not found)." % (abs_stamp_file_path))
if abs_stamp_file_path.suffix not in allowed_image_suffixes:
raise Exception("Unsupported image format for stamp '%s' (allowed formats : %s) " % (abs_stamp_file_path, str(allowed_image_suffixes)))
raise TypeError("Unsupported image format for stamp '%s' (allowed formats : %s) " % (abs_stamp_file_path, str(allowed_image_suffixes)))
return StampDesc(file_path=abs_stamp_file_path,
scale=stamp_desc_as_dict['scale'],
tx=stamp_desc_as_dict['tx'],
Expand Down Expand Up @@ -132,7 +132,7 @@ def save_piece_description(piece, piece_desc_file_path):
the path to the file describing the scanned pdf sheet music
"""
piece_as_dict = piece_to_dict(piece)
with open(piece_desc_file_path, 'w') as file:
with open(piece_desc_file_path, 'w', encoding='utf-8') as file:
json.dump(piece_as_dict, file)


Expand All @@ -147,7 +147,7 @@ def __init__(self, x, y):

class Piece(object):

def __init__(self, uid, title, orchestra, scan_toc, missing_tracks={}, stamp_descs=[], page_info_line_y_pos=1.0):
def __init__(self, uid, title, orchestra, scan_toc, missing_tracks=None, stamp_descs=None, page_info_line_y_pos=1.0):
"""
Parameters
----------
Expand All @@ -164,8 +164,8 @@ def __init__(self, uid, title, orchestra, scan_toc, missing_tracks={}, stamp_des
self.title = title # match.group('title')
self.orchestra = orchestra
self.scan_toc = scan_toc
self.missing_tracks = missing_tracks
self.stamp_descs = stamp_descs
self.missing_tracks = missing_tracks if missing_tracks is not None else {}
self.stamp_descs = stamp_descs if stamp_descs is not None else []
self.page_info_line_y_pos = page_info_line_y_pos
# self.stamp_scale = 0.5
# self.stamp_pos = Vector2(14.0, 4.0)
Expand Down
1 change: 0 additions & 1 deletion test.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,3 @@ def test(src_pdf_file_path, dst_pdf_file_path):
stub_toc.shift_page_indices(NUM_TOC_PAGES)

pymusco.stub_to_print(os.getcwd() + '/results/stubs/666-japanese-tango.pdf', os.getcwd() + '/results/prints/666-japanese-tango.pdf', track_selector, orchestra, stub_toc=stub_toc)

0 comments on commit fea4922

Please sign in to comment.