Skip to content

Video editing with Python

Formalize flake8 linting (#1439)

Álvaro Mondéjar72e14189efc9
diff --git a/.github/workflows/format_check.yml b/.github/workflows/format_check.yml
index f4b2a104..3375d95d 100644
--- a/.github/workflows/format_check.yml
+++ b/.github/workflows/format_check.yml
@@ -6,6 +6,7 @@ on: [push, pull_request]
jobs:
black:
runs-on: ubuntu-latest
+ name: Black
steps:
- uses: actions/checkout@v2
- name: Set up Python
@@ -14,6 +15,7 @@ jobs:
uses: psf/black@stable # already includes args "--check --diff"
flake8:
runs-on: ubuntu-latest
+ name: Flake8
steps:
- uses: actions/checkout@v2
- name: Set up Python
@@ -23,22 +25,12 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
- pip install .
- pip install flake8
- - name: Flake8
- run: |
- # stop the build if there are Python syntax errors or undefined names
- flake8 . --count --select=E901,E999,F821,F822,F823,W605 --show-source --statistics
- # Some warning codes are ignored because they conflict with black's formatting, or are
- # incompatible with MoviePy's structure
- # E203: whitespace before ':'
- # E302: expected 2 blank lines, found 0
- # E402: module level import not at top of file
- # W291: trailing whitespace
- # W293: blank line contains whitespace
- # W503: line break before binary operator
- flake8 moviepy --ignore=E203,E302,E402,W291,W293,W503 --max-complexity=10 --max-line-length=127 --statistics --count --exit-zero
- # Check examples and tests with slightly relaxed rules to allow 'star' imports
- # F403 'from moviepy import *' used; unable to detect undefined names
- # F405 'name' may be undefined, or defined from star imports: moviepy
- flake8 . --ignore=E203,E302,E402,W291,W293,W503,F403,F405 --exclude moviepy/ --max-complexity=10 --max-line-length=127 --statistics --count --exit-zero
+ pip install .[lint]
+ - name: Lint examples
+ run: flake8 examples --show-source
+ - name: Lint scripts
+ run: flake8 setup.py find_latest_imagemagick_version.py docs/conf.py --show-source
+ - name: Lint tests
+ run: flake8 tests --show-source
+ - name: Lint moviepy
+ run: flake8 moviepy --show-source
diff --git a/README.rst b/README.rst
index 73cf9551..c578ca4b 100644
--- a/README.rst
+++ b/README.rst
@@ -164,6 +164,28 @@ The test suite can then be executed via:
$ pytest
+Linting and formatting
+----------------------
+
+To make sure that all the code is well formatted and consistent, we use Black_ and Flake8_. Install them by navigating to the project directory and running:
+
+.. code:: bash
+
+ $ (sudo) pip install moviepy[lint]
+
+You can lint all files running:
+
+.. code:: bash
+
+ $ flake8
+
+To format the files properly use:
+
+.. code:: bash
+
+ $ black -t py36 .
+
+
Contribute
----------
@@ -212,6 +234,8 @@ Maintainers
.. _ImageMagick: https://www.imagemagick.org/script/index.php
.. _`Matplotlib`: https://matplotlib.org/
.. _`Sphinx`: https://www.sphinx-doc.org/en/master/setuptools.html
+.. _`Black`: https://black.readthedocs.io/en/stable/
+.. _`Flake8`: https://flake8.pycqa.org/en/latest/
.. People
.. _Zulko: https://github.com/Zulko
diff --git a/examples/dancing_knights.py b/examples/dancing_knights.py
index 0bf9e68d..299171f1 100644
--- a/examples/dancing_knights.py
+++ b/examples/dancing_knights.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
"""
Result: https://www.youtube.com/watch?v=Qu7HJrsEYFg
diff --git a/examples/headblur.py b/examples/headblur.py
index 16ea17b6..191ddbbf 100644
--- a/examples/headblur.py
+++ b/examples/headblur.py
@@ -1,5 +1,5 @@
from moviepy import *
-from moviepy.video.tools.tracking import manual_tracking
+from moviepy.video.tools.tracking import manual_tracking # noqa 401
from moviepy.video.tools.interpolators import Trajectory
# LOAD THE CLIP (subclip 6'51 - 7'01 of a chaplin movie)
diff --git a/moviepy/Clip.py b/moviepy/Clip.py
index 58340a68..a7f58a84 100644
--- a/moviepy/Clip.py
+++ b/moviepy/Clip.py
@@ -291,7 +291,7 @@ class Clip:
self.end = None if (duration is None) else (self.start + duration)
else:
if self.duration is None:
- raise Exception("Cannot change clip start when new" "duration is None")
+ raise Exception("Cannot change clip start when new duration is None")
self.start = self.end - duration
@outplace
diff --git a/moviepy/audio/fx/__init__.py b/moviepy/audio/fx/__init__.py
index c52f9eb8..e395d134 100644
--- a/moviepy/audio/fx/__init__.py
+++ b/moviepy/audio/fx/__init__.py
@@ -1,7 +1,18 @@
# import every video fx function
-from .audio_fadein import audio_fadein
-from .audio_fadeout import audio_fadeout
-from .audio_normalize import audio_normalize
-from .multiply_stereo_volume import multiply_stereo_volume
-from .multiply_volume import multiply_volume
+from moviepy.audio.fx.audio_fadein import audio_fadein
+from moviepy.audio.fx.audio_fadeout import audio_fadeout
+from moviepy.audio.fx.audio_loop import audio_loop
+from moviepy.audio.fx.audio_normalize import audio_normalize
+from moviepy.audio.fx.multiply_stereo_volume import multiply_stereo_volume
+from moviepy.audio.fx.multiply_volume import multiply_volume
+
+__all__ = (
+ "audio_fadein",
+ "audio_fadeout",
+ "audio_left_right",
+ "audio_loop",
+ "audio_normalize",
+ "multiply_stereo_volume",
+ "multiply_volume",
+)
diff --git a/moviepy/audio/fx/all/__init__.py b/moviepy/audio/fx/all/__init__.py
index 3731a5f4..f9d87840 100644
--- a/moviepy/audio/fx/all/__init__.py
+++ b/moviepy/audio/fx/all/__init__.py
@@ -1,11 +1,11 @@
"""
-moviepy.audio.fx.all is deprecated.
+moviepy.audio.fx.all is deprecated.
Use the fx method directly from the clip instance (e.g. ``clip.audio_normalize(...)``)
-or import the function from moviepy.audio.fx instead.
+or import the function from moviepy.audio.fx instead.
"""
import warnings
-from .. import *
+from .. import * # noqa 401,F403
warnings.warn(f"\nMoviePy: {__doc__}", UserWarning)
diff --git a/moviepy/audio/fx/audio_loop.py b/moviepy/audio/fx/audio_loop.py
new file mode 100644
index 00000000..5748804b
--- /dev/null
+++ b/moviepy/audio/fx/audio_loop.py
@@ -0,0 +1,26 @@
+from moviepy.audio.AudioClip import concatenate_audioclips
+from moviepy.decorators import audio_video_fx
+
+
+@audio_video_fx
+def audio_loop(clip, n_loops=None, duration=None):
+ """Loops over an audio clip.
+
+ Returns an audio clip that plays the given clip either
+ `n_loops` times, or during `duration` seconds.
+
+ Examples
+ ========
+
+ >>> from moviepy import *
+ >>> videoclip = VideoFileClip('myvideo.mp4')
+ >>> music = AudioFileClip('music.ogg')
+ >>> audio = afx.audio_loop( music, duration=videoclip.duration)
+ >>> videoclip.with_audio(audio)
+
+ """
+ if duration is not None:
+ n_loops = int(duration / clip.duration) + 1
+ return concatenate_audioclips(n_loops * [clip]).with_duration(duration)
+
+ return concatenate_audioclips(n_loops * [clip])
diff --git a/moviepy/audio/fx/audio_normalize.py b/moviepy/audio/fx/audio_normalize.py
index 984054c5..31aad7ce 100644
--- a/moviepy/audio/fx/audio_normalize.py
+++ b/moviepy/audio/fx/audio_normalize.py
@@ -1,6 +1,6 @@
from moviepy.decorators import audio_video_fx
-from .multiply_volume import multiply_volume
+from moviepy.audio.fx.multiply_volume import multiply_volume
@audio_video_fx
diff --git a/moviepy/audio/fx/multiply_stereo_volume.py b/moviepy/audio/fx/multiply_stereo_volume.py
index 1116e098..e9d857cc 100644
--- a/moviepy/audio/fx/multiply_stereo_volume.py
+++ b/moviepy/audio/fx/multiply_stereo_volume.py
@@ -1,5 +1,3 @@
-import numpy as np
-
from moviepy.decorators import audio_video_fx
diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.py
index fe49070f..8b6d4244 100644
--- a/moviepy/audio/io/AudioFileClip.py
+++ b/moviepy/audio/io/AudioFileClip.py
@@ -1,5 +1,3 @@
-from __future__ import division
-
from moviepy.audio.AudioClip import AudioClip
from moviepy.audio.io.readers import FFMPEG_AudioReader
from moviepy.decorators import convert_path_to_string
@@ -43,10 +41,12 @@ class AudioFileClip(AudioClip):
Lifetime
--------
- Note that this creates subprocesses and locks files. If you construct one of these instances, you must call
- close() afterwards, or the subresources will not be cleaned up until the process ends.
+ Note that this creates subprocesses and locks files. If you construct one
+ of these instances, you must call close() afterwards, or the subresources
+ will not be cleaned up until the process ends.
- If copies are made, and close() is called on one, it may cause methods on the other copies to fail.
+ If copies are made, and close() is called on one, it may cause methods on
+ the other copies to fail.
However, coreaders must be closed separately.
diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.py
index 2b72f643..409f4d1c 100644
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@ -1,6 +1,5 @@
import os
import subprocess as sp
-import warnings
import proglog
diff --git a/moviepy/editor.py b/moviepy/editor.py
index 4723c9d8..fc9037ce 100644
--- a/moviepy/editor.py
+++ b/moviepy/editor.py
@@ -4,7 +4,8 @@ MoviePy that you will use for live editing by simply typing:
>>> from moviepy.editor import *
-- Starts a pygame session to enable ``clip.show()`` and ``clip.preview()`` if pygame is installed
+- Starts a pygame session to enable ``clip.show()`` and ``clip.preview()``
+ if pygame is installed
- Enables ``clip.ipython_display()`` if in an IPython Notebook
- Allows the use of ``sliders`` if Matplotlib is installed
"""
@@ -16,7 +17,7 @@ from moviepy import *
from moviepy.video.io.html_tools import ipython_display
try:
- from .video.io.sliders import sliders
+ from moviepy.video.io.sliders import sliders
except ImportError:
def sliders(*args, **kwargs):
@@ -38,7 +39,7 @@ os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
# Add methods preview and show (only if pygame installed)
try:
- from .video.io.preview import show, preview
+ from moviepy.video.io.preview import show, preview
except ImportError:
def preview(self, *args, **kwargs):
@@ -54,7 +55,7 @@ VideoClip.preview = preview
VideoClip.show = show
try:
- from .audio.io.preview import preview
+ from moviepy.audio.io.preview import preview
except ImportError:
def preview(self, *args, **kwargs):
diff --git a/moviepy/tools.py b/moviepy/tools.py
index 200bb190..36c7f12c 100644
--- a/moviepy/tools.py
+++ b/moviepy/tools.py
@@ -3,7 +3,6 @@ Misc. useful functions that can be used at many places in the program.
"""
import os
import subprocess as sp
-import sys
import warnings
import proglog
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index b6fdd4dc..66d909fb 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -227,8 +227,8 @@ class VideoClip(Clip):
frame rate to use when generating the sound.
temp_audiofile
- the name of the temporary audiofile, as a string or path-like object, to be created and
- then used to write the complete video, if any.
+ the name of the temporary audiofile, as a string or path-like object,
+ to be created and then used to write the complete video, if any.
temp_audiofile_path
the location that the temporary audiofile is placed, as a
@@ -709,7 +709,7 @@ class VideoClip(Clip):
background.
"""
- from .compositing.CompositeVideoClip import CompositeVideoClip
+ from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
if size is None:
size = self.size
@@ -1312,12 +1312,12 @@ class TextClip(ImageClip):
if arg == "font":
# Slice removes first 8 characters: " Font: "
- return [l[8:] for l in lines if l.startswith(" Font:")]
+ return [line[8:] for line in lines if line.startswith(" Font:")]
elif arg == "color":
- # Each line is of the format "aqua srgb(0,255,255) SVG" so split on space and take
- # the first item to get the color name.
+ # Each line is of the format "aqua srgb(0,255,255) SVG" so split
+ # on space and take the first item to get the color name.
# The first 5 lines are header information, not colors, so ignore
- return [l.split(" ")[0] for l in lines[5:]]
+ return [line.split(" ")[0] for line in lines[5:]]
else:
raise Exception("Moviepy Error: Argument must equal 'font' or 'color'")
@@ -1354,14 +1354,15 @@ class BitmapClip(VideoClip):
self, bitmap_frames, *, fps=None, duration=None, color_dict=None, is_mask=False
):
"""
- Creates a VideoClip object from a bitmap representation. Primarily used in the test suite.
+ Creates a VideoClip object from a bitmap representation. Primarily used
+ in the test suite.
Parameters
-----------
bitmap_frames
- A list of frames. Each frame is a list of strings. Each string represents a row of colors.
- Each color represents an (r, g, b) tuple.
+ A list of frames. Each frame is a list of strings. Each string
+ represents a row of colors. Each color represents an (r, g, b) tuple.
Example input (2 frames, 5x3 pixel size):
[["RRRRR",
"RRBRR",
@@ -1371,16 +1372,18 @@ class BitmapClip(VideoClip):
"RGGGR"]]
fps
- The number of frames per second to display the clip at. `duration` will calculated from the total number of frames.
- If both `fps` and `duration` are set, `duration` will be ignored.
+ The number of frames per second to display the clip at. `duration` will
+ calculated from the total number of frames. If both `fps` and `duration`
+ are set, `duration` will be ignored.
duration
- The total duration of the clip. `fps` will be calculated from the total number of frames.
- If both `fps` and `duration` are set, `duration` will be ignored.
+ The total duration of the clip. `fps` will be calculated from the total
+ number of frames. If both `fps` and `duration` are set, `duration` will
+ be ignored.
color_dict
- A dictionary that can be used to set specific (r, g, b) values that correspond
- to the letters used in ``bitmap_frames``.
+ A dictionary that can be used to set specific (r, g, b) values that
+ correspond to the letters used in ``bitmap_frames``.
eg ``{"A": (50, 150, 150)}``.
Defaults to
diff --git a/moviepy/video/compositing/transitions.py b/moviepy/video/compositing/transitions.py
index 0f5083a2..e5b0c83e 100644
--- a/moviepy/video/compositing/transitions.py
+++ b/moviepy/video/compositing/transitions.py
@@ -7,7 +7,7 @@ from moviepy.decorators import add_mask_if_none, requires_duration
from moviepy.video.fx.fadein import fadein
from moviepy.video.fx.fadeout import fadeout
-from .CompositeVideoClip import CompositeVideoClip
+from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
__all__ = ["crossfadein", "crossfadeout", "slide_in", "slide_out", "make_loopable"]
diff --git a/moviepy/video/fx/__init__.py b/moviepy/video/fx/__init__.py
index 4dc78e68..f99cfa51 100644
--- a/moviepy/video/fx/__init__.py
+++ b/moviepy/video/fx/__init__.py
@@ -1,32 +1,66 @@
# import every video fx function
-from .accel_decel import accel_decel
-from .blackwhite import blackwhite
-from .blink import blink
-from .colorx import colorx
-from .crop import crop
-from .even_size import even_size
-from .fadein import fadein
-from .fadeout import fadeout
-from .freeze import freeze
-from .freeze_region import freeze_region
-from .gamma_corr import gamma_corr
-from .headblur import headblur
-from .invert_colors import invert_colors
-from .loop import loop
-from .lum_contrast import lum_contrast
-from .make_loopable import make_loopable
-from .margin import margin
-from .mask_and import mask_and
-from .mask_color import mask_color
-from .mask_or import mask_or
-from .mirror_x import mirror_x
-from .mirror_y import mirror_y
-from .painting import painting
-from .resize import resize
-from .rotate import rotate
-from .scroll import scroll
-from .speedx import speedx
-from .supersample import supersample
-from .time_mirror import time_mirror
-from .time_symmetrize import time_symmetrize
+from moviepy.video.fx.accel_decel import accel_decel
+from moviepy.video.fx.blackwhite import blackwhite
+from moviepy.video.fx.blink import blink
+from moviepy.video.fx.colorx import colorx
+from moviepy.video.fx.crop import crop
+from moviepy.video.fx.even_size import even_size
+from moviepy.video.fx.fadein import fadein
+from moviepy.video.fx.fadeout import fadeout
+from moviepy.video.fx.freeze import freeze
+from moviepy.video.fx.freeze_region import freeze_region
+from moviepy.video.fx.gamma_corr import gamma_corr
+from moviepy.video.fx.headblur import headblur
+from moviepy.video.fx.invert_colors import invert_colors
+from moviepy.video.fx.loop import loop
+from moviepy.video.fx.lum_contrast import lum_contrast
+from moviepy.video.fx.make_loopable import make_loopable
+from moviepy.video.fx.margin import margin
+from moviepy.video.fx.mask_and import mask_and
+from moviepy.video.fx.mask_color import mask_color
+from moviepy.video.fx.mask_or import mask_or
+from moviepy.video.fx.mirror_x import mirror_x
+from moviepy.video.fx.mirror_y import mirror_y
+from moviepy.video.fx.painting import painting
+from moviepy.video.fx.resize import resize
+from moviepy.video.fx.rotate import rotate
+from moviepy.video.fx.scroll import scroll
+from moviepy.video.fx.speedx import speedx
+from moviepy.video.fx.supersample import supersample
+from moviepy.video.fx.time_mirror import time_mirror
+from moviepy.video.fx.time_symmetrize import time_symmetrize
+
+
+__all__ = (
+ "accel_decel",
+ "blackwhite",
+ "blink",
+ "colorx",
+ "crop",
+ "even_size",
+ "fadein",
+ "fadeout",
+ "freeze",
+ "freeze_region",
+ "gamma_corr",
+ "headblur",
+ "invert_colors",
+ "loop",
+ "lum_contrast",
+ "make_loopable",
+ "margin",
+ "mask_and",
+ "mask_color",
+ "mask_or",
+ "mirror_x",
+ "mirror_y",
+ "painting",
+ "resize",
+ "rotate",
+ "scroll",
+ "speedx",
+ "supersample",
+ "time_mirror",
+ "time_symmetrize",
+)
diff --git a/moviepy/video/fx/all/__init__.py b/moviepy/video/fx/all/__init__.py
index 47364b51..988ef398 100644
--- a/moviepy/video/fx/all/__init__.py
+++ b/moviepy/video/fx/all/__init__.py
@@ -1,11 +1,11 @@
"""
-moviepy.video.fx.all is deprecated.
+moviepy.video.fx.all is deprecated.
Use the fx method directly from the clip instance (e.g. ``clip.resize(...)``)
-or import the function from moviepy.video.fx instead.
+or import the function from moviepy.video.fx instead.
"""
import warnings
-from .. import *
+from moviepy.video.fx import * # noqa F401,F403
warnings.warn(f"\nMoviePy: {__doc__}", UserWarning)
diff --git a/moviepy/video/fx/freeze.py b/moviepy/video/fx/freeze.py
index 76f13d96..f272c8b6 100644
--- a/moviepy/video/fx/freeze.py
+++ b/moviepy/video/fx/freeze.py
@@ -1,6 +1,5 @@
from moviepy.decorators import requires_duration
from moviepy.video.compositing.concatenate import concatenate_videoclips
-from moviepy.video.VideoClip import ImageClip
@requires_duration
diff --git a/moviepy/video/fx/freeze_region.py b/moviepy/video/fx/freeze_region.py
index f9b5034f..718b93b4 100644
--- a/moviepy/video/fx/freeze_region.py
+++ b/moviepy/video/fx/freeze_region.py
@@ -1,10 +1,8 @@
-from moviepy.decorators import apply_to_mask
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
-from .crop import crop
+from moviepy.video.fx.crop import crop
-# @apply_to_mask
def freeze_region(clip, t=0, region=None, outside_region=None, mask=None):
"""Freezes one region of the clip while the rest remains animated.
diff --git a/moviepy/video/fx/loop.py b/moviepy/video/fx/loop.py
index b05c5e4f..cfba88f6 100644
--- a/moviepy/video/fx/loop.py
+++ b/moviepy/video/fx/loop.py
@@ -1,4 +1,4 @@
-from moviepy.decorators import apply_to_audio, apply_to_mask, requires_duration
+from moviepy.decorators import requires_duration
@requires_duration
diff --git a/moviepy/video/fx/mask_and.py b/moviepy/video/fx/mask_and.py
index 5603c6d6..e3306f2a 100644
--- a/moviepy/video/fx/mask_and.py
+++ b/moviepy/video/fx/mask_and.py
@@ -1,6 +1,6 @@
import numpy as np
-from ..VideoClip import ImageClip
+from moviepy.video.VideoClip import ImageClip
def mask_and(clip, other_clip):
diff --git a/moviepy/video/fx/mask_color.py b/moviepy/video/fx/mask_color.py
index 3f745f49..fec1ddc8 100644
--- a/moviepy/video/fx/mask_color.py
+++ b/moviepy/video/fx/mask_color.py
@@ -6,13 +6,13 @@ def mask_color(clip, color=None, threshold=0, stiffness=1):
clip is of the given color.
You can also have a "progressive" mask by specifying a non-null distance
- threshold ``threshold``. In this case, if the distance between a pixel and the given
- color is d, the transparency will be
+ threshold ``threshold``. In this case, if the distance between a pixel and
+ the given color is d, the transparency will be
d**stiffness / (threshold**stiffness + d**stiffness)
- which is 1 when d>>threshold and 0 for d<<threshold, the stiffness of the effect being
- parametrized by ``stiffness``
+ which is 1 when d>>threshold and 0 for d<<threshold, the stiffness of the
+ effect being parametrized by ``stiffness``
"""
if color is None:
color = [0, 0, 0]
diff --git a/moviepy/video/fx/mask_or.py b/moviepy/video/fx/mask_or.py
index a06fb20c..fda26fa9 100644
--- a/moviepy/video/fx/mask_or.py
+++ b/moviepy/video/fx/mask_or.py
@@ -1,6 +1,6 @@
import numpy as np
-from ..VideoClip import ImageClip
+from moviepy.video.VideoClip import ImageClip
def mask_or(clip, other_clip):
diff --git a/moviepy/video/fx/painting.py b/moviepy/video/fx/painting.py
index c1411387..97d61d81 100644
--- a/moviepy/video/fx/painting.py
+++ b/moviepy/video/fx/painting.py
@@ -1,3 +1,5 @@
+import numpy as np
+
# ------- CHECKING DEPENDENCIES -----------------------------------------
painting_possible = True
try:
@@ -10,9 +12,6 @@ except Exception:
# -----------------------------------------------------------------------
-import numpy as np
-
-
def to_painting(image, saturation=1.4, black=0.006):
""" transforms any photo into some kind of painting """
edges = sobel(image.mean(axis=2))
diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.py
index 4200cacc..98c8eda4 100644
--- a/moviepy/video/fx/resize.py
+++ b/moviepy/video/fx/resize.py
@@ -27,11 +27,11 @@ except ImportError:
def resizer(pic, new_size):
new_size = list(map(int, new_size))[::-1]
- shape = pic.shape
- if len(shape) == 3:
- newshape = (new_size[0], new_size[1], shape[2])
- else:
- newshape = (new_size[0], new_size[1])
+ # shape = pic.shape
+ # if len(shape) == 3:
+ # newshape = (new_size[0], new_size[1], shape[2])
+ # else:
+ # newshape = (new_size[0], new_size[1])
pil_img = Image.fromarray(pic)
resized_pil = pil_img.resize(new_size[::-1], Image.ANTIALIAS)
@@ -91,9 +91,9 @@ def resize(clip, new_size=None, height=None, width=None, apply_to_mask=True):
if new_size is not None:
def translate_new_size(new_size_):
- """
- Returns a [w, h] pair from `new_size_`. If `new_size_` is a scalar, then work out
- the correct pair using the clip's size. Otherwise just return `new_size_`
+ """Returns a [w, h] pair from `new_size_`. If `new_size_` is a
+ scalar, then work out the correct pair using the clip's size.
+ Otherwise just return `new_size_`
"""
if isinstance(new_size_, (int, float)):
return [new_size_ * w, new_size_ * h]
diff --git a/moviepy/video/fx/rotate.py b/moviepy/video/fx/rotate.py
index aa63a7e4..81557fd1 100644
--- a/moviepy/video/fx/rotate.py
+++ b/moviepy/video/fx/rotate.py
@@ -1,7 +1,5 @@
import numpy as np
-from moviepy.decorators import apply_to_mask
-
try:
from PIL import Image
@@ -23,8 +21,9 @@ except ImportError:
def rotate(clip, angle, unit="deg", resample="bicubic", expand=True):
"""
Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise
- If the angle is not a multiple of 90 (degrees), the package ``pillow`` must be installed,
- and there will be black borders. You can make them transparent with
+ If the angle is not a multiple of 90 (degrees), the package ``pillow`` must
+ be installed, and there will be black borders. You can make them
+ transparent with
>>> new_clip = clip.add_mask().rotate(72)
@@ -45,7 +44,8 @@ def rotate(clip, angle, unit="deg", resample="bicubic", expand=True):
One of "nearest", "bilinear", or "bicubic".
expand
- Only applIf False, the clip will maintain the same True, the clip will be resized so that the whole
+ Only applIf False, the clip will maintain the same True, the clip will be
+ resized so that the whole
"""
if PIL_FOUND:
resample = {
diff --git a/moviepy/video/fx/speedx.py b/moviepy/video/fx/speedx.py
index 6e93fc05..a7446054 100644
--- a/moviepy/video/fx/speedx.py
+++ b/moviepy/video/fx/speedx.py
@@ -1,6 +1,3 @@
-from moviepy.decorators import apply_to_audio, apply_to_mask
-
-
def speedx(clip, factor=None, final_duration=None):
"""
Returns a clip playing the current clip but at a speed multiplied
diff --git a/moviepy/video/fx/time_symmetrize.py b/moviepy/video/fx/time_symmetrize.py
index e4ebb8b5..e561776f 100644
--- a/moviepy/video/fx/time_symmetrize.py
+++ b/moviepy/video/fx/time_symmetrize.py
@@ -1,7 +1,7 @@
-from moviepy.decorators import apply_to_audio, apply_to_mask, requires_duration
+from moviepy.decorators import apply_to_mask, requires_duration
from moviepy.video.compositing.concatenate import concatenate_videoclips
-from .time_mirror import time_mirror
+from moviepy.video.fx.time_mirror import time_mirror
@requires_duration
diff --git a/moviepy/video/io/ImageSequenceClip.py b/moviepy/video/io/ImageSequenceClip.py
index 5104a6ba..a5b9e52c 100644
--- a/moviepy/video/io/ImageSequenceClip.py
+++ b/moviepy/video/io/ImageSequenceClip.py
@@ -3,7 +3,7 @@ import os
import numpy as np
from imageio import imread
-from ..VideoClip import VideoClip
+from moviepy.video.VideoClip import VideoClip
class ImageSequenceClip(VideoClip):
diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.py
index 432889f2..f17cb23c 100644
--- a/moviepy/video/io/VideoFileClip.py
+++ b/moviepy/video/io/VideoFileClip.py
@@ -72,10 +72,12 @@ class VideoFileClip(VideoClip):
Lifetime
--------
- Note that this creates subprocesses and locks files. If you construct one of these instances, you must call
- close() afterwards, or the subresources will not be cleaned up until the process ends.
+ Note that this creates subprocesses and locks files. If you construct one
+ of these instances, you must call close() afterwards, or the subresources
+ will not be cleaned up until the process ends.
- If copies are made, and close() is called on one, it may cause methods on the other copies to fail.
+ If copies are made, and close() is called on one, it may cause methods on
+ the other copies to fail.
"""
diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.py
index 5cd67417..f66529df 100644
--- a/moviepy/video/io/ffmpeg_reader.py
+++ b/moviepy/video/io/ffmpeg_reader.py
@@ -3,8 +3,6 @@ This module implements all the functions to read a video or a picture
using ffmpeg. It is quite ugly, as there are many pitfalls to avoid
"""
-from __future__ import division
-
import os
import re
import subprocess as sp
@@ -149,12 +147,20 @@ class FFMPEG_VideoReader:
if len(s) != nbytes:
warnings.warn(
- f"In file {self.filename}, "
- + "%d bytes wanted but %d bytes read," % (nbytes, len(s))
- + f"at frame index {self.pos} (out of a total {self.nframes} frames), "
- + f"at time %.02f/%.02f sec. "
- % (1.0 * self.pos / self.fps, self.duration)
- + "Using the last valid frame instead.",
+ (
+ "In file %s, %d bytes wanted but %d bytes read at frame index"
+ " %d (out of a total %d frames), at time %.02f/%.02f sec."
+ " Using the last valid frame instead."
+ )
+ % (
+ self.filename,
+ nbytes,
+ len(s),
+ self.pos,
+ self.nframes,
+ 1.0 * self.pos / self.fps,
+ self.duration,
+ ),
UserWarning,
)
if not hasattr(self, "last_read"):
@@ -199,7 +205,7 @@ class FFMPEG_VideoReader:
# Initialize proc if it is not open
if not self.proc:
- print(f"Proc not detected")
+ print("Proc not detected")
self.initialize(t)
return self.last_read
@@ -335,14 +341,15 @@ def ffmpeg_parse_infos(
if check_duration:
try:
if decode_file:
- line = [l for l in lines if "time=" in l][-1]
+ line = [line for line in lines if "time=" in line][-1]
else:
- line = [l for l in lines if "Duration:" in l][-1]
+ line = [line for line in lines if "Duration:" in line][-1]
match = re.findall("([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])", line)[0]
result["duration"] = convert_to_seconds(match)
except Exception:
raise IOError(
- f"MoviePy error: failed to read the duration of file {filename}.\nHere are the file infos returned by ffmpeg:\n\n{infos}"
+ f"MoviePy error: failed to read the duration of file {filename}.\n"
+ f"Here are the file infos returned by ffmpeg:\n\n{infos}"
)
# get the output line that speaks about video
@@ -449,7 +456,7 @@ def ffmpeg_parse_infos(
% (filename, infos)
)
- lines_audio = [l for l in lines if " Audio: " in l]
+ lines_audio = [line for line in lines if " Audio: " in line]
result["audio_found"] = lines_audio != []
diff --git a/moviepy/video/io/html_tools.py b/moviepy/video/io/html_tools.py
index bc6e2bbe..a94c21dd 100644
--- a/moviepy/video/io/html_tools.py
+++ b/moviepy/video/io/html_tools.py
@@ -15,8 +15,8 @@ from base64 import b64encode
from moviepy.audio.AudioClip import AudioClip
from moviepy.tools import extensions_dict
-from ..VideoClip import ImageClip, VideoClip
-from .ffmpeg_reader import ffmpeg_parse_infos
+from moviepy.video.VideoClip import ImageClip, VideoClip
+from moviepy.video.io.ffmpeg_reader import ffmpeg_parse_infos
try:
from IPython.display import HTML
@@ -40,7 +40,7 @@ templates = {
+ sorry
+ "</audio>"
),
- "image": "<img %(options)s " "src='data:image/%(ext)s;base64,%(data)s'>",
+ "image": "<img %(options)s src='data:image/%(ext)s;base64,%(data)s'>",
"video": (
"<video %(options)s"
"src='data:video/%(ext)s;base64,%(data)s' controls>" + sorry + "</video>"
@@ -139,15 +139,17 @@ def html_embed(
)
if filetype in ["audio", "video"]:
-
duration = ffmpeg_parse_infos(filename, decode_file=True)["duration"]
if duration > maxduration:
raise ValueError(
- "The duration of video %s (%.1f) exceeds the 'maxduration' "
+ (
+ "The duration of video %s (%.1f) exceeds the 'maxduration'"
+ " attribute. You can increase 'maxduration', by passing"
+ " 'maxduration' parameter to ipython_display function."
+ " But note that embedding large videos may take all the memory"
+ " away!"
+ )
% (filename, duration)
- + "attribute. You can increase 'maxduration', by passing 'maxduration' parameter"
- "to ipython_display function."
- "But note that embedding large videos may take all the memory away !"
)
with open(filename, "rb") as file:
diff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.py
index 33683797..c50d6ed3 100644
--- a/moviepy/video/tools/cuts.py
+++ b/moviepy/video/tools/cuts.py
@@ -83,8 +83,8 @@ class FramesMatches(list):
def filter(self, condition):
"""
Returns a FramesMatches object obtained by filtering out the FramesMatch
- which do not satistify the condition ``condition``. ``condition`` is a function
- (FrameMatch -> bool).
+ which do not satistify the condition ``condition``. ``condition``
+ is a function (FrameMatch -> bool).
Examples
---------
@@ -116,7 +116,8 @@ class FramesMatches(list):
looping gif.
This teturns a FramesMatches object of the all pairs of frames with
- (end_time-start_time < max_duration) and whose distance is under distance_threshold.
+ (end_time-start_time < max_duration) and whose distance is under
+ distance_threshold.
This is well optimized routine and quite fast.
@@ -129,7 +130,8 @@ class FramesMatches(list):
>>> from moviepy import VideoFileClip
>>> from moviepy.video.tools.cuts import FramesMatches
>>> clip = VideoFileClip("foo.mp4").resize(width=200)
- >>> matches = FramesMatches.from_clip(clip, distance_threshold=10, max_duration=3) # will take time
+ >>> matches = FramesMatches.from_clip(clip, distance_threshold=10,
+ ... max_duration=3) # will take time
>>> best = matches.filter(lambda m: m.time_span > 1.5).best()
>>> clip.subclip(best.start_time, best.end_time).write_gif("foo.gif")
diff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.py
index a4d54031..6f93b049 100644
--- a/moviepy/video/tools/subtitles.py
+++ b/moviepy/video/tools/subtitles.py
@@ -24,14 +24,16 @@ class SubtitlesClip(VideoClip):
encoding
Optional, specifies srt file encoding.
- Any standard Python encoding is allowed (listed at https://docs.python.org/3.8/library/codecs.html#standard-encodings)
+ Any standard Python encoding is allowed (listed at
+ https://docs.python.org/3.8/library/codecs.html#standard-encodings)
Examples
=========
>>> from moviepy.video.tools.subtitles import SubtitlesClip
>>> from moviepy.video.io.VideoFileClip import VideoFileClip
- >>> generator = lambda text: TextClip(text, font='Georgia-Regular', font_size=24, color='white')
+ >>> generator = lambda text: TextClip(text, font='Georgia-Regular',
+ ... font_size=24, color='white')
>>> sub = SubtitlesClip("subtitles.srt", generator)
>>> sub = SubtitlesClip("subtitles.srt", generator, encoding='utf-8')
>>> myvideo = VideoFileClip("myvideo.avi")
@@ -48,7 +50,8 @@ class SubtitlesClip(VideoClip):
# `subtitles` is a string or path-like object
subtitles = file_to_subtitles(subtitles, encoding=encoding)
- # subtitles = [(map(convert_to_seconds, times),text) for times, text in subtitles]
+ # subtitles = [(map(convert_to_seconds, times), text)
+ # for times, text in subtitles]
self.subtitles = subtitles
self.textclips = dict()
diff --git a/moviepy/video/tools/tracking.py b/moviepy/video/tools/tracking.py
index 313f2874..07aaf98a 100644
--- a/moviepy/video/tools/tracking.py
+++ b/moviepy/video/tools/tracking.py
@@ -12,8 +12,8 @@ import numpy as np
from moviepy.decorators import convert_parameter_to_seconds, use_clip_fps_by_default
-from ..io.preview import imdisplay
-from .interpolators import Trajectory
+from moviepy.video.io.preview import imdisplay
+from moviepy.video.tools.interpolators import Trajectory
try:
import cv2
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 00000000..7f5ffeb9
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,17 @@
+[flake8]
+max-line-length = 88
+extend-ignore =
+ # Black compatibility
+ E203,
+ W503,
+ # allow lambda expressions
+ E731
+per-file-ignores =
+ # allow imports not placed at the top of the file
+ # allow 'from moviepy import *' in editor.py
+ moviepy/editor.py: E402, F403, F405
+ # allow 'from moviepy import *' in examples
+ examples/*.py: F403, F405
+
+# Complexity should be decreased before uncomment:
+#max-complexity = 10
diff --git a/setup.py b/setup.py
index 0720724a..60266309 100644
--- a/setup.py
+++ b/setup.py
@@ -102,10 +102,21 @@ test_reqs = [
"coveralls>=3.0.0",
"pytest-cov>=2.5.1,<3.0",
"pytest>=3.0.0,<4.0",
- "requests>=2.8.1,<3.0",
]
-extra_reqs = {"optional": optional_reqs, "doc": doc_reqs, "test": test_reqs}
+lint_reqs = [
+ "black>=20.8b1",
+ "flake8>3.7.0,<4.0.0",
+ "flake8-implicit-str-concat==0.2.0",
+ "flake8-absolute-import>=1.0",
+]
+
+extra_reqs = {
+ "optional": optional_reqs,
+ "doc": doc_reqs,
+ "test": test_reqs,
+ "lint": lint_reqs,
+}
# Load the README.
with open("README.rst", "r", "utf-8") as file:
diff --git a/tests/test_AudioClips.py b/tests/test_AudioClips.py
index ee7dc7ab..3e115512 100644
--- a/tests/test_AudioClips.py
+++ b/tests/test_AudioClips.py
@@ -1,16 +1,13 @@
-# -*- coding: utf-8 -*-
"""Image sequencing clip tests meant to be run with pytest."""
+
import os
-import sys
import pytest
import numpy as np
-from numpy import pi, sin
from moviepy.audio.AudioClip import (
AudioArrayClip,
AudioClip,
- CompositeAudioClip,
concatenate_audioclips,
)
from moviepy.audio.io.AudioFileClip import AudioFileClip
@@ -27,7 +24,7 @@ def test_audio_coreader():
def test_audioclip():
- make_frame = lambda t: [sin(440 * 2 * pi * t)]
+ make_frame = lambda t: [np.sin(440 * 2 * np.pi * t)]
audio = AudioClip(make_frame, duration=2, fps=22050)
audio.write_audiofile(os.path.join(TMP_DIR, "audioclip.mp3"), bitrate="16")
@@ -62,8 +59,8 @@ def test_audioclip_io():
def test_audioclip_concat():
- make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]
- make_frame_880 = lambda t: [sin(880 * 2 * pi * t)]
+ make_frame_440 = lambda t: [np.sin(440 * 2 * np.pi * t)]
+ make_frame_880 = lambda t: [np.sin(880 * 2 * np.pi * t)]
clip1 = AudioClip(make_frame_440, duration=1, fps=44100)
clip2 = AudioClip(make_frame_880, duration=2, fps=22050)
@@ -80,7 +77,7 @@ def test_audioclip_concat():
def test_audioclip_with_file_concat():
- make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]
+ make_frame_440 = lambda t: [np.sin(440 * 2 * np.pi * t)]
clip1 = AudioClip(make_frame_440, duration=1, fps=44100)
clip2 = AudioFileClip("media/crunching.mp3")
diff --git a/tests/test_ImageSequenceClip.py b/tests/test_ImageSequenceClip.py
index a998ff5f..9fa11973 100644
--- a/tests/test_ImageSequenceClip.py
+++ b/tests/test_ImageSequenceClip.py
@@ -1,5 +1,5 @@
-# -*- coding: utf-8 -*-
"""Image sequencing clip tests meant to be run with pytest."""
+
import os
import pytest
diff --git a/tests/test_PR.py b/tests/test_PR.py
index 96e4fb1e..37dc46c8 100644
--- a/tests/test_PR.py
+++ b/tests/test_PR.py
@@ -1,5 +1,5 @@
-# -*- coding: utf-8 -*-
"""Pull request tests meant to be run with pytest."""
+
import os
from pathlib import Path
diff --git a/tests/test_VideoClip.py b/tests/test_VideoClip.py
index ea3dc090..964d1dfc 100644
--- a/tests/test_VideoClip.py
+++ b/tests/test_VideoClip.py
@@ -1,7 +1,7 @@
import os
+import numpy as np
import pytest
-from numpy import pi, sin, array
from moviepy.audio.AudioClip import AudioClip
from moviepy.audio.io.AudioFileClip import AudioFileClip
@@ -39,8 +39,8 @@ def test_write_frame_errors():
with pytest.raises(IOError) as e:
clip.write_videofile(location, codec="nonexistent-codec")
assert (
- "The video export failed because FFMPEG didn't find the specified codec for video "
- "encoding nonexistent-codec" in str(e.value)
+ "The video export failed because FFMPEG didn't find the specified"
+ " codec for video encoding nonexistent-codec" in str(e.value)
), e.value
close_all_clips(locals())
@@ -57,8 +57,8 @@ def test_write_frame_errors_with_redirected_logs():
with pytest.raises(IOError) as e:
clip.write_videofile(location, codec="nonexistent-codec", write_logfile=True)
assert (
- "The video export failed because FFMPEG didn't find the specified codec for video "
- "encoding nonexistent-codec" in str(e.value)
+ "The video export failed because FFMPEG didn't find the specified"
+ " codec for video encoding nonexistent-codec" in str(e.value)
)
close_all_clips(locals())
@@ -197,7 +197,7 @@ def test_oncolor():
def test_setaudio():
clip = ColorClip(size=(100, 60), color=(255, 0, 0), duration=0.5)
- make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]
+ make_frame_440 = lambda t: [np.sin(440 * 2 * np.pi * t)]
audio = AudioClip(make_frame_440, duration=0.5)
audio.fps = 44100
clip = clip.with_audio(audio)
diff --git a/tests/test_VideoFileClip.py b/tests/test_VideoFileClip.py
index b17844fc..6ce2d185 100644
--- a/tests/test_VideoFileClip.py
+++ b/tests/test_VideoFileClip.py
@@ -1,5 +1,5 @@
-# -*- coding: utf-8 -*-
"""Video file clip tests meant to be run with pytest."""
+
import os
import pytest
diff --git a/tests/test_Videos.py b/tests/test_Videos.py
index 183fae13..c6625c30 100644
--- a/tests/test_Videos.py
+++ b/tests/test_Videos.py
@@ -1,5 +1,5 @@
-# -*- coding: utf-8 -*-
"""Video tests meant to be run with pytest."""
+
import os
import pytest
diff --git a/tests/test_compositing.py b/tests/test_compositing.py
index f46c361d..685970da 100644
--- a/tests/test_compositing.py
+++ b/tests/test_compositing.py
@@ -1,10 +1,13 @@
-# -*- coding: utf-8 -*-
"""Compositing tests for use with pytest."""
-from os.path import join
+
+import os
import pytest
-from moviepy import *
+from moviepy.video.VideoClip import BitmapClip, ColorClip
+from moviepy.video.compositing.concatenate import concatenate_videoclips
+from moviepy.video.compositing.CompositeVideoClip import clips_array
+from moviepy.video.fx.resize import resize
from moviepy.utils import close_all_clips
from tests.test_helper import TMP_DIR
@@ -18,7 +21,9 @@ def test_clips_array():
video = clips_array([[red, green, blue]])
with pytest.raises(ValueError): # duration not set
- video.resize(width=480).write_videofile(join(TMP_DIR, "test_clips_array.mp4"))
+ video.fx(resize, width=480).write_videofile(
+ os.path.join(TMP_DIR, "test_clips_array.mp4")
+ )
close_all_clips(locals())
@@ -31,12 +36,12 @@ def test_clips_array_duration():
video = clips_array([[red, green, blue]]).with_duration(5)
with pytest.raises(AttributeError): # fps not set
- video.write_videofile(join(TMP_DIR, "test_clips_array.mp4"))
+ video.write_videofile(os.path.join(TMP_DIR, "test_clips_array.mp4"))
# this one should work correctly
red.fps = green.fps = blue.fps = 30
video = clips_array([[red, green, blue]]).with_duration(5)
- video.write_videofile(join(TMP_DIR, "test_clips_array.mp4"))
+ video.write_videofile(os.path.join(TMP_DIR, "test_clips_array.mp4"))
close_all_clips(locals())
@@ -46,7 +51,7 @@ def test_concatenate_self():
concatenated = concatenate_videoclips([clip])
- concatenated.write_videofile(join(TMP_DIR, "test_concatenate_self.mp4"))
+ concatenated.write_videofile(os.path.join(TMP_DIR, "test_concatenate_self.mp4"))
assert concatenated == target
@@ -60,5 +65,5 @@ def test_concatenate_floating_point():
"""
clip = ColorClip([100, 50], color=[255, 128, 64], duration=1.12).with_fps(25.0)
concat = concatenate_videoclips([clip])
- concat.write_videofile(join(TMP_DIR, "concat.mp4"), preset="ultrafast")
+ concat.write_videofile(os.path.join(TMP_DIR, "concat.mp4"), preset="ultrafast")
close_all_clips(locals())
diff --git a/tests/test_examples.py b/tests/test_examples.py
index 140aa5a6..dfe4da0e 100644
--- a/tests/test_examples.py
+++ b/tests/test_examples.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import os
import numpy as np
diff --git a/tests/test_ffmpeg_reader.py b/tests/test_ffmpeg_reader.py
index 89bab5d4..f509bae7 100644
--- a/tests/test_ffmpeg_reader.py
+++ b/tests/test_ffmpeg_reader.py
@@ -1,5 +1,5 @@
-# -*- coding: utf-8 -*-
"""FFmpeg reader tests meant to be run with pytest."""
+
import pytest
import numpy as np
@@ -99,14 +99,14 @@ def test_large_skip_frame_pos():
assert reader.fps == 24
# 10 sec * 24 fps = 240 frames
- frame = reader.get_frame(240 // 24)
+ reader.get_frame(240 // 24)
assert reader.pos == 241
- frame2 = reader.get_frame(719 / 24)
+ reader.get_frame(719 / 24)
assert reader.pos == 720
# Go backwards
- backwards_frame = reader.get_frame(120 // 24)
+ reader.get_frame(120 // 24)
assert reader.pos == 121
diff --git a/tests/test_fx.py b/tests/test_fx.py
index d20f3df7..a8dfda3d 100644
--- a/tests/test_fx.py
+++ b/tests/test_fx.py
@@ -10,7 +10,6 @@ from moviepy.audio.fx import multiply_stereo_volume
from moviepy.utils import close_all_clips
from moviepy.video.fx import (
blackwhite,
- blink,
colorx,
crop,
even_size,
@@ -579,5 +578,4 @@ def test_multiply_stereo_volume():
if __name__ == "__main__":
- # pytest.main()
- test_loop()
+ pytest.main()
diff --git a/tests/test_helper.py b/tests/test_helper.py
index 757f5af6..f204fc77 100644
--- a/tests/test_helper.py
+++ b/tests/test_helper.py
@@ -1,6 +1,5 @@
-# -*- coding: utf-8 -*-
"""Define general test helper attributes and utilities."""
-import os
+
import sys
import tempfile
@@ -10,9 +9,9 @@ TMP_DIR = tempfile.gettempdir() # because tempfile.tempdir is sometimes None
# Arbitrary font used in caption testing.
if sys.platform in ("win32", "cygwin"):
FONT = "Arial"
- # Even if Windows users install the Liberation fonts, it is called LiberationMono on Windows, so
- # it doesn't help.
+ # Even if Windows users install the Liberation fonts, it is called
+ # LiberationMono on Windows, so it doesn't help.
else:
FONT = (
- "Liberation-Mono" # This is available in the fonts-liberation package on Linux.
+ "Liberation-Mono" # This is available in the fonts-liberation package on Linux
)
diff --git a/tests/test_issues.py b/tests/test_issues.py
index 44b21a86..35d097cd 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -1,12 +1,17 @@
-# -*- coding: utf-8 -*-
"""Issue tests meant to be run with pytest."""
+
import pytest
import os
-from moviepy import *
-from moviepy.utils import close_all_clips
+from moviepy.video.VideoClip import ColorClip, ImageClip, VideoClip
+from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
+from moviepy.video.compositing.concatenate import concatenate_videoclips
+from moviepy.video.compositing.transitions import crossfadein, crossfadeout
from moviepy.video.fx.blink import blink
from moviepy.video.fx.resize import resize
+from moviepy.audio.io.AudioFileClip import AudioFileClip
+from moviepy.video.io.VideoFileClip import VideoFileClip
+from moviepy.utils import close_all_clips
from tests.test_helper import TMP_DIR
@@ -228,7 +233,7 @@ def test_issue_334():
tt = VideoFileClip("media/big_buck_bunny_0_30.webm").subclip(0, 3)
# TODO: Setting mask here does not work:
# .with_mask(maskclip).resize(size)])
- final = CompositeVideoClip([tt, concatenated.with_position(posi).resize(size)])
+ final = CompositeVideoClip([tt, concatenated.with_position(posi).fx(resize, size)])
final.duration = tt.duration
final.write_videofile(os.path.join(TMP_DIR, "issue_334.mp4"), fps=10)
@@ -247,7 +252,7 @@ def test_issue_354():
# align='South-East')
# caption.duration = clip.duration
- fadecaption = clip.crossfadein(crosstime).crossfadeout(crosstime)
+ fadecaption = clip.fx(crossfadein, crosstime).fx(crossfadeout, crosstime)
CompositeVideoClip([clip, fadecaption]).close()
@@ -259,7 +264,6 @@ def test_issue_359():
def test_issue_368():
import numpy as np
- import matplotlib
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_moons
diff --git a/tests/test_misc.py b/tests/test_misc.py
index 4648dad5..958e5eb1 100644
--- a/tests/test_misc.py
+++ b/tests/test_misc.py
@@ -2,7 +2,8 @@ import os
import pytest
-import moviepy.video.tools.cuts as cuts
+from moviepy.video.tools.cuts import find_video_period
+from moviepy.video.fx.resize import resize
from moviepy.utils import close_all_clips
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
from moviepy.video.compositing.concatenate import concatenate_videoclips
@@ -28,8 +29,8 @@ MEDIA_SUBTITLES_UNICODE_DATA = [
def test_cuts1():
- clip = VideoFileClip("media/big_buck_bunny_432_433.webm").resize(0.2)
- cuts.find_video_period(clip) == pytest.approx(0.966666666667, 0.0001)
+ clip = VideoFileClip("media/big_buck_bunny_432_433.webm").fx(resize, 0.2)
+ find_video_period(clip) == pytest.approx(0.966666666667, 0.0001)
close_all_clips(locals())
diff --git a/tests/test_resourcerelease.py b/tests/test_resourcerelease.py
index f70c087d..07c18a32 100644
--- a/tests/test_resourcerelease.py
+++ b/tests/test_resourcerelease.py
@@ -1,15 +1,13 @@
-# -*- coding: utf-8 -*-
+"""
+Tool tests meant to be run with pytest.
+
+Testing whether issue #596 has been repaired.
+Note: Platform dependent test. Will only fail on Windows > NT.
"""
- Tool tests meant to be run with pytest.
-
- Testing whether issue #596 has been repaired.
-
- Note: Platform dependent test. Will only fail on Windows > NT. """
+import os
import time
-from os import remove
-from os.path import join
from moviepy.video.compositing.CompositeVideoClip import clips_array
from moviepy.video.io.VideoFileClip import VideoFileClip
@@ -29,7 +27,7 @@ def test_release_of_file_via_close():
# Repeat this so we can see no conflicts.
for i in range(3):
# Get the name of a temporary file we can use.
- local_video_filename = join(
+ local_video_filename = os.path.join(
TMP_DIR, "test_release_of_file_via_close_%s.mp4" % int(time.time())
)
@@ -45,7 +43,7 @@ def test_release_of_file_via_close():
# This would fail on Windows if the file is still locked.
# This should succeed without exceptions.
- remove(local_video_filename)
+ os.remove(local_video_filename)
red.close()
green.close()
diff --git a/tests/test_resourcereleasedemo.py b/tests/test_resourcereleasedemo.py
index c61288c5..f3c24f7b 100644
--- a/tests/test_resourcereleasedemo.py
+++ b/tests/test_resourcereleasedemo.py
@@ -1,30 +1,25 @@
-# -*- coding: utf-8 -*-
+"""
+Tool tests meant to be run with pytest.
+
+Demonstrates issue #596 exists.
+Note: Platform dependent test. Will only fail on Windows > NT.
"""
- Tool tests meant to be run with pytest.
-
- Demonstrates issue #596 exists.
-
- Note: Platform dependent test. Will only fail on Windows > NT. """
+import os
import time
-from os import remove
-from os.path import join
from moviepy.video.compositing.CompositeVideoClip import clips_array
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.VideoClip import ColorClip
-# from tempfile import NamedTemporaryFile
from tests.test_helper import TMP_DIR
-# import pytest
-
def test_failure_to_release_file():
"""This isn't really a test, because it is expected to fail.
- It demonstrates that there *is* a problem with not releasing resources when running on
- Windows.
+ It demonstrates that there *is* a problem with not releasing resources when
+ running on Windows.
The real issue was that, as of movepy 0.2.3.2, there was no way around it.
@@ -32,7 +27,7 @@ def test_failure_to_release_file():
"""
# Get the name of a temporary file we can use.
- local_video_filename = join(
+ local_video_filename = os.path.join(
TMP_DIR, "test_release_of_file_%s.mp4" % int(time.time())
)
@@ -66,7 +61,7 @@ def test_failure_to_release_file():
"On Windows, this succeeds the first few times around the loop"
" but eventually fails."
)
- print("Need to shut down the process now. No more tests in" "this file.")
+ print("Need to shut down the process now. No more tests in this file.")
return
try:
@@ -76,7 +71,7 @@ def test_failure_to_release_file():
# In particular, this raises an exception with PermissionError.
# In there was no way to avoid it.
- remove(local_video_filename)
+ os.remove(local_video_filename)
print("You are not running Windows, because that worked.")
except OSError: # More specifically, PermissionError in Python 3.
print("Yes, on Windows this fails.")
diff --git a/tests/test_tools.py b/tests/test_tools.py
index 2e9b0187..b0bef70a 100644
--- a/tests/test_tools.py
+++ b/tests/test_tools.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Tool tests meant to be run with pytest. Taken from PR #121 (grimley517)."""
-import sys
import pytest
@@ -38,7 +36,9 @@ def test_find_extensions_not_found():
],
)
def test_cvsecs(given, expected):
- """Test the convert_to_seconds funtion outputs correct times as per the docstring."""
+ """Test the convert_to_seconds funtion outputs correct times as per
+ the docstring.
+ """
assert tools.convert_to_seconds(given) == expected
diff --git a/tests/test_videotools.py b/tests/test_videotools.py
index 80e8a1b2..6dd6ca83 100644
--- a/tests/test_videotools.py
+++ b/tests/test_videotools.py
@@ -1,5 +1,5 @@
-# -*- coding: utf-8 -*-
"""Video file clip tests meant to be run with pytest."""
+
import os
from moviepy.video.compositing.concatenate import concatenate_videoclips