Video editing with Python
Apply black formatting
osaajani59e0f8bac10b
diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex f39a774c..ace99a9f 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -185,7 +185,7 @@ class Clip:keep_duration=keep_duration,)- def with_effects(self, effects: List['Effect']):+ def with_effects(self, effects: List["Effect"]):"""Return a copy of the current clip with the effects applied>>> new_clip = clip.with_effects([vfx.Resize(0.2, method="bilinear")])@@ -195,14 +195,14 @@ class Clip:>>> clip.with_effects([afx.VolumeX(0.5), vfx.Resize(0.3), vfx.Mirrorx()])"""new_clip = self.copy()- for effect in effects :+ for effect in effects:# We always copy effect before using it, see Effect.copy# to see why we need toeffect_copy = effect.copy()new_clip = effect_copy.apply(new_clip)return new_clip-+@apply_to_mask@apply_to_audio@convert_parameter_to_seconds(["t"])@@ -292,7 +292,6 @@ class Clip:raise ValueError("Cannot change clip start when new duration is None")self.start = self.end - duration-@outplacedef with_make_frame(self, make_frame):"""Sets a ``make_frame`` attribute for the clip. Useful for setting@@ -458,21 +457,26 @@ class Clip:return new_clip.with_duration(self.duration - (end_time - start_time))else: # pragma: no coverreturn new_clip-- def with_multiply_speed(self, factor: float = None, final_duration: float = None) :++ def with_multiply_speed(self, factor: float = None, final_duration: float = None):"""Returns a clip playing the current clip but at a speed multiplied by ``factor``.For info on the parameters, please see ``vfx.MultiplySpeed``"""from moviepy.video.fx.MultiplySpeed import MultiplySpeed- return self.with_effects([MultiplySpeed(factor=factor, final_duration=final_duration)])-- def with_multiply_volume(self, factor: float, start_time = None, end_time = None) :- """Returns a new clip with audio volume multiplied by the value `factor`.++ return self.with_effects(+ [MultiplySpeed(factor=factor, final_duration=final_duration)]+ )++ def with_multiply_volume(self, factor: float, start_time=None, end_time=None):+ """Returns a new clip with audio volume multiplied by the value `factor`.For info on the parameters, please see ``afx.MultiplyVolume``"""from moviepy.audio.fx.MultiplyVolume import MultiplyVolume- return self.with_effects([MultiplyVolume(factor=factor, start_time=start_time,- end_time=end_time)])++ return self.with_effects(+ [MultiplyVolume(factor=factor, start_time=start_time, end_time=end_time)]+ )@requires_duration@use_clip_fps_by_default@@ -557,7 +561,6 @@ class Clip:else:return (t >= self.start) and ((self.end is None) or (t < self.end))-def close(self):"""Release any resources that are in use."""# Implementation note for subclasses:diff --git a/moviepy/Effect.py b/moviepy/Effect.pyindex 33c6c602..9cdb2dcd 100644--- a/moviepy/Effect.py+++ b/moviepy/Effect.py@@ -1,11 +1,11 @@-from abc import ABCMeta, abstractmethodfrom moviepy.Clip import Clipimport copy as _copy+class Effect(metaclass=ABCMeta):"""Base abastract class for all effects in MoviePy.- Any new effect have to extend this base class.+ Any new effect have to extend this base class."""def copy(self):@@ -14,7 +14,7 @@ class Effect(metaclass=ABCMeta):You must *always* copy an ``Effect`` before applying,because some of them will modify their own attributes when applied.For example, setting a previously unset property by using target clip property.-+If we was to use the original effect, calling the same effect multiple timescould lead to different properties, and different results for equivalent clips.@@ -24,7 +24,6 @@ class Effect(metaclass=ABCMeta):In a way, copy make the effect himself beeing kind of indempotent."""return _copy.copy(self)-@abstractmethoddef apply(self, clip: Clip) -> Clip:"""Apply the current effect on a clip@@ -34,6 +33,6 @@ class Effect(metaclass=ABCMeta):clipThe target clip to apply the effect on.(Internally, MoviePy will always pass a copy of the original clip)-+"""- pass\ No newline at end of file+ passdiff --git a/moviepy/__init__.py b/moviepy/__init__.pyindex 989fceaf..45acfc4c 100644--- a/moviepy/__init__.py+++ b/moviepy/__init__.py@@ -13,7 +13,11 @@ from moviepy.audio.io.AudioFileClip import AudioFileClipfrom moviepy.tools import convert_to_secondsfrom moviepy.version import __version__from moviepy.video import fx as vfx, tools as videotools-from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip, clips_array, concatenate_videoclips+from moviepy.video.compositing.CompositeVideoClip import (+ CompositeVideoClip,+ clips_array,+ concatenate_videoclips,+)from moviepy.video.io import ffmpeg_toolsfrom moviepy.video.io.display_in_notebook import display_in_notebookfrom moviepy.video.io.ImageSequenceClip import ImageSequenceClipdiff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex cef6f878..43e61c3c 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -265,15 +265,10 @@ class AudioClip(Clip):ffmpeg_params=ffmpeg_params,logger=logger,)-+@requires_durationdef audiopreview(- self,- fps=None,- buffersize=2000,- nbytes=2,- audio_flag=None,- video_flag=None+ self, fps=None, buffersize=2000, nbytes=2, audio_flag=None, video_flag=None):"""Preview an AudioClip using ffplay@@ -301,7 +296,14 @@ class AudioClip(Clip):Instances of class threading events that are used to synchronizevideo and audio during ``VideoClip.preview()``."""- ffplay_audiopreview(clip=self, fps=fps, buffersize=buffersize, nbytes=nbytes, audio_flag=audio_flag, video_flag=video_flag)+ ffplay_audiopreview(+ clip=self,+ fps=fps,+ buffersize=buffersize,+ nbytes=nbytes,+ audio_flag=audio_flag,+ video_flag=video_flag,+ )def __add__(self, other):if isinstance(other, AudioClip):diff --git a/moviepy/audio/__init__.py b/moviepy/audio/__init__.pyindex a171db6d..9a438400 100644--- a/moviepy/audio/__init__.py+++ b/moviepy/audio/__init__.py@@ -1 +1 @@-"""Everything about audio manipulation."""\ No newline at end of file+"""Everything about audio manipulation."""diff --git a/moviepy/audio/fx/AudioDelay.py b/moviepy/audio/fx/AudioDelay.pyindex 3e9d0498..691fe5db 100644--- a/moviepy/audio/fx/AudioDelay.py+++ b/moviepy/audio/fx/AudioDelay.py@@ -8,8 +8,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class AudioDelay(Effect) :+class AudioDelay(Effect):"""Repeats audio certain number of times at constant intervals multiplyingtheir volume levels using a linear space in the range 1 to ``decay`` argumentvalue.@@ -49,7 +50,7 @@ class AudioDelay(Effect) :offset: float = 0.2n_repeats: int = 8decay: float = 1-+@audio_video_effectdef apply(self, clip: Clip) -> Clip:decayments = np.linspace(1, max(0, self.decay), self.n_repeats + 1)@@ -57,7 +58,9 @@ class AudioDelay(Effect) :[clip.copy(),*[- clip.with_start((rep + 1) * self.offset).with_effects([MultiplyVolume(decayments[rep + 1])])+ clip.with_start((rep + 1) * self.offset).with_effects(+ [MultiplyVolume(decayments[rep + 1])]+ )for rep in range(self.n_repeats)],]diff --git a/moviepy/audio/fx/AudioFadeIn.py b/moviepy/audio/fx/AudioFadeIn.pyindex 1b8735c9..5b5f1e74 100644--- a/moviepy/audio/fx/AudioFadeIn.py+++ b/moviepy/audio/fx/AudioFadeIn.py@@ -7,8 +7,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class AudioFadeIn(Effect) :+class AudioFadeIn(Effect):"""Return an audio (or video) clip that is first mute, then thesound arrives progressively over ``duration`` seconds.@@ -27,24 +28,21 @@ class AudioFadeIn(Effect) :duration: float- def __post_init__ (self) :+ def __post_init__(self):self.duration = convert_to_seconds(self.duration)-def _mono_factor_getter(self):return lambda t, duration: np.minimum(t / duration, 1)-def _stereo_factor_getter(self, nchannels):def getter(t, duration):factor = np.minimum(t / duration, 1)return np.array([factor for _ in range(nchannels)]).Treturn getter-@audio_video_effect- def apply(self, clip: Clip) -> Clip:+ def apply(self, clip: Clip) -> Clip:if clip.duration is None:raise ValueError("Attribute 'duration' not set")diff --git a/moviepy/audio/fx/AudioFadeOut.py b/moviepy/audio/fx/AudioFadeOut.pyindex 325b9f87..8dcd524a 100644--- a/moviepy/audio/fx/AudioFadeOut.py+++ b/moviepy/audio/fx/AudioFadeOut.py@@ -7,8 +7,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class AudioFadeOut(Effect) :+class AudioFadeOut(Effect):"""Return a sound clip where the sound fades out progressivelyover ``duration`` seconds at the end of the clip.@@ -28,14 +29,12 @@ class AudioFadeOut(Effect) :duration: float- def __post_init__ (self) :+ def __post_init__(self):self.duration = convert_to_seconds(self.duration)-def _mono_factor_getter(self, clip_duration):return lambda t, duration: np.minimum(1.0 * (clip_duration - t) / duration, 1)-def _stereo_factor_getter(self, clip_duration, nchannels):def getter(t, duration):factor = np.minimum(1.0 * (clip_duration - t) / duration, 1)@@ -43,7 +42,6 @@ class AudioFadeOut(Effect) :return getter-@audio_video_effectdef apply(self, clip: Clip) -> Clip:if clip.duration is None:diff --git a/moviepy/audio/fx/AudioLoop.py b/moviepy/audio/fx/AudioLoop.pyindex f67caddb..2de9169c 100644--- a/moviepy/audio/fx/AudioLoop.py+++ b/moviepy/audio/fx/AudioLoop.py@@ -5,8 +5,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class AudioLoop(Effect) :+class AudioLoop(Effect):"""Loops over an audio clip.Returns an audio clip that plays the given clip either@@ -30,6 +31,8 @@ class AudioLoop(Effect) :def apply(self, clip: Clip) -> Clip:if self.duration is not None:self.n_loops = int(self.duration / clip.duration) + 1- return concatenate_audioclips(self.n_loops * [clip]).with_duration(self.duration)+ return concatenate_audioclips(self.n_loops * [clip]).with_duration(+ self.duration+ )return concatenate_audioclips(self.n_loops * [clip])diff --git a/moviepy/audio/fx/AudioNormalize.py b/moviepy/audio/fx/AudioNormalize.pyindex 77039afe..e6e03c2d 100644--- a/moviepy/audio/fx/AudioNormalize.py+++ b/moviepy/audio/fx/AudioNormalize.py@@ -5,8 +5,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class AudioNormalize(Effect) :+class AudioNormalize(Effect):"""Return a clip whose volume is normalized to 0db.Return an audio (or video) clip whose audio volume is normalized@@ -19,7 +20,7 @@ class AudioNormalize(Effect) :>>> videoclip = VideoFileClip('myvideo.mp4').with_effects([afx.AudioNormalize()])"""-+@audio_video_effectdef apply(self, clip: Clip) -> Clip:max_volume = clip.max_volume()diff --git a/moviepy/audio/fx/MultiplyStereoVolume.py b/moviepy/audio/fx/MultiplyStereoVolume.pyindex c1789f16..022447ef 100644--- a/moviepy/audio/fx/MultiplyStereoVolume.py+++ b/moviepy/audio/fx/MultiplyStereoVolume.py@@ -4,8 +4,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class MultiplyStereoVolume(Effect) :+class MultiplyStereoVolume(Effect):"""For a stereo audioclip, this function enables to change the volumeof the left and right channel separately (with the factors `left`and `right`). Makes a stereo audio clip in which the volume of left@@ -25,7 +26,6 @@ class MultiplyStereoVolume(Effect) :@audio_video_effectdef apply(self, clip: Clip) -> Clip:-def stereo_volume(get_frame, t):frame = get_frame(t)if len(frame) == 1: # monodiff --git a/moviepy/audio/fx/MultiplyVolume.py b/moviepy/audio/fx/MultiplyVolume.pyindex d273fdc1..f8519f0f 100644--- a/moviepy/audio/fx/MultiplyVolume.py+++ b/moviepy/audio/fx/MultiplyVolume.py@@ -7,8 +7,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class MultiplyVolume(Effect) :+class MultiplyVolume(Effect):"""Returns a clip with audio volume multiplied by thevalue `factor`. Can be applied to both audio and video clips.@@ -43,14 +44,13 @@ class MultiplyVolume(Effect) :start_time: float = Noneend_time: float = None- def __post_init__ (self) :+ def __post_init__(self):if self.start_time is not None:self.start_time = convert_to_seconds(self.start_time)if self.end_time is not None:self.end_time = convert_to_seconds(self.end_time)-def _multiply_volume_in_range(self, factor, start_time, end_time, nchannels):def factors_filter(factor, t):return np.array([factor if start_time <= t_ <= end_time else 1 for t_ in t])@@ -66,7 +66,6 @@ class MultiplyVolume(Effect) :return multiply_mono_volume if nchannels == 1 else multiply_stereo_volume-@audio_video_effectdef apply(self, clip: Clip) -> Clip:if self.start_time is None and self.end_time is None:@@ -83,4 +82,4 @@ class MultiplyVolume(Effect) :clip.nchannels,),keep_duration=True,- )\ No newline at end of file+ )diff --git a/moviepy/audio/io/ffplay_audiopreviewer.py b/moviepy/audio/io/ffplay_audiopreviewer.pyindex 0ecd2aaf..62666128 100644--- a/moviepy/audio/io/ffplay_audiopreviewer.py+++ b/moviepy/audio/io/ffplay_audiopreviewer.py@@ -33,12 +33,11 @@ class FFPLAY_AudioPreviewer:nbytes=2,nchannels=2,):-# order is importantcmd = [FFPLAY_BINARY,- "-autoexit", # If you dont precise, ffplay dont stop at end- "-nodisp", # If you dont precise a window is+ "-autoexit", # If you dont precise, ffplay dont stop at end+ "-nodisp", # If you dont precise a window is"-f","s%dle" % (8 * nbytes),"-ar",@@ -56,7 +55,7 @@ class FFPLAY_AudioPreviewer:self.proc = sp.Popen(cmd, **popen_params)def write_frames(self, frames_array):- """ Send a raw audio frame (a chunck of audio) to ffplay to be played"""+ """Send a raw audio frame (a chunck of audio) to ffplay to be played"""try:self.proc.stdin.write(frames_array.tobytes())except IOError as err:@@ -103,12 +102,7 @@ class FFPLAY_AudioPreviewer:@requires_durationdef ffplay_audiopreview(- clip,- fps=None,- buffersize=2000,- nbytes=2,- audio_flag=None,- video_flag=None+ clip, fps=None, buffersize=2000, nbytes=2, audio_flag=None, video_flag=None):"""A function that wraps the FFPLAY_AudioPreviewer to preview an AudioClip@@ -142,25 +136,19 @@ def ffplay_audiopreview(else:fps = clip.fps- with FFPLAY_AudioPreviewer(- fps,- nbytes,- clip.nchannels- ) as previewer:--+ with FFPLAY_AudioPreviewer(fps, nbytes, clip.nchannels) as previewer:first_frame = Truefor chunk in clip.iter_chunks(chunksize=buffersize, quantize=True, nbytes=nbytes, fps=fps):# On first frame, wait for video- if first_frame :+ if first_frame:first_frame = False-- if audio_flag is not None:- audio_flag.set() # Say to video that audio is ready++ if audio_flag is not None:+ audio_flag.set() # Say to video that audio is readyif video_flag is not None:- video_flag.wait() # Wait for video to be ready+ video_flag.wait() # Wait for video to be ready- previewer.write_frames(chunk)\ No newline at end of file+ previewer.write_frames(chunk)diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex a25bbbde..6173616a 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -148,7 +148,7 @@ class FFMPEG_AudioReader:Parameters:------------chunksize (float): The desired number of audio frames to read.-+"""# chunksize is not being autoconverted from float to intchunksize = int(round(chunksize))diff --git a/moviepy/config.py b/moviepy/config.pyindex d93b3b5e..61c0b2b5 100644--- a/moviepy/config.py+++ b/moviepy/config.py@@ -56,7 +56,7 @@ else:raise IOError(f"{err} - The path specified for the ffmpeg binary might be wrong")-+if FFPLAY_BINARY == "auto-detect":if try_cmd(["ffplay"])[0]:diff --git a/moviepy/tools.py b/moviepy/tools.pyindex 0b75c943..b771103d 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -193,7 +193,7 @@ def close_all_clips(objects="globals", types=("audio", "video", "image")):from moviepy.audio.io.AudioFileClip import AudioFileClipfrom moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.VideoClip import ImageClip-+CLIP_TYPES = {"audio": AudioFileClip,"video": VideoFileClip,diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 52c162fd..f74f300b 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -69,9 +69,9 @@ class VideoClip(Clip):durationhas_constant_size- Define if clip size is constant or if it may vary with time. Default+ Define if clip size is constant or if it may vary with time. Defaultto True-+Attributes@@ -526,7 +526,6 @@ class VideoClip(Clip):logger=logger,)-# ===============================================================# PREVIEW OPERATIONS@@ -566,20 +565,14 @@ class VideoClip(Clip):# clip = CompositeVideoClip([self.with_position((0, 0))])frame = clip.get_frame(t)- pil_img = Image.fromarray(frame.astype('uint8'))+ pil_img = Image.fromarray(frame.astype("uint8"))pil_img.show()-@requires_duration@convert_masks_to_RGBdef preview(- self,- fps=15,- audio=True,- audio_fps=22050,- audio_buffersize=3000,- audio_nbytes=2+ self, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000, audio_nbytes=2):"""Displays the clip in a window, at the given frames per second (of movie)@@ -630,18 +623,27 @@ class VideoClip(Clip):# launch the threadaudiothread = threading.Thread(target=self.audio.audiopreview,- args=(audio_fps, audio_buffersize, audio_nbytes, audio_flag, video_flag),+ args=(+ audio_fps,+ audio_buffersize,+ audio_nbytes,+ audio_flag,+ video_flag,+ ),)audiothread.start()# passthrough to ffmpeg, passing flag for ffmpeg to set- ffplay_preview_video(clip=self, fps=fps, audio_flag=audio_flag, video_flag=video_flag)-+ ffplay_preview_video(+ clip=self, fps=fps, audio_flag=audio_flag, video_flag=video_flag+ )# -----------------------------------------------------------------# F I L T E R I N G- def with_sub_effects(self, effects: List['Effect'], start_time=0, end_time=None, **kwargs):+ def with_sub_effects(+ self, effects: List["Effect"], start_time=0, end_time=None, **kwargs+ ):"""Apply a transformation to a part of the clip.Returns a new clip in which the function ``fun`` (clip->clip)@@ -667,7 +669,6 @@ class VideoClip(Clip):return concatenate_videoclips(clips).with_start(self.start)-# IMAGE FILTERSdef image_transform(self, image_func, apply_to=None):@@ -693,7 +694,7 @@ class VideoClip(Clip):------------pre_array (numpy.ndarray)The original array to be filled.-+shape (tuple)The desired shape of the resulting array.@@ -940,33 +941,77 @@ class VideoClip(Clip):"""Returns a video clip that is a resized version of the clip.For info on the parameters, please see ``vfx.Resize``"""- return self.with_effects([Resize(new_size=new_size, height=height,- width=width, apply_to_mask=apply_to_mask)])-- def rotated(self, angle: float, unit: str = "deg", resample: str = "bicubic",- expand: bool = False, center: tuple = None, translate: tuple = None,- bg_color: tuple = None) :+ return self.with_effects(+ [+ Resize(+ new_size=new_size,+ height=height,+ width=width,+ apply_to_mask=apply_to_mask,+ )+ ]+ )++ def rotated(+ self,+ angle: float,+ unit: str = "deg",+ resample: str = "bicubic",+ expand: bool = False,+ center: tuple = None,+ translate: tuple = None,+ bg_color: tuple = None,+ ):"""Rotates the specified clip by ``angle`` degrees (or radians) anticlockwiseIf the angle is not a multiple of 90 (degrees) or ``center``, ``translate``,and ``bg_color`` are not ``None``.For info on the parameters, please see ``vfx.Rotate``"""- return self.with_effects([Rotate(angle=angle, unit=unit, resample=resample,- expand=expand, center=center, translate=translate,- bg_color=bg_color)])+ return self.with_effects(+ [+ Rotate(+ angle=angle,+ unit=unit,+ resample=resample,+ expand=expand,+ center=center,+ translate=translate,+ bg_color=bg_color,+ )+ ]+ )- def cropped(self, x1: int = None, y1: int = None, x2: int = None, y2: int = None,- width: int = None, height: int = None, x_center: int = None,- y_center: int = None) :+ def cropped(+ self,+ x1: int = None,+ y1: int = None,+ x2: int = None,+ y2: int = None,+ width: int = None,+ height: int = None,+ x_center: int = None,+ y_center: int = None,+ ):"""Returns a new clip in which just a rectangular subregion of theoriginal clip is conserved. x1,y1 indicates the top left corner andx2,y2 is the lower right corner of the croped region.All coordinates are in pixels. Float numbers are accepted.For info on the parameters, please see ``vfx.Crop``"""- return self.with_effects([Crop(x1=x1, y1=y1, x2=x2, y2=y2,- width=width, height=height, x_center=x_center, y_center=y_center)])-+ return self.with_effects(+ [+ Crop(+ x1=x1,+ y1=y1,+ x2=x2,+ y2=y2,+ width=width,+ height=height,+ x_center=x_center,+ y_center=y_center,+ )+ ]+ )# --------------------------------------------------------------# CONVERSIONS TO OTHER TYPES@@ -1016,7 +1061,9 @@ class VideoClip(Clip):def __add__(self, other):if isinstance(other, VideoClip):- from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips+ from moviepy.video.compositing.CompositeVideoClip import (+ concatenate_videoclips,+ )method = "chain" if self.size == other.size else "compose"return concatenate_videoclips([self, other], method=method)@@ -1046,19 +1093,20 @@ class VideoClip(Clip):def __matmul__(self, n):"""- Implement matrice multiplication (self @ other) to rotate a video- by other degrees+ Implement matrice multiplication (self @ other) to rotate a video+ by other degrees"""if not isinstance(n, Real):return NotImplemented-+from moviepy.video.fx.Rotate import Rotate+return self.with_effects([Rotate(n)])def __and__(self, mask):"""- Implement the and (self & other) to produce a video with other- used as a mask for self.+ Implement the and (self & other) to produce a video with other+ used as a mask for self."""return self.with_mask(mask)@@ -1193,7 +1241,7 @@ class ImageClip(VideoClip):if not isinstance(img, np.ndarray):# img is a string or path-like object, so read it in from disk- img = imread_v2(img) # We use v2 imread cause v3 fail with gif+ img = imread_v2(img) # We use v2 imread cause v3 fail with gifif len(img.shape) == 3: # img is (now) a RGB(a) numpy arrayif img.shape[2] == 4:@@ -1314,280 +1362,410 @@ class ColorClip(ImageClip):class TextClip(ImageClip):- """Class for autogenerated text clips.+ """Class for autogenerated text clips.- Creates an ImageClip originating from a script-generated text image.+ Creates an ImageClip originating from a script-generated text image.- Parameters- ----------+ Parameters+ ----------- font- Path to the font to use. Must be an OpenType font.- See ``TextClip.list('font')`` for the list of fonts you can use on- your computer.+ font+ Path to the font to use. Must be an OpenType font.+ See ``TextClip.list('font')`` for the list of fonts you can use on+ your computer.- text- A string of the text to write. Can be replaced by argument- ``filename``.+ text+ A string of the text to write. Can be replaced by argument+ ``filename``.- filename- The name of a file in which there is the text to write,- as a string or a path-like object.- Can be provided instead of argument ``text``+ filename+ The name of a file in which there is the text to write,+ as a string or a path-like object.+ Can be provided instead of argument ``text``- font_size- Font size in point. Can be auto-set if method='caption',- or if method='label' and size is set.+ font_size+ Font size in point. Can be auto-set if method='caption',+ or if method='label' and size is set.- size- Size of the picture in pixels. Can be auto-set if- method='label' and font_size is set, but mandatory if method='caption'.- the height can be None for caption if font_size is defined,- it will then be auto-determined.+ size+ Size of the picture in pixels. Can be auto-set if+ method='label' and font_size is set, but mandatory if method='caption'.+ the height can be None for caption if font_size is defined,+ it will then be auto-determined.- bg_color- Color of the background. Default to None for no background. Can be- a RGB (or RGBA if transparent = ``True``) ``tuple``, a color name, or an- hexadecimal notation.+ bg_color+ Color of the background. Default to None for no background. Can be+ a RGB (or RGBA if transparent = ``True``) ``tuple``, a color name, or an+ hexadecimal notation.- color- Color of the text. Default to "black". Can be- a RGB (or RGBA if transparent = ``True``) ``tuple``, a color name, or an- hexadecimal notation.+ color+ Color of the text. Default to "black". Can be+ a RGB (or RGBA if transparent = ``True``) ``tuple``, a color name, or an+ hexadecimal notation.-- stroke_color- Color of the stroke (=contour line) of the text. If ``None``,- there will be no stroke.- stroke_width- Width of the stroke, in pixels. Can be a float, like 1.5.+ stroke_color+ Color of the stroke (=contour line) of the text. If ``None``,+ there will be no stroke.- method- Either 'label' (default, the picture will be autosized so as to fit- exactly the size) or 'caption' (the text will be drawn in a picture- with fixed size provided with the ``size`` argument). If `caption`,- the text will be wrapped automagically.+ stroke_width+ Width of the stroke, in pixels. Can be a float, like 1.5.- text_align- center | left | right. Text align similar to css. Default to ``left``.+ method+ Either 'label' (default, the picture will be autosized so as to fit+ exactly the size) or 'caption' (the text will be drawn in a picture+ with fixed size provided with the ``size`` argument). If `caption`,+ the text will be wrapped automagically.- horizontal_align- center | left | right. Define horizontal align of text bloc in image.- Default to ``center``.+ text_align+ center | left | right. Text align similar to css. Default to ``left``.- vertical_align- center | top | bottom. Define vertical align of text bloc in image.- Default to ``center``.+ horizontal_align+ center | left | right. Define horizontal align of text bloc in image.+ Default to ``center``.- interline- Interline spacing. Default to ``4``.+ vertical_align+ center | top | bottom. Define vertical align of text bloc in image.+ Default to ``center``.- transparent- ``True`` (default) if you want to take into account the- transparency in the image.+ interline+ Interline spacing. Default to ``4``.- duration- Duration of the clip- """+ transparent+ ``True`` (default) if you want to take into account the+ transparency in the image.- @convert_path_to_string("filename")- def __init__(- self,- font,- text=None,- filename=None,- font_size=None,- size=(None, None),- color="black",- bg_color=None,- stroke_color=None,- stroke_width=0,- method="label",- text_align="left",- horizontal_align="center",- vertical_align="center",- interline=4,- transparent=True,- duration=None- ):-- def break_text (width, text, font, font_size, stroke_width, align, spacing) -> List[str] :- """- Break text to never overflow a width- """- img = Image.new("RGB", (1, 1))- font_pil = ImageFont.truetype(font, font_size)- draw = ImageDraw.Draw(img)-- lines = []- current_line = ''- words = text.split(' ')- for word in words:- temp_line = (current_line + ' ' + word if current_line else word)- temp_left, temp_top, temp_right, temp_bottom = draw.multiline_textbbox((0,0), temp_line, font=font_pil, spacing=spacing,- align=align, stroke_width=stroke_width)- temp_width = temp_right - temp_left-- if temp_width <= width:- current_line = temp_line- else:- lines.append(current_line)- current_line = word-- if current_line :+ duration+ Duration of the clip+ """++ @convert_path_to_string("filename")+ def __init__(+ self,+ font,+ text=None,+ filename=None,+ font_size=None,+ size=(None, None),+ color="black",+ bg_color=None,+ stroke_color=None,+ stroke_width=0,+ method="label",+ text_align="left",+ horizontal_align="center",+ vertical_align="center",+ interline=4,+ transparent=True,+ duration=None,+ ):+ def break_text(+ width, text, font, font_size, stroke_width, align, spacing+ ) -> List[str]:+ """+ Break text to never overflow a width+ """+ img = Image.new("RGB", (1, 1))+ font_pil = ImageFont.truetype(font, font_size)+ draw = ImageDraw.Draw(img)++ lines = []+ current_line = ""+ words = text.split(" ")+ for word in words:+ temp_line = current_line + " " + word if current_line else word+ temp_left, temp_top, temp_right, temp_bottom = draw.multiline_textbbox(+ (0, 0),+ temp_line,+ font=font_pil,+ spacing=spacing,+ align=align,+ stroke_width=stroke_width,+ )+ temp_width = temp_right - temp_left++ if temp_width <= width:+ current_line = temp_line+ else:lines.append(current_line)+ current_line = word++ if current_line:+ lines.append(current_line)++ return lines++ def find_text_size(+ text,+ font,+ font_size,+ stroke_width,+ align,+ spacing,+ max_width=None,+ allow_break=False,+ ) -> tuple[int, int]:+ """+ Find dimensions a text will occupy+ return a tuple (width, height)+ """+ img = Image.new("RGB", (1, 1))+ font_pil = ImageFont.truetype(font, font_size)+ draw = ImageDraw.Draw(img)++ if max_width is None or not allow_break:+ left, top, right, bottom = draw.multiline_textbbox(+ (0, 0),+ text,+ font=font_pil,+ spacing=spacing,+ align=align,+ stroke_width=stroke_width,+ anchor="lm",+ )- return lines-- def find_text_size (text, font, font_size, stroke_width, align, spacing, max_width=None, allow_break=False) -> tuple[int, int] :- """- Find dimensions a text will occupy- return a tuple (width, height)- """- img = Image.new("RGB", (1, 1))- font_pil = ImageFont.truetype(font, font_size)- draw = ImageDraw.Draw(img)-- if max_width is None or not allow_break:- left, top, right, bottom = draw.multiline_textbbox((0,0), text, font=font_pil, spacing=spacing,- align=align, stroke_width=stroke_width, anchor="lm")-- return (int(right - left), int(bottom - top))-- lines = break_text(width=max_width, text=text, font=font, font_size=font_size, stroke_width=stroke_width,- align=align, spacing=spacing)-- left, top, right, bottom = draw.multiline_textbbox((0,0), "\n".join(lines), font=font_pil, spacing=spacing,- align=align, stroke_width=stroke_width, anchor="lm")-return (int(right - left), int(bottom - top))- def find_optimum_font_size (text, font, stroke_width, align, spacing, width, height=None, allow_break=False) :- """- Find the best font size to fit as optimally as possible- """- max_font_size = width- min_font_size = 1-- # Try find best size using bisection- while min_font_size < max_font_size:- avg_font_size = int((max_font_size + min_font_size) // 2)- text_width, text_height = find_text_size(text, font, avg_font_size, stroke_width, align, spacing,- max_width=width, allow_break=allow_break)-- if text_width <= width and (height is None or text_height <= height):- min_font_size = avg_font_size + 1- else:- max_font_size = avg_font_size - 1-- # Check if the last font size tested fits within the given width and height- text_width, text_height = find_text_size(text, font, min_font_size, stroke_width, align, spacing,- max_width=width, allow_break=allow_break)+ lines = break_text(+ width=max_width,+ text=text,+ font=font,+ font_size=font_size,+ stroke_width=stroke_width,+ align=align,+ spacing=spacing,+ )++ left, top, right, bottom = draw.multiline_textbbox(+ (0, 0),+ "\n".join(lines),+ font=font_pil,+ spacing=spacing,+ align=align,+ stroke_width=stroke_width,+ anchor="lm",+ )++ return (int(right - left), int(bottom - top))++ def find_optimum_font_size(+ text,+ font,+ stroke_width,+ align,+ spacing,+ width,+ height=None,+ allow_break=False,+ ):+ """+ Find the best font size to fit as optimally as possible+ """+ max_font_size = width+ min_font_size = 1++ # Try find best size using bisection+ while min_font_size < max_font_size:+ avg_font_size = int((max_font_size + min_font_size) // 2)+ text_width, text_height = find_text_size(+ text,+ font,+ avg_font_size,+ stroke_width,+ align,+ spacing,+ max_width=width,+ allow_break=allow_break,+ )+if text_width <= width and (height is None or text_height <= height):- return min_font_size+ min_font_size = avg_font_size + 1else:- return min_font_size - 1-- try :- print("f", font)- _ = ImageFont.truetype(font)- except Exception as e :- raise ValueError("Invalid font {}, pillow failed to use it with error {}".format(font, e))-- if filename:- with open(filename, 'r') as file:- text = file.read().rstrip() # Remove newline at end-- if text is None :- raise ValueError("No text nor filename provided")-- # Compute all img and text sizes if some are missing- img_width, img_height = size-- if method == "caption" :- if img_width is None :- raise ValueError("Size is mandatory when method is caption")-- if img_height is None and font_size is None :- raise ValueError("Height is mandatory when method is caption and font size is None")-- if font_size is None :- font_size = find_optimum_font_size(text=text, font=font, stroke_width=stroke_width, align=text_align,- spacing=interline, width=img_width, height=img_height, allow_break=True)-- if img_height is None :- img_height = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,- align=text_align, spacing=interline, max_width=img_width, allow_break=True)[1]-- # Add line breaks whenever needed- text = "\n".join(break_text(width=img_width, text=text, font=font, font_size=font_size, stroke_width=stroke_width,- align=text_align, spacing=interline))-- elif method == "label" :- if font_size is None and img_width is None :- raise ValueError("Font size is mandatory when method is label and size is None")-- if font_size is None :- font_size = find_optimum_font_size(text=text, font=font, stroke_width=stroke_width, align=text_align,- spacing=interline, width=img_width, height=img_height)-- if img_width is None :- img_width = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,- align=text_align, spacing=interline)[0]-- if img_height is None :- img_height = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,- align=text_align, spacing=interline, max_width=img_width)[1]-- else :- raise ValueError("Method must be either `caption` or `label`.")-- # Trace the image- img_mode = "RGBA" if transparent else "RGB"-- if bg_color is None and transparent :- bg_color = (0, 0, 0, 0)-- img = Image.new(img_mode, (img_width, img_height), color=bg_color)- pil_font = ImageFont.truetype(font, font_size)- draw = ImageDraw.Draw(img)+ max_font_size = avg_font_size - 1++ # Check if the last font size tested fits within the given width and height+ text_width, text_height = find_text_size(+ text,+ font,+ min_font_size,+ stroke_width,+ align,+ spacing,+ max_width=width,+ allow_break=allow_break,+ )+ if text_width <= width and (height is None or text_height <= height):+ return min_font_size+ else:+ return min_font_size - 1++ try:+ print("f", font)+ _ = ImageFont.truetype(font)+ except Exception as e:+ raise ValueError(+ "Invalid font {}, pillow failed to use it with error {}".format(font, e)+ )++ if filename:+ with open(filename, "r") as file:+ text = file.read().rstrip() # Remove newline at end- # Dont need allow break here, because we already breaked in caption- text_width, text_height = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,- align=text_align, spacing=interline, max_width=img_width)-- x = 0- if horizontal_align == "right" :- x = img_width - text_width- elif horizontal_align == "center" :- x = (img_width - text_width) / 2-- y = 0- if vertical_align == "bottom" :- y = img_height - text_height- elif vertical_align == "center" :- y = (img_height - text_height) / 2--- # So, pillow multiline support is horrible, in particular multiline_text and multiline_textbbox- # are not intuitive at all. They cannot use left top (see https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html)- # as anchor, so we always have to use left middle instead. Else we would always have a useless- # margin (the diff between ascender and top) on any text.- # That mean our Y is actually not from 0 for top, but need to be increment by half our text height,- # since we have to reference from middle line.- y += text_height / 2-- draw.multiline_text(xy=(x, y), text=text, fill=color, font=pil_font, spacing=interline, align=text_align, stroke_width=stroke_width,- stroke_fill=stroke_color, anchor="lm")-- # We just need the image as a numpy array- img_numpy = np.array(img)-- ImageClip.__init__(self, img=img_numpy, transparent=transparent, duration=duration)- self.text = text- self.color = color- self.stroke_color = stroke_color+ if text is None:+ raise ValueError("No text nor filename provided")++ # Compute all img and text sizes if some are missing+ img_width, img_height = size++ if method == "caption":+ if img_width is None:+ raise ValueError("Size is mandatory when method is caption")++ if img_height is None and font_size is None:+ raise ValueError(+ "Height is mandatory when method is caption and font size is None"+ )++ if font_size is None:+ font_size = find_optimum_font_size(+ text=text,+ font=font,+ stroke_width=stroke_width,+ align=text_align,+ spacing=interline,+ width=img_width,+ height=img_height,+ allow_break=True,+ )++ if img_height is None:+ img_height = find_text_size(+ text=text,+ font=font,+ font_size=font_size,+ stroke_width=stroke_width,+ align=text_align,+ spacing=interline,+ max_width=img_width,+ allow_break=True,+ )[1]++ # Add line breaks whenever needed+ text = "\n".join(+ break_text(+ width=img_width,+ text=text,+ font=font,+ font_size=font_size,+ stroke_width=stroke_width,+ align=text_align,+ spacing=interline,+ )+ )++ elif method == "label":+ if font_size is None and img_width is None:+ raise ValueError(+ "Font size is mandatory when method is label and size is None"+ )++ if font_size is None:+ font_size = find_optimum_font_size(+ text=text,+ font=font,+ stroke_width=stroke_width,+ align=text_align,+ spacing=interline,+ width=img_width,+ height=img_height,+ )++ if img_width is None:+ img_width = find_text_size(+ text=text,+ font=font,+ font_size=font_size,+ stroke_width=stroke_width,+ align=text_align,+ spacing=interline,+ )[0]++ if img_height is None:+ img_height = find_text_size(+ text=text,+ font=font,+ font_size=font_size,+ stroke_width=stroke_width,+ align=text_align,+ spacing=interline,+ max_width=img_width,+ )[1]++ else:+ raise ValueError("Method must be either `caption` or `label`.")++ # Trace the image+ img_mode = "RGBA" if transparent else "RGB"++ if bg_color is None and transparent:+ bg_color = (0, 0, 0, 0)++ img = Image.new(img_mode, (img_width, img_height), color=bg_color)+ pil_font = ImageFont.truetype(font, font_size)+ draw = ImageDraw.Draw(img)++ # Dont need allow break here, because we already breaked in caption+ text_width, text_height = find_text_size(+ text=text,+ font=font,+ font_size=font_size,+ stroke_width=stroke_width,+ align=text_align,+ spacing=interline,+ max_width=img_width,+ )++ x = 0+ if horizontal_align == "right":+ x = img_width - text_width+ elif horizontal_align == "center":+ x = (img_width - text_width) / 2++ y = 0+ if vertical_align == "bottom":+ y = img_height - text_height+ elif vertical_align == "center":+ y = (img_height - text_height) / 2++ # So, pillow multiline support is horrible, in particular multiline_text and multiline_textbbox+ # are not intuitive at all. They cannot use left top (see https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html)+ # as anchor, so we always have to use left middle instead. Else we would always have a useless+ # margin (the diff between ascender and top) on any text.+ # That mean our Y is actually not from 0 for top, but need to be increment by half our text height,+ # since we have to reference from middle line.+ y += text_height / 2++ draw.multiline_text(+ xy=(x, y),+ text=text,+ fill=color,+ font=pil_font,+ spacing=interline,+ align=text_align,+ stroke_width=stroke_width,+ stroke_fill=stroke_color,+ anchor="lm",+ )++ # We just need the image as a numpy array+ img_numpy = np.array(img)++ ImageClip.__init__(+ self, img=img_numpy, transparent=transparent, duration=duration+ )+ self.text = text+ self.color = color+ self.stroke_color = stroke_colorclass BitmapClip(VideoClip):diff --git a/moviepy/video/__init__.py b/moviepy/video/__init__.pyindex 32be8f28..48f39539 100644--- a/moviepy/video/__init__.py+++ b/moviepy/video/__init__.py@@ -1 +1 @@-"""Everything about video manipulation."""\ No newline at end of file+"""Everything about video manipulation."""diff --git a/moviepy/video/compositing/__init__.py b/moviepy/video/compositing/__init__.pyindex 38139ef5..7ceb996b 100644--- a/moviepy/video/compositing/__init__.py+++ b/moviepy/video/compositing/__init__.py@@ -1 +1 @@-"""All for compositing video clips."""\ No newline at end of file+"""All for compositing video clips."""diff --git a/moviepy/video/fx/AccelDecel.py b/moviepy/video/fx/AccelDecel.pyindex 9f6d6653..ad89e9ec 100644--- a/moviepy/video/fx/AccelDecel.py+++ b/moviepy/video/fx/AccelDecel.py@@ -1,52 +1,55 @@from moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass AccelDecel(Effect):"""Accelerates and decelerates a clip, useful for GIF making.- Parameters- ----------+ Parameters+ ----------- new_duration : float- Duration for the new transformed clip. If None, will be that of the- current clip.+ new_duration : float+ Duration for the new transformed clip. If None, will be that of the+ current clip.- abruptness : float- Slope shape in the acceleration-deceleration function. It will depend- on the value of the parameter:+ abruptness : float+ Slope shape in the acceleration-deceleration function. It will depend+ on the value of the parameter:- * ``-1 < abruptness < 0``: speed up, down, up.- * ``abruptness == 0``: no effect.- * ``abruptness > 0``: speed down, up, down.+ * ``-1 < abruptness < 0``: speed up, down, up.+ * ``abruptness == 0``: no effect.+ * ``abruptness > 0``: speed down, up, down.- soonness : float- For positive abruptness, determines how soon the transformation occurs.- Should be a positive number.+ soonness : float+ For positive abruptness, determines how soon the transformation occurs.+ Should be a positive number.- Raises- ------+ Raises+ ------- ValueError- When ``sooness`` argument is lower than 0.+ ValueError+ When ``sooness`` argument is lower than 0.- Examples- --------+ Examples+ --------- The following graphs show functions generated by different combinations- of arguments, where the value of the slopes represents the speed of the- videos generated, being the linear function (in red) a combination that- does not produce any transformation.+ The following graphs show functions generated by different combinations+ of arguments, where the value of the slopes represents the speed of the+ videos generated, being the linear function (in red) a combination that+ does not produce any transformation.- .. image:: /_static/medias/accel_decel-fx-params.png- :alt: acced_decel FX parameters combinations+ .. image:: /_static/medias/accel_decel-fx-params.png+ :alt: acced_decel FX parameters combinations"""-+new_duration: float = Noneabruptness: float = 1.0soonness: float = 1.0- def _f_accel_decel(self, t, old_duration, new_duration, abruptness=1.0, soonness=1.0):+ def _f_accel_decel(+ self, t, old_duration, new_duration, abruptness=1.0, soonness=1.0+ ):a = 1.0 + abruptnessdef _f(t):@@ -57,7 +60,7 @@ class AccelDecel(Effect):return 1 - f1(1 - t)return (t < 0.5) * f1(t) + (t >= 0.5) * f2(t)-+return old_duration * _f((t / new_duration) ** soonness)def apply(self, clip):@@ -66,7 +69,13 @@ class AccelDecel(Effect):if self.soonness < 0:raise ValueError("'sooness' should be a positive number")-+return clip.time_transform(- lambda t: self._f_accel_decel(t=t, old_duration=clip.duration , new_duration=self.new_duration, abruptness=self.abruptness, soonness=self.soonness)+ lambda t: self._f_accel_decel(+ t=t,+ old_duration=clip.duration,+ new_duration=self.new_duration,+ abruptness=self.abruptness,+ soonness=self.soonness,+ )).with_duration(self.new_duration)diff --git a/moviepy/video/fx/BlackAndWhite.py b/moviepy/video/fx/BlackAndWhite.pyindex 2c15b4b7..fd473b7c 100644--- a/moviepy/video/fx/BlackAndWhite.py+++ b/moviepy/video/fx/BlackAndWhite.py@@ -2,6 +2,7 @@ import numpy as npfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass BlackAndWhite(Effect):"""Desaturates the picture, makes it black and white.@@ -13,7 +14,7 @@ class BlackAndWhite(Effect):RGB: str = Nonepreserve_luminosity: bool = True-+def apply(self, clip):if self.RGB is None:self.RGB = [1, 1, 1]@@ -21,7 +22,11 @@ class BlackAndWhite(Effect):if self.RGB == "CRT_phosphor":self.RGB = [0.2125, 0.7154, 0.0721]- R, G, B = 1.0 * np.array(self.RGB) / (sum(self.RGB) if self.preserve_luminosity else 1)+ R, G, B = (+ 1.0+ * np.array(self.RGB)+ / (sum(self.RGB) if self.preserve_luminosity else 1)+ )def filter(im):im = R * im[:, :, 0] + G * im[:, :, 1] + B * im[:, :, 2]diff --git a/moviepy/video/fx/Blink.py b/moviepy/video/fx/Blink.pyindex b44c0e9f..57be1d2d 100644--- a/moviepy/video/fx/Blink.py+++ b/moviepy/video/fx/Blink.py@@ -1,6 +1,7 @@from moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass Blink(Effect):"""@@ -20,5 +21,5 @@ class Blink(Effect):clip.mask = clip.mask.transform(lambda get_frame, t: get_frame(t) * ((t % duration) < self.duration_on))-+return clipdiff --git a/moviepy/video/fx/Crop.py b/moviepy/video/fx/Crop.pyindex afdca9c6..f38772f1 100644--- a/moviepy/video/fx/Crop.py+++ b/moviepy/video/fx/Crop.py@@ -2,6 +2,7 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass Crop(Effect):x1: int = None@@ -55,10 +56,16 @@ class Crop(Effect):self.y1 = self.y2 - self.heightif self.x_center:- self.x1, self.x2 = self.x_center - self.width / 2, self.x_center + self.width / 2+ self.x1, self.x2 = (+ self.x_center - self.width / 2,+ self.x_center + self.width / 2,+ )if self.y_center:- self.y1, self.y2 = self.y_center - self.height / 2, self.y_center + self.height / 2+ self.y1, self.y2 = (+ self.y_center - self.height / 2,+ self.y_center + self.height / 2,+ )self.x1 = self.x1 or 0self.y1 = self.y1 or 0@@ -66,5 +73,8 @@ class Crop(Effect):self.y2 = self.y2 or clip.size[1]return clip.image_transform(- lambda frame: frame[int(self.y1) : int(self.y2), int(self.x1) : int(self.x2)], apply_to=["mask"]+ lambda frame: frame[+ int(self.y1) : int(self.y2), int(self.x1) : int(self.x2)+ ],+ apply_to=["mask"],)diff --git a/moviepy/video/fx/CrossFadeIn.py b/moviepy/video/fx/CrossFadeIn.pyindex 2712eb94..b130861a 100644--- a/moviepy/video/fx/CrossFadeIn.py+++ b/moviepy/video/fx/CrossFadeIn.py@@ -4,6 +4,7 @@ from dataclasses import dataclassfrom moviepy.video.fx.FadeIn import FadeIn+@dataclassclass CrossFadeIn(Effect):"""Makes the clip appear progressively, over ``duration`` seconds.@@ -21,6 +22,5 @@ class CrossFadeIn(Effect):clip.mask.duration = clip.durationclip.mask = clip.mask.with_effects([FadeIn(self.duration)])-- return clip+ return clipdiff --git a/moviepy/video/fx/CrossFadeOut.py b/moviepy/video/fx/CrossFadeOut.pyindex de10ca49..a05e44b0 100644--- a/moviepy/video/fx/CrossFadeOut.py+++ b/moviepy/video/fx/CrossFadeOut.py@@ -4,6 +4,7 @@ from dataclasses import dataclassfrom moviepy.video.fx.FadeOut import FadeOut+@dataclassclass CrossFadeOut(Effect):"""Makes the clip disappear progressively, over ``duration`` seconds.@@ -21,6 +22,5 @@ class CrossFadeOut(Effect):clip.mask.duration = clip.durationclip.mask = clip.mask.with_effects([FadeOut(self.duration)])-- return clip+ return clipdiff --git a/moviepy/video/fx/EvenSize.py b/moviepy/video/fx/EvenSize.pyindex 6b233da0..f027ebdf 100644--- a/moviepy/video/fx/EvenSize.py+++ b/moviepy/video/fx/EvenSize.py@@ -1,8 +1,8 @@-from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass EvenSize(Effect):"""Crops the clip to make dimensions even."""@@ -29,5 +29,4 @@ class EvenSize(Effect):def image_filter(a):return a[:-1, :, :]- return clip.image_transform(image_filter, apply_to=['mask'])-\ No newline at end of file+ return clip.image_transform(image_filter, apply_to=["mask"])diff --git a/moviepy/video/fx/FadeIn.py b/moviepy/video/fx/FadeIn.pyindex f3ed251a..a51075cf 100644--- a/moviepy/video/fx/FadeIn.py+++ b/moviepy/video/fx/FadeIn.py@@ -5,6 +5,7 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass FadeIn(Effect):"""Makes the clip progressively appear from some color (black by default),@@ -19,7 +20,6 @@ class FadeIn(Effect):initial_color: list = Nonedef apply(self, clip: Clip) -> Clip:-if self.initial_color is None:self.initial_color = 0 if clip.is_mask else [0, 0, 0]diff --git a/moviepy/video/fx/FadeOut.py b/moviepy/video/fx/FadeOut.pyindex b2c42a93..3338e594 100644--- a/moviepy/video/fx/FadeOut.py+++ b/moviepy/video/fx/FadeOut.py@@ -4,6 +4,7 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass FadeOut(Effect):"""Makes the clip progressively fade to some color (black by default),@@ -13,14 +14,14 @@ class FadeOut(Effect):For cross-fading (progressive appearance or disappearance of a clip over anotherclip), see ``CrossFadeOut``"""-+duration: floatfinal_color: list = None- def apply(self, clip: Clip) -> Clip:+ def apply(self, clip: Clip) -> Clip:if clip.duration is None:raise ValueError("Attribute 'duration' not set")-+if self.final_color is None:self.final_color = 0 if clip.is_mask else [0, 0, 0]diff --git a/moviepy/video/fx/Freeze.py b/moviepy/video/fx/Freeze.pyindex a65a9452..35be3dec 100644--- a/moviepy/video/fx/Freeze.py+++ b/moviepy/video/fx/Freeze.py@@ -4,8 +4,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class Freeze(Effect) :+class Freeze(Effect):"""Momentarily freeze the clip at time t.Set `t='end'` to freeze the clip at the end (actually it will freeze on the@@ -24,7 +25,7 @@ class Freeze(Effect) :def apply(self, clip: Clip) -> Clip:if clip.duration is None:raise ValueError("Attribute 'duration' not set")-+if self.t == "end":self.t = clip.duration - self.padding_end - 1 / clip.fps@@ -35,7 +36,7 @@ class Freeze(Effect) :)self.freeze_duration = self.total_duration - clip.duration- before = [clip[:self.t]] if (self.t != 0) else []+ before = [clip[: self.t]] if (self.t != 0) else []freeze = [clip.to_ImageClip(self.t).with_duration(self.freeze_duration)]- after = [clip[self.t:]] if (self.t != clip.duration) else []+ after = [clip[self.t :]] if (self.t != clip.duration) else []return concatenate_videoclips(before + freeze + after)diff --git a/moviepy/video/fx/FreezeRegion.py b/moviepy/video/fx/FreezeRegion.pyindex bcacb3bd..c34d4a3a 100644--- a/moviepy/video/fx/FreezeRegion.py+++ b/moviepy/video/fx/FreezeRegion.py@@ -5,6 +5,7 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass FreezeRegion(Effect):"""Freezes one region of the clip while the rest remains animated.@@ -38,23 +39,27 @@ class FreezeRegion(Effect):outside_region: tuple = Nonemask: Clip = None- def apply(self, clip: Clip) -> Clip:+ def apply(self, clip: Clip) -> Clip:if self.region is not None:- x1, y1, x2, y2 = self.region- freeze = (- clip.with_effects([Crop(*self.region)])- .to_ImageClip(t=self.t)- .with_duration(clip.duration)- .with_position((x1, y1))- )- return CompositeVideoClip([clip, freeze])+ x1, y1, x2, y2 = self.region+ freeze = (+ clip.with_effects([Crop(*self.region)])+ .to_ImageClip(t=self.t)+ .with_duration(clip.duration)+ .with_position((x1, y1))+ )+ return CompositeVideoClip([clip, freeze])elif self.outside_region is not None:x1, y1, x2, y2 = self.outside_region- animated_region = clip.with_effects([Crop(*self.outside_region)]).with_position((x1, y1))+ animated_region = clip.with_effects(+ [Crop(*self.outside_region)]+ ).with_position((x1, y1))freeze = clip.to_ImageClip(t=self.t).with_duration(clip.duration)return CompositeVideoClip([freeze, animated_region])elif self.mask is not None:- freeze = clip.to_ImageClip(t=t).with_duration(clip.duration).with_mask(self.mask)+ freeze = (+ clip.to_ImageClip(t=t).with_duration(clip.duration).with_mask(self.mask)+ )return CompositeVideoClip([clip, freeze])diff --git a/moviepy/video/fx/GammaCorrection.py b/moviepy/video/fx/GammaCorrection.pyindex 035c72fd..14a6696e 100644--- a/moviepy/video/fx/GammaCorrection.py+++ b/moviepy/video/fx/GammaCorrection.py@@ -2,8 +2,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class GammaCorrection(Effect) :+class GammaCorrection(Effect):"""Gamma-correction of a video clip."""gamma: floatdiff --git a/moviepy/video/fx/HeadBlur.py b/moviepy/video/fx/HeadBlur.pyindex bc9d5b2c..837787d5 100644--- a/moviepy/video/fx/HeadBlur.py+++ b/moviepy/video/fx/HeadBlur.py@@ -4,21 +4,21 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class HeadBlur(Effect) :+class HeadBlur(Effect):"""Returns a filter that will blur a moving part (a head ?) of the frames.The position of the blur at time t is defined by (fx(t), fy(t)), the radiusof the blurring by ``radius`` and the intensity of the blurring by ``intensity``."""-+fx: callablefy: callableradius: floatintensity: float = Nonedef apply(self, clip: Clip) -> Clip:-if self.intensity is None:self.intensity = int(2 * self.radius / 3)@@ -30,13 +30,13 @@ class HeadBlur(Effect) :y1, y2 = max(0, y - self.radius), min(y + self.radius, h)image = Image.fromarray(im)- mask = Image.new('RGB', image.size)+ mask = Image.new("RGB", image.size)draw = ImageDraw.Draw(mask)- draw.ellipse([x1, y1, x2, y2],fill=(255,255,255))+ draw.ellipse([x1, y1, x2, y2], fill=(255, 255, 255))blurred = image.filter(ImageFilter.GaussianBlur(radius=self.intensity))- res = np.where(np.array(mask) > 0, np.array(blurred), np.array(image))+ res = np.where(np.array(mask) > 0, np.array(blurred), np.array(image))return res- return clip.transform(filter)\ No newline at end of file+ return clip.transform(filter)diff --git a/moviepy/video/fx/InvertColors.py b/moviepy/video/fx/InvertColors.pyindex 8a5bc4df..8952fd57 100644--- a/moviepy/video/fx/InvertColors.py+++ b/moviepy/video/fx/InvertColors.py@@ -2,8 +2,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class InvertColors(Effect) :+class InvertColors(Effect):"""Returns the color-inversed clip.The values of all pixels are replaced with (255-v) or (1-v) for masksdiff --git a/moviepy/video/fx/Loop.py b/moviepy/video/fx/Loop.pyindex 9d0f4b73..d0ccde9d 100644--- a/moviepy/video/fx/Loop.py+++ b/moviepy/video/fx/Loop.py@@ -2,8 +2,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class Loop(Effect) :+class Loop(Effect):"""Returns a clip that plays the current clip in an infinite loop.Ideal for clips coming from GIFs.@@ -18,14 +19,14 @@ class Loop(Effect) :durationTotal duration of the clip. Can be specified instead of n."""-+n: int = Noneduration: float = None-+def apply(self, clip: Clip) -> Clip:if clip.duration is None:- raise ValueError("Attribute 'duration' not set")-+ raise ValueError("Attribute 'duration' not set")+previous_duration = clip.durationclip = clip.time_transform(lambda t: t % previous_duration, apply_to=["mask", "audio"]@@ -38,4 +39,3 @@ class Loop(Effect) :clip = clip.with_duration(self.duration)return clip-\ No newline at end of filediff --git a/moviepy/video/fx/LumContrast.py b/moviepy/video/fx/LumContrast.pyindex 330e666d..8db12065 100644--- a/moviepy/video/fx/LumContrast.py+++ b/moviepy/video/fx/LumContrast.py@@ -2,8 +2,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class LumContrast(Effect) :+class LumContrast(Effect):"""Luminosity-contrast correction of a clip."""lum: float = 0@@ -11,10 +12,11 @@ class LumContrast(Effect) :contrast_threshold: float = 127def apply(self, clip: Clip) -> Clip:-def image_filter(im):im = 1.0 * im # float conversion- corrected = im + self.lum + self.contrast * (im - float(self.contrast_threshold))+ corrected = (+ im + self.lum + self.contrast * (im - float(self.contrast_threshold))+ )corrected[corrected < 0] = 0corrected[corrected > 255] = 255return corrected.astype("uint8")diff --git a/moviepy/video/fx/MakeLoopable.py b/moviepy/video/fx/MakeLoopable.pyindex 367efe64..106fe64c 100644--- a/moviepy/video/fx/MakeLoopable.py+++ b/moviepy/video/fx/MakeLoopable.py@@ -5,8 +5,9 @@ from moviepy.Effect import Effectfrom moviepy.video.fx.CrossFadeIn import CrossFadeInfrom dataclasses import dataclass+@dataclass-class MakeLoopable(Effect) :+class MakeLoopable(Effect):"""Makes the clip fade in progressively at its own end, this way it can belooped indefinitely.@@ -20,8 +21,9 @@ class MakeLoopable(Effect) :overlap_duration: floatdef apply(self, clip: Clip) -> Clip:-clip2 = clip.with_effects([CrossFadeIn(self.overlap_duration)]).with_start(clip.duration - self.overlap_duration)- return CompositeVideoClip([clip, clip2]).with_subclip(self.overlap_duration, clip.duration)+ return CompositeVideoClip([clip, clip2]).with_subclip(+ self.overlap_duration, clip.duration+ )diff --git a/moviepy/video/fx/Margin.py b/moviepy/video/fx/Margin.pyindex 531bf129..8d5489b0 100644--- a/moviepy/video/fx/Margin.py+++ b/moviepy/video/fx/Margin.py@@ -7,8 +7,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class Margin(Effect) :+class Margin(Effect):"""Draws an external margin all around the frame.Parameters@@ -44,8 +45,8 @@ class Margin(Effect) :bottom: int = 0color: tuple = (0, 0, 0)opacity: float = 1.0-- def add_margin (self, clip: Clip) :++ def add_margin(self, clip: Clip):if (self.opacity != 1.0) and (clip.mask is None) and not (clip.is_mask):clip = clip.with_add_mask()@@ -68,6 +69,7 @@ class Margin(Effect) :return clip.image_transform(lambda pic: im)else:+def filter(get_frame, t):pic = get_frame(t)h, w = pic.shape[:2]@@ -77,12 +79,11 @@ class Margin(Effect) :return clip.transform(filter)-def apply(self, clip: Clip) -> Clip:# We apply once on clip and once on mask if we have oneclip = self.add_margin(clip=clip)- if clip.mask :+ if clip.mask:clip.mask = self.add_margin(clip=clip.mask)- return clip\ No newline at end of file+ return clipdiff --git a/moviepy/video/fx/MaskColor.py b/moviepy/video/fx/MaskColor.pyindex abea24bd..2ef32a1c 100644--- a/moviepy/video/fx/MaskColor.py+++ b/moviepy/video/fx/MaskColor.py@@ -4,8 +4,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class MaskColor(Effect) :+class MaskColor(Effect):"""Returns a new clip with a mask for transparency where the originalclip is of the given color.@@ -28,7 +29,9 @@ class MaskColor(Effect) :def hill(x):if self.threshold:- return x**self.stiffness / (self.threshold ** self.stiffness + x ** self.stiffness)+ return x**self.stiffness / (+ self.threshold**self.stiffness + x**self.stiffness+ )else:return 1.0 * (x != 0)diff --git a/moviepy/video/fx/MasksAnd.py b/moviepy/video/fx/MasksAnd.pyindex 878e892c..6c355a7e 100644--- a/moviepy/video/fx/MasksAnd.py+++ b/moviepy/video/fx/MasksAnd.py@@ -7,8 +7,9 @@ from moviepy.Effect import Effectfrom dataclasses import dataclassfrom typing import Union+@dataclass-class MasksAnd(Effect) :+class MasksAnd(Effect):"""Returns the logical 'and' (minimum pixel color values) between two masks.The result has the duration of the clip to which has been applied, if it has any.@@ -37,8 +38,12 @@ class MasksAnd(Effect) :self.other_clip = self.other_clip.imgif isinstance(self.other_clip, np.ndarray):- return clip.image_transform(lambda frame: np.minimum(frame, self.other_clip))+ return clip.image_transform(+ lambda frame: np.minimum(frame, self.other_clip)+ )else:return clip.transform(- lambda get_frame, t: np.minimum(get_frame(t), self.other_clip.get_frame(t))+ lambda get_frame, t: np.minimum(+ get_frame(t), self.other_clip.get_frame(t)+ ))diff --git a/moviepy/video/fx/MasksOr.py b/moviepy/video/fx/MasksOr.pyindex 3a931709..9d755a7d 100644--- a/moviepy/video/fx/MasksOr.py+++ b/moviepy/video/fx/MasksOr.py@@ -7,8 +7,9 @@ from moviepy.Effect import Effectfrom dataclasses import dataclassfrom typing import Union+@dataclass-class MasksOr(Effect) :+class MasksOr(Effect):"""Returns the logical 'or' (maximum pixel color values) between two masks.The result has the duration of the clip to which has been applied, if it has any.@@ -37,8 +38,12 @@ class MasksOr(Effect) :other_clip = self.other_clip.imgif isinstance(self.other_clip, np.ndarray):- return clip.image_transform(lambda frame: np.maximum(frame, self.other_clip))+ return clip.image_transform(+ lambda frame: np.maximum(frame, self.other_clip)+ )else:return clip.transform(- lambda get_frame, t: np.maximum(get_frame(t), self.other_clip.get_frame(t))+ lambda get_frame, t: np.maximum(+ get_frame(t), self.other_clip.get_frame(t)+ ))diff --git a/moviepy/video/fx/MirrorX.py b/moviepy/video/fx/MirrorX.pyindex aa0dbbb5..2e44b0ac 100644--- a/moviepy/video/fx/MirrorX.py+++ b/moviepy/video/fx/MirrorX.py@@ -3,8 +3,9 @@ from moviepy.Effect import Effectfrom dataclasses import dataclassfrom typing import Union, List+@dataclass-class MirrorX(Effect) :+class MirrorX(Effect):"""Flips the clip horizontally (and its mask too, by default)."""apply_to: Union[List, str] = "mask"diff --git a/moviepy/video/fx/MirrorY.py b/moviepy/video/fx/MirrorY.pyindex e5f9db3a..38380c27 100644--- a/moviepy/video/fx/MirrorY.py+++ b/moviepy/video/fx/MirrorY.py@@ -3,8 +3,9 @@ from moviepy.Effect import Effectfrom dataclasses import dataclassfrom typing import Union, List+@dataclass-class MirrorY(Effect) :+class MirrorY(Effect):"""Flips the clip vertically (and its mask too, by default)."""apply_to: Union[List, str] = "mask"diff --git a/moviepy/video/fx/MultiplyColor.py b/moviepy/video/fx/MultiplyColor.pyindex fb8e4893..7da8ebb3 100644--- a/moviepy/video/fx/MultiplyColor.py+++ b/moviepy/video/fx/MultiplyColor.py@@ -3,17 +3,18 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class MultiplyColor(Effect) :+class MultiplyColor(Effect):"""Multiplies the clip's colors by the given factor, can be usedto decrease or increase the clip's brightness (is that theright word ?)"""-+factor: floatdef apply(self, clip: Clip) -> Clip:return clip.image_transform(- lambda frame: np.minimum(255, (self.factor * frame)).astype("uint8")- )+ lambda frame: np.minimum(255, (self.factor * frame)).astype("uint8")+ )diff --git a/moviepy/video/fx/MultiplySpeed.py b/moviepy/video/fx/MultiplySpeed.pyindex 3dee6e63..ce61f3b4 100644--- a/moviepy/video/fx/MultiplySpeed.py+++ b/moviepy/video/fx/MultiplySpeed.py@@ -2,8 +2,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class MultiplySpeed(Effect) :+class MultiplySpeed(Effect):"""Returns a clip playing the current clip but at a speed multiplied by ``factor``.Instead of factor one can indicate the desired ``final_duration`` of the clip, and@@ -14,11 +15,13 @@ class MultiplySpeed(Effect) :factor: float = Nonefinal_duration: float = None- def apply(self, clip: Clip) -> Clip:+ def apply(self, clip: Clip) -> Clip:if self.final_duration:self.factor = 1.0 * clip.duration / self.final_duration- new_clip = clip.time_transform(lambda t: self.factor * t, apply_to=["mask", "audio"])+ new_clip = clip.time_transform(+ lambda t: self.factor * t, apply_to=["mask", "audio"]+ )if clip.duration is not None:new_clip = new_clip.with_duration(1.0 * clip.duration / self.factor)diff --git a/moviepy/video/fx/Painting.py b/moviepy/video/fx/Painting.pyindex bb9a7b3e..3b35e411 100644--- a/moviepy/video/fx/Painting.py+++ b/moviepy/video/fx/Painting.py@@ -5,8 +5,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class Painting(Effect) :+class Painting(Effect):"""Transforms any photo into some kind of painting.Transforms any photo into some kind of painting. Saturation@@ -31,7 +32,6 @@ class Painting(Effect) :image = Image.fromarray(np_image)image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)-# Convert the image to grayscalegrayscale_image = image.convert("L")@@ -55,7 +55,7 @@ class Painting(Effect) :return painting-def apply(self, clip: Clip) -> Clip:- return clip.image_transform(lambda im: self.to_painting(im, self.saturation, self.black))-+ return clip.image_transform(+ lambda im: self.to_painting(im, self.saturation, self.black)+ )diff --git a/moviepy/video/fx/Resize.py b/moviepy/video/fx/Resize.pyindex 58c600a7..b315e2a0 100644--- a/moviepy/video/fx/Resize.py+++ b/moviepy/video/fx/Resize.py@@ -5,6 +5,7 @@ from moviepy.Effect import Effectfrom dataclasses import dataclassfrom typing import Union+@dataclassclass Resize(Effect):"""Returns a video clip that is a resized version of the clip.@@ -40,13 +41,11 @@ class Resize(Effect):width: int = Noneapply_to_mask: bool = True-def resizer(self, pic, new_size):- new_size = list(map(int, new_size))- pil_img = Image.fromarray(pic)- resized_pil = pil_img.resize(new_size, Image.Resampling.LANCZOS)- return np.array(resized_pil)-+ new_size = list(map(int, new_size))+ pil_img = Image.fromarray(pic)+ resized_pil = pil_img.resize(new_size, Image.Resampling.LANCZOS)+ return np.array(resized_pil)def apply(self, clip):w, h = clip.size@@ -73,20 +72,28 @@ class Resize(Effect):def filter(get_frame, t):return (- self.resizer((255 * get_frame(t)).astype("uint8"), get_new_size(t))+ self.resizer(+ (255 * get_frame(t)).astype("uint8"), get_new_size(t)+ )/ 255.0)else:def filter(get_frame, t):- return self.resizer(get_frame(t).astype("uint8"), get_new_size(t))+ return self.resizer(+ get_frame(t).astype("uint8"), get_new_size(t)+ )newclip = clip.transform(- filter, keep_duration=True, apply_to=(["mask"] if self.apply_to_mask else [])+ filter,+ keep_duration=True,+ apply_to=(["mask"] if self.apply_to_mask else []),)if self.apply_to_mask and clip.mask is not None:- newclip.mask = clip.mask.with_effects([Resize(self.new_size, apply_to_mask=False)])+ newclip.mask = clip.mask.with_effects(+ [Resize(self.new_size, apply_to_mask=False)]+ )return newclip@@ -115,14 +122,20 @@ class Resize(Effect):else:self.new_size = [self.width, h * self.width / w]else:- raise ValueError("You must provide either 'new_size' or 'height' or 'width'")+ raise ValueError(+ "You must provide either 'new_size' or 'height' or 'width'"+ )# From here, the resizing is constant (not a function of time), size=newsizeif clip.is_mask:def image_filter(pic):- return 1.0 * self.resizer((255 * pic).astype("uint8"), self.new_size) / 255.0+ return (+ 1.0+ * self.resizer((255 * pic).astype("uint8"), self.new_size)+ / 255.0+ )else:@@ -132,6 +145,8 @@ class Resize(Effect):new_clip = clip.image_transform(image_filter)if self.apply_to_mask and clip.mask is not None:- new_clip.mask = clip.mask.with_effects([Resize(self.new_size, apply_to_mask=False)])+ new_clip.mask = clip.mask.with_effects(+ [Resize(self.new_size, apply_to_mask=False)]+ )return new_clipdiff --git a/moviepy/video/fx/Rotate.py b/moviepy/video/fx/Rotate.pyindex 9cba4135..1e5d70d1 100644--- a/moviepy/video/fx/Rotate.py+++ b/moviepy/video/fx/Rotate.py@@ -7,46 +7,47 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class Rotate(Effect) :+class Rotate(Effect):"""- Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise- If the angle is not a multiple of 90 (degrees) or ``center``, ``translate``,- and ``bg_color`` are not ``None``, there will be black borders.- You can make them transparent with:+ Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise+ If the angle is not a multiple of 90 (degrees) or ``center``, ``translate``,+ and ``bg_color`` are not ``None``, there will be black borders.+ You can make them transparent with:- >>> new_clip = clip.with_add_mask().rotate(72)+ >>> new_clip = clip.with_add_mask().rotate(72)- Parameters- ----------+ Parameters+ ----------- clip : VideoClip- A video clip.+ clip : VideoClip+ A video clip.- angle : float- Either a value or a function angle(t) representing the angle of rotation.+ angle : float+ Either a value or a function angle(t) representing the angle of rotation.- unit : str, optional- Unit of parameter `angle` (either "deg" for degrees or "rad" for radians).+ unit : str, optional+ Unit of parameter `angle` (either "deg" for degrees or "rad" for radians).- resample : str, optional- An optional resampling filter. One of "nearest", "bilinear", or "bicubic".+ resample : str, optional+ An optional resampling filter. One of "nearest", "bilinear", or "bicubic".- expand : bool, optional- If true, expands the output image to make it large enough to hold the- entire rotated image. If false or omitted, make the output image the same- size as the input image.+ expand : bool, optional+ If true, expands the output image to make it large enough to hold the+ entire rotated image. If false or omitted, make the output image the same+ size as the input image.- translate : tuple, optional- An optional post-rotate translation (a 2-tuple).+ translate : tuple, optional+ An optional post-rotate translation (a 2-tuple).- center : tuple, optional- Optional center of rotation (a 2-tuple). Origin is the upper left corner.+ center : tuple, optional+ Optional center of rotation (a 2-tuple). Origin is the upper left corner.- bg_color : tuple, optional- An optional color for area outside the rotated image. Only has effect if- ``expand`` is true.- """+ bg_color : tuple, optional+ An optional color for area outside the rotated image. Only has effect if+ ``expand`` is true.+ """angle: floatunit: str = "deg"@@ -57,7 +58,6 @@ class Rotate(Effect) :bg_color: tuple = Nonedef apply(self, clip: Clip) -> Clip:-try:resample = {"bilinear": Image.BILINEAR,@@ -93,18 +93,17 @@ class Rotate(Effect) :return np.transpose(im, axes=transpose)[:, ::-1]elif (angle == 180) and self.expand:return im[::-1, ::-1]--+pillow_kwargs = {}- if self.bg_color is not None :- pillow_kwargs['fillcolor'] = self.bg_color-- if self.center is not None :- pillow_kwargs['center'] = self.center+ if self.bg_color is not None:+ pillow_kwargs["fillcolor"] = self.bg_color++ if self.center is not None:+ pillow_kwargs["center"] = self.center- if self.translate is not None :- pillow_kwargs['translate'] = self.translate+ if self.translate is not None:+ pillow_kwargs["translate"] = self.translate# 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 bydiff --git a/moviepy/video/fx/Scroll.py b/moviepy/video/fx/Scroll.pyindex b429096f..555c15a0 100644--- a/moviepy/video/fx/Scroll.py+++ b/moviepy/video/fx/Scroll.py@@ -1,8 +1,17 @@from moviepy.Effect import Effect-class Scroll(Effect) :- def __init__ (self, w=None, h=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask") :+class Scroll(Effect):+ def __init__(+ self,+ w=None,+ h=None,+ x_speed=0,+ y_speed=0,+ x_start=0,+ y_start=0,+ apply_to="mask",+ ):"""Scrolls horizontally or vertically a clip, e.g. to make end credits@@ -28,12 +37,11 @@ class Scroll(Effect) :self.y_start = y_startself.apply_to = apply_to-- def apply(self, clip) :+ def apply(self, clip):if self.h is None:self.h = clip.h- if self.w is None :+ if self.w is None:self.w = clip.wx_max = self.w - 1@@ -43,5 +51,5 @@ class Scroll(Effect) :x = int(max(0, min(x_max, self.x_start + round(self.x_speed * t))))y = int(max(0, min(y_max, self.y_start + round(self.y_speed * t))))return get_frame(t)[y : y + self.h, x : x + self.w]-- return clip.transform(filter, apply_to=self.apply_to)\ No newline at end of file++ return clip.transform(filter, apply_to=self.apply_to)diff --git a/moviepy/video/fx/SlideIn.py b/moviepy/video/fx/SlideIn.pyindex 26236eb8..14ba6204 100644--- a/moviepy/video/fx/SlideIn.py+++ b/moviepy/video/fx/SlideIn.py@@ -2,6 +2,7 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass SlideIn(Effect):"""Makes the clip arrive from one side of the screen.@@ -53,6 +54,3 @@ class SlideIn(Effect):}return clip.with_position(pos_dict[self.side])---diff --git a/moviepy/video/fx/SlideOut.py b/moviepy/video/fx/SlideOut.pyindex 3e14f135..cb2425b9 100644--- a/moviepy/video/fx/SlideOut.py+++ b/moviepy/video/fx/SlideOut.py@@ -2,6 +2,7 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclassclass SlideOut(Effect):"""Makes the clip goes away by one side of the screen.@@ -57,6 +58,3 @@ class SlideOut(Effect):}return clip.with_position(pos_dict[self.side])---diff --git a/moviepy/video/fx/SuperSample.py b/moviepy/video/fx/SuperSample.pyindex 958a5b2f..9ffa0b72 100644--- a/moviepy/video/fx/SuperSample.py+++ b/moviepy/video/fx/SuperSample.py@@ -4,8 +4,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class SuperSample(Effect) :+class SuperSample(Effect):"""Replaces each frame at time t by the mean of `n_frames` equally spaced framestaken in the interval [t-d, t+d]. This results in motion blur."""@@ -17,8 +18,9 @@ class SuperSample(Effect) :def filter(get_frame, t):timings = np.linspace(t - self.d, t + self.d, self.n_frames)frame_average = np.mean(- 1.0 * np.array([get_frame(t_) for t_ in timings], dtype="uint16"), axis=0+ 1.0 * np.array([get_frame(t_) for t_ in timings], dtype="uint16"),+ axis=0,)return frame_average.astype("uint8")-+return clip.transform(filter)diff --git a/moviepy/video/fx/TimeMirror.py b/moviepy/video/fx/TimeMirror.pyindex a6613afc..b3260fd4 100644--- a/moviepy/video/fx/TimeMirror.py+++ b/moviepy/video/fx/TimeMirror.py@@ -2,8 +2,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class TimeMirror(Effect) :+class TimeMirror(Effect):"""Returns a clip that plays the current clip backwards.The clip must have its ``duration`` attribute set.@@ -13,5 +14,5 @@ class TimeMirror(Effect) :def apply(self, clip: Clip) -> Clip:if clip.duration is None:raise ValueError("Attribute 'duration' not set")-- return clip[::-1]\ No newline at end of file++ return clip[::-1]diff --git a/moviepy/video/fx/TimeSymmetrize.py b/moviepy/video/fx/TimeSymmetrize.pyindex ed5c04ed..ed3bc122 100644--- a/moviepy/video/fx/TimeSymmetrize.py+++ b/moviepy/video/fx/TimeSymmetrize.py@@ -2,8 +2,9 @@ from moviepy.Clip import Clipfrom moviepy.Effect import Effectfrom dataclasses import dataclass+@dataclass-class TimeSymmetrize(Effect) :+class TimeSymmetrize(Effect):"""Returns a clip that plays the current clip once forwards andthen once backwards. This is very practival to make video that@@ -15,5 +16,5 @@ class TimeSymmetrize(Effect) :def apply(self, clip: Clip) -> Clip:if clip.duration is None:raise ValueError("Attribute 'duration' not set")-+return clip + clip[::-1]diff --git a/moviepy/video/fx/__init__.py b/moviepy/video/fx/__init__.pyindex 33ce668f..4f5d20f4 100644--- a/moviepy/video/fx/__init__.py+++ b/moviepy/video/fx/__init__.py@@ -73,4 +73,4 @@ __all__ = ("SuperSample","TimeMirror","TimeSymmetrize",-)\ No newline at end of file+)diff --git a/moviepy/video/io/ImageSequenceClip.py b/moviepy/video/io/ImageSequenceClip.pyindex ba308314..01ff5535 100644--- a/moviepy/video/io/ImageSequenceClip.py+++ b/moviepy/video/io/ImageSequenceClip.py@@ -41,7 +41,7 @@ class ImageSequenceClip(VideoClip):load_imagesSpecify that all images should be loaded into the RAM. This is only- interesting if you have a small number of images that will be used+ interesting if you have a small number of images that will be usedmore than once."""diff --git a/moviepy/video/io/ffplay_previewer.py b/moviepy/video/io/ffplay_previewer.pyindex 5417a93c..3137767d 100644--- a/moviepy/video/io/ffplay_previewer.py+++ b/moviepy/video/io/ffplay_previewer.py@@ -25,7 +25,7 @@ class FFPLAY_VideoPreviewer:Frames per second in the output video file.pixel_format : str- Pixel format for the output video file, ``rgb24`` for normal video, ``rgba``+ Pixel format for the output video file, ``rgb24`` for normal video, ``rgba``if video with mask."""@@ -38,7 +38,7 @@ class FFPLAY_VideoPreviewer:# order is importantcmd = [FFPLAY_BINARY,- "-autoexit", # If you dont precise, ffplay dont stop at end+ "-autoexit", # If you dont precise, ffplay dont stop at end"-f","rawvideo","-pixel_format",@@ -92,11 +92,7 @@ class FFPLAY_VideoPreviewer:def ffplay_preview_video(- clip,- fps,- pixel_format="rgb24",- audio_flag=None,- video_flag=None+ clip, fps, pixel_format="rgb24", audio_flag=None, video_flag=None):"""Preview the clip using ffplay. See VideoClip.preview for detailson the parameters.@@ -117,7 +113,7 @@ def ffplay_preview_video(it require applying mask on CompositeVideoClip and thoses are believed tonot be working.- Pixel format for the output video file, ``rgb24`` for normal video, ``rgba``+ Pixel format for the output video file, ``rgb24`` for normal video, ``rgba``if video with maskaudio_flag : Thread.Event, optional@@ -128,26 +124,17 @@ def ffplay_preview_video(provided, we simply ignore"""- with FFPLAY_VideoPreviewer(- clip.size,- fps,- pixel_format- ) as previewer:+ with FFPLAY_VideoPreviewer(clip.size, fps, pixel_format) as previewer:first_frame = True- for t, frame in clip.iter_frames(- with_times=True, fps=fps, dtype="uint8"- ):-+ for t, frame in clip.iter_frames(with_times=True, fps=fps, dtype="uint8"):previewer.show_frame(frame)# After first frame is shown, if we have audio/video flag, set video ready and wait for audio- if first_frame :+ if first_frame:first_frame = False- if video_flag :+ if video_flag:video_flag.set() # say to the audio: video is ready- if audio_flag :+ if audio_flag:audio_flag.wait() # wait for the audio to be ready--diff --git a/moviepy/video/io/gif_writers.py b/moviepy/video/io/gif_writers.pyindex aaf2ff91..0a66b1ee 100644--- a/moviepy/video/io/gif_writers.py+++ b/moviepy/video/io/gif_writers.py@@ -4,19 +4,18 @@ import proglogfrom moviepy.decorators import requires_duration, use_clip_fps_by_defaultimport imageio.v3 as iio+@requires_duration@use_clip_fps_by_default-def write_gif_with_imageio(- clip, filename, fps=None, loop=0, logger="bar"-):+def write_gif_with_imageio(clip, filename, fps=None, loop=0, logger="bar"):"""- Writes the gif with the Python library ImageIO (calls FreeImage).+ Writes the gif with the Python library ImageIO (calls FreeImage)."""logger = proglog.default_bar_logger(logger)- with iio.imopen(filename, 'w', plugin="pillow") as writer:+ with iio.imopen(filename, "w", plugin="pillow") as writer:logger(message="MoviePy - Building file %s with imageio." % filename)for frame in clip.iter_frames(fps=fps, logger=logger, dtype="uint8"):- writer.write(frame, duration=1000 / fps, loop=loop) # Duration is in ms not s--\ No newline at end of file+ writer.write(+ frame, duration=1000 / fps, loop=loop+ ) # Duration is in ms not sdiff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.pyindex 03c5e630..fa1309dd 100644--- a/moviepy/video/tools/subtitles.py+++ b/moviepy/video/tools/subtitles.py@@ -67,8 +67,8 @@ class SubtitlesClip(VideoClip):self.font = fontif make_textclip is None:- if self.font is None :- raise ValueError('Argument font is required if make_textclip is None.')+ if self.font is None:+ raise ValueError("Argument font is required if make_textclip is None.")def make_textclip(txt):return TextClip(