Skip to content
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

Resolving linter errors flake8 #9

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions pysubtools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@
from __future__ import print_function
from __future__ import unicode_literals

from zipfile import ZipExtFile

from . import parsers
from . import exporters
from .subtitle import Subtitle, SubtitleUnit, SubtitleLine

__all__ = [
'Subtitle',
'SubtitleUnit',
'SubtitleLine',
'parsers',
'exporters',
'Subtitle',
'SubtitleUnit',
'SubtitleLine',
'parsers',
'exporters',
]
163 changes: 87 additions & 76 deletions pysubtools/exporters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,82 +7,93 @@

from ..subtitle import Subtitle

class NoExporterFound(Exception):
pass

class Exporter(object):
"""Base class for exporting Subtitle."""

@staticmethod
def from_format(format, **options):
"""Returns an exporter for specified 'format'."""
for exporter in Exporter.__subclasses__():
if exporter.FORMAT == format:
return exporter(**options)
raise NoExporterFound("Could not find exporter with name '{}'.".format(format))

def __init__(self, **options):
self._init(**options)

def _init(self, **options):
"""A conveniance init method (no need for overloading)."""
class NoExporterFound(Exception):
pass

def _export_metadata(self, metadata):
"""
Returns subtitles metadata in format. In your implementation,
make sure you output str object. Parameter 'metadata' is in
dict object.
"""
raise NotImplementedError

def _export_unit(self, unit):
"""
Returns whole subtitle unit in format. In your implementation,
make sure you output str object.
"""
raise NotImplementedError

def _export_end(self, metadata):
"""Returns the end part of subtitle."""
raise NotImplementedError

@property
def format(self):
return self.FORMAT

def export(self, output, subtitle):
"""Exports to 'output', it may be filename or a file object."""
if not isinstance(subtitle, Subtitle):
raise TypeError("Can export only Subtitle objects.")

try:
basestring
except NameError:
# Python3 compat
basestring = str

if isinstance(output, basestring):
output = io.BufferedWriter(io.open(output, 'wb'))

try:
if isinstance(output, file):
output = io.BufferedWriter(io.FileIO(output.fileno(), closefd = False, mode = output.mode))
except NameError:
# Python3 does not need this
pass

if not isinstance(output, io.BufferedIOBase):
raise TypeError("Output needs to be a filename, file or BufferedIOBase with write capability.")

# Export subtitle metadata
output.write(self._export_metadata(subtitle.meta))

# Go through units and export one by one
for unit in subtitle:
output.write(self._export_unit(unit))

# The final piece
output.write(self._export_end(subtitle.meta))

# Done

class Exporter(object):
"""Base class for exporting Subtitle."""

@staticmethod
def from_format(format, **options):
"""Returns an exporter for specified 'format'."""
for exporter in Exporter.__subclasses__():
if exporter.FORMAT == format:
return exporter(**options)
raise NoExporterFound(
"Could not find exporter with name '{}'.".format(format)
)

def __init__(self, **options):
self._init(**options)

def _init(self, **options):
"""A conveniance init method (no need for overloading)."""
pass

def _export_metadata(self, metadata):
"""
Returns subtitles metadata in format. In your implementation,
make sure you output str object. Parameter 'metadata' is in
dict object.
"""
raise NotImplementedError

def _export_unit(self, unit):
"""
Returns whole subtitle unit in format. In your implementation,
make sure you output str object.
"""
raise NotImplementedError

def _export_end(self, metadata):
"""Returns the end part of subtitle."""
raise NotImplementedError

@property
def format(self):
return self.FORMAT

def export(self, output, subtitle):
"""Exports to 'output', it may be filename or a file object."""
if not isinstance(subtitle, Subtitle):
raise TypeError("Can export only Subtitle objects.")

try:
global basestring
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it should be better to ignore flake8 error here.

Also, there might be a better way how to identify python 2/3 incompatibility for basestring.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

except NameError:
# Python3 compat
basestring = str

if isinstance(output, basestring):
output = io.BufferedWriter(io.open(output, 'wb'))

try:
if isinstance(output, file):
output = io.BufferedWriter(
MasterMind2k marked this conversation as resolved.
Show resolved Hide resolved
io.FileIO(
output.fileno(),
closefd=False,
mode=output.mode)
)
except NameError:
# Python3 does not need this
pass

if not isinstance(output, io.BufferedIOBase):
raise TypeError(
"""Output needs to be a filename, file or BufferedIOBase with
write capability.""")

# Export subtitle metadata
output.write(self._export_metadata(subtitle.meta))

# Go through units and export one by one
for unit in subtitle:
output.write(self._export_unit(unit))

# The final piece
output.write(self._export_end(subtitle.meta))

# Done
114 changes: 59 additions & 55 deletions pysubtools/exporters/subrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,59 +7,63 @@

from ..subtitle import HumanTime


class SubRipExporter(Exporter):
"""Exported for SubRip format."""
FORMAT = 'SubRip'

def _init(self, encoding = 'utf-8', line_ending = b'\r\n'):
self._encoding = encoding
self._line_ending = line_ending

@staticmethod
def _convert_time(time):
output = []

if isinstance(time, (float, int)):
time = HumanTime.from_seconds(time)
elif not isinstance(time, HumanTime):
raise TypeError("Expecting time")

output.append('{:02d}'.format(time.hours))
output.append('{:02d}'.format(time.minutes))
seconds = int(time.seconds)
miliseconds = int((time.seconds - seconds) * 1000)
output.append('{:02d},{:03d}'.format(seconds, miliseconds))

return ':'.join(output)

def _export_metadata(self, metadata):
# No subtitle wide metadata, just reset counter
self._unit = 0
return b''

def _export_unit(self, unit):
output = []

if self._unit:
# An empty line at the beginning
output.append(b'')
self._unit += 1

# Sequence
output.append(str(self._unit).encode(self._encoding))
# Timing
# TODO 3D positions
output.append("{} --> {}".format(self._convert_time(unit.start),
self._convert_time(unit.end)).encode(self._encoding))
# Text
output.append(self._line_ending.join([i.encode(self._encoding, 'ignore') for i in unit.lines]))

# End of line
output.append(b'')

# All done
return self._line_ending.join(output)

def _export_end(self, metadata):
# No specific footer also
return b''
"""Exported for SubRip format."""
FORMAT = 'SubRip'

def _init(self, encoding='utf-8', line_ending=b'\r\n'):
self._encoding = encoding
self._line_ending = line_ending

@staticmethod
def _convert_time(time):
output = []

if isinstance(time, (float, int)):
time = HumanTime.from_seconds(time)
elif not isinstance(time, HumanTime):
raise TypeError("Expecting time")

output.append('{:02d}'.format(time.hours))
output.append('{:02d}'.format(time.minutes))
seconds = int(time.seconds)
miliseconds = int((time.seconds - seconds) * 1000)
output.append('{:02d},{:03d}'.format(seconds, miliseconds))

return ':'.join(output)

def _export_metadata(self, metadata):
# No subtitle wide metadata, just reset counter
self._unit = 0
return b''

def _export_unit(self, unit):
output = []

if self._unit:
# An empty line at the beginning
output.append(b'')
self._unit += 1

# Sequence
output.append(str(self._unit).encode(self._encoding))
# Timing
# TODO 3D positions
output.append("{} --> {}".format(
self._convert_time(unit.start),
self._convert_time(unit.end)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Last line in lists, tuples etc. should end with a comma. Helps when you add or move lines up and down (they look all the same).

).encode(self._encoding))
# Text
output.append(self._line_ending.join(
[i.encode(self._encoding, 'ignore') for i in unit.lines]))

# End of line
output.append(b'')

# All done
return self._line_ending.join(output)

def _export_end(self, metadata):
# No specific footer also
return b''
14 changes: 7 additions & 7 deletions pysubtools/parsers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
from . import encodings

# To load all parser
from . import subrip
from . import microdvd
# from . import subrip
# from . import microdvd

__all__ = [
'Parser',
'EncodingError',
'NoParserError',
'ParseError',
'encodings',
'Parser',
'EncodingError',
'NoParserError',
'ParseError',
'encodings',
]
Loading