Skip to content

Commit 3afd895

Browse files
GH-31: Analyse the code quality using codacy (GH-32)
* Fix the names to correspond to the functionality * Clean-up - use attribute delegate * Make the FileFormatter abstract base class * Fix the critical code quality issues
1 parent a55d5c8 commit 3afd895

File tree

3 files changed

+39
-33
lines changed

3 files changed

+39
-33
lines changed

thumbnails/__init__.py

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
from PIL import Image
88

9+
from .formatter import FileFormatter
910
from .formatter import FormatterFactory
10-
from .formatter import ThumbnailFormat
1111
from .thumbnails import Thumbnails
1212
from .thumbnails import arange
1313

@@ -17,34 +17,33 @@
1717
DEFAULT_BASEPATH = ""
1818

1919

20-
def register_format(typename):
21-
"""Register a new thumbnail format to the factory."""
20+
def register_formatter(typename):
21+
"""Register a new thumbnail formatter to the factory."""
2222

23-
def _registrator(cls):
24-
if not issubclass(cls, ThumbnailFormat):
25-
raise ValueError("Thumbnail format must implement"
26-
"the ThumbnailFormat interface.")
23+
def _register_factory(cls):
24+
if not issubclass(cls, FileFormatter):
25+
raise ValueError("The formatter must implement the FileFormatter interface.")
2726

2827
cls.extension = typename
2928
FormatterFactory.thumbnails[typename] = cls
3029
return cls
3130

32-
return _registrator
31+
return _register_factory
3332

3433

35-
@register_format("vtt")
36-
class VTT(ThumbnailFormat):
34+
@register_formatter("vtt")
35+
class VTTFormatter(FileFormatter):
3736
"""Implements the methods for generating thumbnails in the WebVTT format."""
3837

3938
def __init__(self, video):
4039
super().__init__(video)
4140
self._master_name = self.filename + ".png"
4241

4342
def prepare_thumbnails(self):
44-
_thumbnails = self.video.thumbnails(True)
43+
_thumbnails = self.thumbnails(True)
4544
master = Image.new(mode="RGBA", size=next(_thumbnails))
4645

47-
for frame, start, end, x, y in self.video.thumbnails():
46+
for frame, start, end, x, y in self.thumbnails():
4847
with Image.open(frame) as image:
4948
image = image.resize((self.width, self.height), Image.ANTIALIAS)
5049
master.paste(image, (x, y))
@@ -60,19 +59,19 @@ def _format_time(secs):
6059
_lines = ["WEBVTT\n\n"]
6160
_img_src = self.basepath + self._master_name
6261

63-
for frame, start, end, x, y in self.video.thumbnails():
62+
for frame, start, end, x, y in self.thumbnails():
6463
_thumbnail = "%s --> %s\n%s#xywh=%d,%d,%d,%d\n\n" % (
6564
_format_time(start), _format_time(end),
6665
_img_src, x, y, self.width, self.height
6766
)
6867
_lines.append(_thumbnail)
6968

70-
with open(self.output_format, "w") as fp:
69+
with open(self.thumbnail_file, "w") as fp:
7170
fp.writelines(_lines)
7271

7372

74-
@register_format("json")
75-
class JSON(ThumbnailFormat):
73+
@register_formatter("json")
74+
class JSONFormatter(FileFormatter):
7675
"""Implements the methods for generating thumbnails in the JSON format."""
7776

7877
def __init__(self, video):
@@ -88,7 +87,7 @@ def prepare_thumbnails(self):
8887
def generate(self):
8988
_content = {}
9089

91-
for frame, start, end, x, y in self.video.thumbnails():
90+
for frame, start, end, x, y in self.thumbnails():
9291
frame = self._outdir + os.sep + os.path.split(frame)[1]
9392
with Image.open(frame) as image:
9493
image.resize((self.width, self.height), Image.ANTIALIAS).save(frame)
@@ -98,16 +97,16 @@ def generate(self):
9897
}
9998
_content[int(start)] = _thumbnail
10099

101-
with open(self.output_format, "w") as fp:
100+
with open(self.thumbnail_file, "w") as fp:
102101
json.dump(_content, fp, indent=2)
103102

104103

105104
__version__ = "v1.0"
106105
__all__ = (
107-
FormatterFactory,
108-
register_format,
109-
ThumbnailFormat,
110-
Thumbnails,
111-
JSON,
112-
VTT,
106+
"register_formatter",
107+
"FormatterFactory",
108+
"FileFormatter",
109+
"JSONFormatter",
110+
"VTTFormatter",
111+
"Thumbnails",
113112
)

thumbnails/__main__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,12 @@ def format_usage(self, ctx, formatter):
3333
formatter.write_usage(ctx.command_path, "\n\t\t\t".join(usages), prefix="Usages: ")
3434

3535

36+
# This defines a set of supported values for the particular option of the CLI.
37+
_type = click.Choice(FormatterFactory.thumbnails.keys(), case_sensitive=False)
38+
39+
3640
@click.command(cls=_ThumbnailsCLI)
37-
@click.option("--as", "-F", default=DEFAULT_AS, help="Output format. Default is %s." % DEFAULT_AS,
38-
type=click.Choice(FormatterFactory.thumbnails.keys(), case_sensitive=False))
41+
@click.option("--as", "-F", default=DEFAULT_AS, type=_type, help="Output format. Default is %s." % DEFAULT_AS)
3942
@click.option("--compress", "-C", default=DEFAULT_COMPRESS, help="The image scale coefficient. A number from 0 to 1.")
4043
@click.option("--interval", "-I", default=DEFAULT_INTERVAL, help="The interval between neighbor thumbnails in seconds.")
4144
@click.option("--basepath", "-B", default=DEFAULT_BASEPATH, help="The prefix of the thumbnails path can be customized.")

thumbnails/formatter.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
class ThumbnailFormat:
2-
"""The interface of the thumbnails' final output format generator."""
1+
from abc import ABCMeta, abstractmethod
2+
3+
4+
class FileFormatter(metaclass=ABCMeta):
5+
"""Any thumbnail describing format should implement the base Formatter."""
36

47
extension = None
58

@@ -11,16 +14,17 @@ def __getattr__(self, item):
1114
return getattr(self.video, item)
1215

1316
@property
14-
def output_format(self):
17+
def thumbnail_file(self):
18+
"""Return the name of the thumbnail file."""
1519
return "%s.%s" % (self.filename, self.extension)
1620

21+
@abstractmethod
1722
def prepare_thumbnails(self):
1823
"""Prepare the thumbnails before generating the output."""
19-
raise NotImplementedError
2024

25+
@abstractmethod
2126
def generate(self):
2227
"""Generate the thumbnails for the given video."""
23-
raise NotImplementedError
2428

2529

2630
class FormatterFactory:
@@ -29,9 +33,9 @@ class FormatterFactory:
2933
thumbnails = {}
3034

3135
@classmethod
32-
def create_formatter(cls, typename, *args, **kwargs) -> ThumbnailFormat:
36+
def create_formatter(cls, typename, *args, **kwargs) -> FileFormatter:
3337
"""Create a new thumbnail formatter by the given typename."""
3438
try:
3539
return cls.thumbnails[typename](*args, **kwargs)
3640
except KeyError:
37-
raise ValueError("Thumbnail format '%s' is not supported." % typename)
41+
raise ValueError("The formatter type '%s' is not registered." % typename)

0 commit comments

Comments
 (0)