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

Sourcery refactored master branch #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

sourcery-ai[bot]
Copy link

@sourcery-ai sourcery-ai bot commented Mar 15, 2022

Branch master refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the master branch, then run:

git fetch origin sourcery/master
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai bot requested a review from matthewryanscott March 15, 2022 21:30
Copy link
Author

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Due to GitHub API limits, only the first 60 comments can be shown.

Comment on lines -70 to +78
# Coming soon: smart error handling for debugging at this point
if self.memoize:
if t == self.memoized_t:
return self.memoized_frame
else:
frame = self.make_frame(t)
self.memoized_t = t
self.memoized_frame = frame
return frame
else:
if not self.memoize:
# print(t)
return self.make_frame(t)
if t == self.memoized_t:
return self.memoized_frame
frame = self.make_frame(t)
self.memoized_t = t
self.memoized_frame = frame
return frame
Copy link
Author

Choose a reason for hiding this comment

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

Function Clip.get_frame refactored with the following changes:

This removes the following comments ( why? ):

# Coming soon: smart error handling for debugging at this point

Comment on lines +283 to -288
elif self.duration is None:
raise ValueError("Cannot change clip start when new duration is None")
else:
if self.duration is None:
raise ValueError("Cannot change clip start when new duration is None")
Copy link
Author

Choose a reason for hiding this comment

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

Function Clip.with_duration refactored with the following changes:

Comment on lines -361 to +373
if isinstance(t, np.ndarray):
# is the whole list of t outside the clip ?
tmin, tmax = t.min(), t.max()

if (self.end is not None) and (tmin >= self.end):
return False

if tmax < self.start:
return False
if not isinstance(t, np.ndarray):
return (t >= self.start) and ((self.end is None) or (t < self.end))
# is the whole list of t outside the clip ?
tmin, tmax = t.min(), t.max()

# If we arrive here, a part of t falls in the clip
result = 1 * (t >= self.start)
if self.end is not None:
result *= t <= self.end
return result
if (self.end is not None) and (tmin >= self.end):
return False

else:
if tmax < self.start:
return False

return (t >= self.start) and ((self.end is None) or (t < self.end))
# If we arrive here, a part of t falls in the clip
result = 1 * (t >= self.start)
if self.end is not None:
result *= t <= self.end
return result
Copy link
Author

Choose a reason for hiding this comment

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

Function Clip.is_playing refactored with the following changes:

Comment on lines -564 to +561
# Make sure that each frame is the same
for frame1, frame2 in zip(self.iter_frames(), other.iter_frames()):
if not np.array_equal(frame1, frame2):
return False

return True
return all(
np.array_equal(frame1, frame2)
for frame1, frame2 in zip(self.iter_frames(), other.iter_frames())
)
Copy link
Author

Choose a reason for hiding this comment

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

Function Clip.__eq__ refactored with the following changes:

This removes the following comments ( why? ):

# Make sure that each frame is the same

Comment on lines -72 to +77
if hasattr(clip, "audio"):
new_clip = clip.copy()
if clip.audio is not None:
new_clip.audio = func(clip.audio, *args, **kwargs)
return new_clip
else:
if not hasattr(clip, "audio"):
return func(clip, *args, **kwargs)
new_clip = clip.copy()
if clip.audio is not None:
new_clip.audio = func(clip.audio, *args, **kwargs)
return new_clip
Copy link
Author

Choose a reason for hiding this comment

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

Function audio_video_fx refactored with the following changes:

if self.is_mask:
new_clip = self.image_transform(
lambda pic: np.dstack(3 * [255 * pic]).astype("uint8")
)
new_clip.is_mask = False
return new_clip
else:
if not self.is_mask:
return self
new_clip = self.image_transform(
lambda pic: np.dstack(3 * [255 * pic]).astype("uint8")
)
new_clip.is_mask = False
return new_clip
Copy link
Author

Choose a reason for hiding this comment

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

Function VideoClip.to_RGB refactored with the following changes:

Comment on lines -1048 to +1047
if img.shape[2] == 4:
if fromalpha:
img = 1.0 * img[:, :, 3] / 255
elif is_mask:
img = 1.0 * img[:, :, 0] / 255
elif transparent:
self.mask = ImageClip(1.0 * img[:, :, 3] / 255, is_mask=True)
img = img[:, :, :3]
elif is_mask:
if img.shape[2] == 4 and fromalpha:
img = 1.0 * img[:, :, 3] / 255
elif img.shape[2] == 4 and is_mask or img.shape[2] != 4 and is_mask:
img = 1.0 * img[:, :, 0] / 255

elif img.shape[2] == 4 and transparent:
self.mask = ImageClip(1.0 * img[:, :, 3] / 255, is_mask=True)
img = img[:, :, :3]
Copy link
Author

Choose a reason for hiding this comment

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

Function ImageClip.__init__ refactored with the following changes:

Comment on lines -1256 to +1248
text = "@" + temptxt
text = f"@{temptxt}"
else:
# use a file instead of a text.
text = "@%" + filename
text = f"@%{filename}"
Copy link
Author

Choose a reason for hiding this comment

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

Function TextClip.__init__ refactored with the following changes:

Comment on lines -1440 to +1431
self.color_dict = color_dict if color_dict else self.DEFAULT_COLOR_DICT
self.color_dict = color_dict or self.DEFAULT_COLOR_DICT

frame_list = []
for input_frame in bitmap_frames:
output_frame = []
for row in input_frame:
output_frame.append([self.color_dict[color] for color in row])
output_frame = [
[self.color_dict[color] for color in row] for row in input_frame
]

Copy link
Author

Choose a reason for hiding this comment

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

Function BitmapClip.__init__ refactored with the following changes:

self.fps = max(fpss) if fpss else None
self.fps = max(fpss, default=None)
Copy link
Author

Choose a reason for hiding this comment

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

Function CompositeVideoClip.__init__ refactored with the following changes:

This removes the following comments ( why? ):

# compute audio

i = max([i for i, e in enumerate(timings) if e <= t])
i = max(i for i, e in enumerate(timings) if e <= t)
Copy link
Author

Choose a reason for hiding this comment

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

Function concatenate_videoclips.make_frame refactored with the following changes:

Comment on lines -20 to +21
else:
fading = 1.0 * t / duration
return fading * get_frame(t) + (1 - fading) * initial_color
fading = 1.0 * t / duration
return fading * get_frame(t) + (1 - fading) * initial_color
Copy link
Author

Choose a reason for hiding this comment

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

Function fadein.filter refactored with the following changes:

Comment on lines -23 to +24
else:
fading = 1.0 * (clip.duration - t) / duration
return fading * get_frame(t) + (1 - fading) * final_color
fading = 1.0 * (clip.duration - t) / duration
return fading * get_frame(t) + (1 - fading) * final_color
Copy link
Author

Choose a reason for hiding this comment

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

Function fadeout.filter refactored with the following changes:

Comment on lines -56 to +59
bg = np.tile(opacity, (new_h, new_w)).astype(float).reshape(shape)
return np.tile(opacity, (new_h, new_w)).astype(float).reshape(shape)
else:
shape = (new_h, new_w, 3)
bg = np.tile(color, (new_h, new_w)).reshape(shape)
return bg
return np.tile(color, (new_h, new_w)).reshape(shape)
Copy link
Author

Choose a reason for hiding this comment

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

Function margin.make_bg refactored with the following changes:

Comment on lines -137 to +149
else:
if kw_value is not None: # if not default value
warnings.warn(
f"rotate '{kw_name}' argument is not supported"
" by your Pillow version and is being ignored. Minimum"
" Pillow version required:"
f" v{'.'.join(str(n) for n in min_version)}",
UserWarning,
)
elif kw_value is not None: # if not default value
warnings.warn(
f"rotate '{kw_name}' argument is not supported"
" by your Pillow version and is being ignored. Minimum"
" Pillow version required:"
f" v{'.'.join(str(n) for n in min_version)}",
UserWarning,
)

# PIL expects uint8 type data. However a mask image has values in the
# range [0, 1] and is of float type. To handle this we scale it up by
# a factor 'a' for use with PIL and then back again by 'a' afterwards.
if im.dtype == "float64":
# this is a mask image
a = 255.0
else:
a = 1

a = 255.0 if im.dtype == "float64" else 1
Copy link
Author

Choose a reason for hiding this comment

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

Function rotate.filter refactored with the following changes:

This removes the following comments ( why? ):

# this is a mask image

Comment on lines -450 to +451
logger(message="MoviePy - Building file %s with imageio." % filename)
logger(message=f"MoviePy - Building file {filename} with imageio.")
Copy link
Author

Choose a reason for hiding this comment

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

Function write_gif_with_image_io refactored with the following changes:

filename = TEMP_PREFIX + ".png"
filename = f'{TEMP_PREFIX}.png'
Copy link
Author

Choose a reason for hiding this comment

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

Function html_embed refactored with the following changes:

print("position, color : ", "%s, %s" % (str((x, y)), str(rgb)))
print("position, color : ", f"{(x, y)}, {str(rgb)}")
Copy link
Author

Choose a reason for hiding this comment

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

Function show refactored with the following changes:

if fullscreen:
flags = pg.FULLSCREEN
else:
flags = 0

flags = pg.FULLSCREEN if fullscreen else 0
Copy link
Author

Choose a reason for hiding this comment

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

Function preview refactored with the following changes:

for i in range(int(line.split(" ")[1])):
texts.append(["\n", "\n"])
texts.extend(["\n", "\n"] for _ in range(int(line.split(" ")[1])))
Copy link
Author

Choose a reason for hiding this comment

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

Function CreditsClip.__init__ refactored with the following changes:

Comment on lines -502 to +509
if clip is not None:
end = clip.duration
else:
end = len(luminosities) * (1.0 / fps)
end = clip.duration if clip is not None else len(luminosities) * (1.0 / fps)
luminosity_diffs = abs(np.diff(luminosities))
avg = luminosity_diffs.mean()
luminosity_jumps = (
1 + np.array(np.nonzero(luminosity_diffs > luminosity_threshold * avg))[0]
)
timings = [0] + list((1.0 / fps) * luminosity_jumps) + [end]
cuts = [(t1, t2) for t1, t2 in zip(timings, timings[1:])]
cuts = list(zip(timings, timings[1:]))
Copy link
Author

Choose a reason for hiding this comment

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

Function detect_scenes refactored with the following changes:

if pos is None:
pos = (0, 0) # pragma: no cover
else:
# Cast to tuple in case pos is not subscriptable.
pos = tuple(pos)
pos = (0, 0) if pos is None else tuple(pos)
Copy link
Author

Choose a reason for hiding this comment

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

Function blit refactored with the following changes:

This removes the following comments ( why? ):

# Cast to tuple in case pos is not subscriptable.
# pragma: no cover

Comment on lines -91 to +92
if not sub:
return False
if not sub:
return False
Copy link
Author

Choose a reason for hiding this comment

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

Function SubtitlesClip.__init__.add_textclip_if_none refactored with the following changes:

times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line)
if times:
if times := re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line):
Copy link
Author

Choose a reason for hiding this comment

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

Function file_to_subtitles refactored with the following changes:

Comment on lines -230 to +233
for t in tt[1:]:
xys.append(findAround(clip.get_frame(t), pattern, xy=xys[-1], r=radius))
xys.extend(
findAround(clip.get_frame(t), pattern, xy=xys[-1], r=radius)
for t in tt[1:]
)
Copy link
Author

Choose a reason for hiding this comment

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

Function autoTrack refactored with the following changes:

logfile_name = filename + ".log"
logfile_name = f'{filename}.log'
Copy link
Author

Choose a reason for hiding this comment

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

Function test_ffmpeg_write_video refactored with the following changes:

Comment on lines -175 to +176
assert os.path.isfile(filename + ".log")
os.remove(filename + ".log")
assert os.path.isfile(f'{filename}.log')
os.remove(f'{filename}.log')
Copy link
Author

Choose a reason for hiding this comment

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

Function test_ffmpeg_write_image refactored with the following changes:

bw_color_dict = {}
for num in range(0, 256):
bw_color_dict[chr(num + 255)] = (num, num, num)
bw_color_dict = {chr(num + 255): (num, num, num) for num in range(256)}
Copy link
Author

Choose a reason for hiding this comment

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

Function test_blackwhite refactored with the following changes:

Comment on lines -575 to +573
clip_size = tuple(random.randint(3, 10) for i in range(2))
clip_size = tuple(random.randint(3, 10) for _ in range(2))
Copy link
Author

Choose a reason for hiding this comment

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

Function test_mask_and refactored with the following changes:

Comment on lines -632 to +630
clip_size = tuple(random.randint(3, 10) for i in range(2))
clip_size = tuple(random.randint(3, 10) for _ in range(2))
Copy link
Author

Choose a reason for hiding this comment

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

Function test_mask_or refactored with the following changes:

@sourcery-ai
Copy link
Author

sourcery-ai bot commented Mar 15, 2022

Sourcery Code Quality Report

✅  Merging this PR will increase code quality in the affected files by 0.36%.

Quality metrics Before After Change
Complexity 11.90 🙂 11.41 🙂 -0.49 👍
Method Length 77.59 🙂 77.40 🙂 -0.19 👍
Working memory 10.65 😞 10.66 😞 0.01 👎
Quality 57.14% 🙂 57.50% 🙂 0.36% 👍
Other metrics Before After Change
Lines 10449 10325 -124
Changed files Quality Before Quality After Quality Change
moviepy/Clip.py 77.22% ⭐ 78.63% ⭐ 1.41% 👍
moviepy/decorators.py 79.36% ⭐ 79.78% ⭐ 0.42% 👍
moviepy/tools.py 86.19% ⭐ 86.15% ⭐ -0.04% 👎
moviepy/audio/AudioClip.py 64.58% 🙂 65.02% 🙂 0.44% 👍
moviepy/audio/io/ffmpeg_audiowriter.py 61.95% 🙂 62.29% 🙂 0.34% 👍
moviepy/audio/io/preview.py 48.69% 😞 51.35% 🙂 2.66% 👍
moviepy/audio/io/readers.py 62.13% 🙂 61.86% 🙂 -0.27% 👎
moviepy/video/VideoClip.py 58.50% 🙂 58.76% 🙂 0.26% 👍
moviepy/video/compositing/CompositeVideoClip.py 48.52% 😞 49.19% 😞 0.67% 👍
moviepy/video/compositing/concatenate.py 41.30% 😞 41.30% 😞 0.00%
moviepy/video/fx/fadein.py 80.45% ⭐ 83.99% ⭐ 3.54% 👍
moviepy/video/fx/fadeout.py 74.49% 🙂 77.82% ⭐ 3.33% 👍
moviepy/video/fx/margin.py 59.10% 🙂 59.79% 🙂 0.69% 👍
moviepy/video/fx/rotate.py 29.72% 😞 31.68% 😞 1.96% 👍
moviepy/video/io/ImageSequenceClip.py 34.25% 😞 34.25% 😞 0.00%
moviepy/video/io/ffmpeg_reader.py 44.50% 😞 43.28% 😞 -1.22% 👎
moviepy/video/io/ffmpeg_writer.py 52.95% 🙂 53.51% 🙂 0.56% 👍
moviepy/video/io/gif_writers.py 25.16% 😞 25.05% 😞 -0.11% 👎
moviepy/video/io/html_tools.py 38.77% 😞 38.68% 😞 -0.09% 👎
moviepy/video/io/preview.py 41.25% 😞 42.18% 😞 0.93% 👍
moviepy/video/tools/credits.py 35.41% 😞 38.16% 😞 2.75% 👍
moviepy/video/tools/cuts.py 60.02% 🙂 60.16% 🙂 0.14% 👍
moviepy/video/tools/drawing.py 34.57% 😞 32.98% 😞 -1.59% 👎
moviepy/video/tools/subtitles.py 71.09% 🙂 70.97% 🙂 -0.12% 👎
moviepy/video/tools/tracking.py 51.38% 🙂 51.28% 🙂 -0.10% 👎
tests/conftest.py 63.08% 🙂 68.03% 🙂 4.95% 👍
tests/test_AudioClips.py 69.28% 🙂 69.82% 🙂 0.54% 👍
tests/test_ImageSequenceClip.py 88.98% ⭐ 89.06% ⭐ 0.08% 👍
tests/test_VideoClip.py 76.43% ⭐ 76.43% ⭐ 0.00%
tests/test_ffmpeg_reader.py 69.47% 🙂 70.06% 🙂 0.59% 👍
tests/test_ffmpeg_writer.py 35.98% 😞 35.98% 😞 0.00%
tests/test_fx.py 53.32% 🙂 53.74% 🙂 0.42% 👍
tests/test_tools.py 58.89% 🙂 60.36% 🙂 1.47% 👍

Here are some functions in these files that still need a tune-up:

File Function Complexity Length Working Memory Quality Recommendation
moviepy/video/io/ffmpeg_reader.py FFmpegInfosParser.parse 107 ⛔ 748 ⛔ 24 ⛔ 2.39% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
tests/test_fx.py test_multiply_volume_audioclip 40 ⛔ 444 ⛔ 20 ⛔ 10.52% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
moviepy/video/VideoClip.py TextClip.__init__ 28 😞 330 ⛔ 28 ⛔ 14.28% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
moviepy/video/io/gif_writers.py write_gif 29 😞 417 ⛔ 21 ⛔ 14.62% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
moviepy/video/io/ImageSequenceClip.py ImageSequenceClip.__init__ 35 ⛔ 465 ⛔ 14 😞 17.76% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions

Legend and Explanation

The emojis denote the absolute quality of the code:

  • ⭐ excellent
  • 🙂 good
  • 😞 poor
  • ⛔ very poor

The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request.


Please see our documentation here for details on how these metrics are calculated.

We are actively working on this report - lots more documentation and extra metrics to come!

Help us improve this quality report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

0 participants