Video editing with Python
Start transition of effect from function to real class, video effects done
osaajani3545f8d842bd
diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex afbb7dd0..4bdb1c9a 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -9,6 +9,11 @@ from operator import addimport numpy as npimport proglog+from typing import Union, List, TYPE_CHECKING++if TYPE_CHECKING:+ from moviepy.Effect import Effect+from moviepy.decorators import (apply_to_audio,apply_to_mask,@@ -180,25 +185,27 @@ class Clip:keep_duration=keep_duration,)- def fx(self, func, *args, **kwargs):- """Returns the result of ``func(self, *args, **kwargs)``, for instance-- >>> new_clip = clip.fx(resize, 0.2, method="bilinear")-- is equivalent to+ def with_effect(self, effects: Union['Effect', List['Effect']]):+ """Return a copy of the current clip with the effects applied- >>> new_clip = resize(clip, 0.2, method="bilinear")+ >>> new_clip = clip.with_effect(vfx.Resize(0.2, method="bilinear"))- The motivation of fx is to keep the name of the effect near its- parameters when the effects are chained:+ You can also pass multiple effect as a list- >>> from moviepy.video.fx import multiply_volume, resize, mirrorx- >>> clip.fx(multiply_volume, 0.5).fx(resize, 0.3).fx(mirrorx)- >>> # Is equivalent, but clearer than- >>> mirrorx(resize(multiply_volume(clip, 0.5), 0.3))+ >>> clip.with_effect([vfx.VolumeX(0.5), vfx.Resize(0.3), vfx.Mirrorx()])"""- return func(self, *args, **kwargs)+ if not isinstance(effects, list) :+ effects = [effects]+ new_clip = self.copy()+ for effect in effects :+ # We always copy effect before using it, see Effect.copy+ # to see why we need to+ effect_copy = effect.copy()+ new_clip = effect_copy.apply(new_clip)++ return new_clip+@apply_to_mask@apply_to_audio@convert_parameter_to_seconds(["t"])@@ -288,6 +295,7 @@ 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@@ -317,9 +325,9 @@ class Clip:fps is halved in this mode, the duration will be doubled."""if change_duration:- from moviepy.video.fx.multiply_speed import multiply_speed+ from moviepy.video.fx.MultiplySpeed import MultiplySpeed- newclip = multiply_speed(self, fps / self.fps)+ newclip = self.with_effect(MultiplySpeed(fps / self.fps))else:newclip = self.copy()@@ -649,6 +657,6 @@ class Clip:if not isinstance(n, Real):return NotImplemented- from moviepy.video.fx.loop import loop+ from moviepy.video.fx.Loop import Loop- return loop(self, n)+ return self.with_effect(Loop(n))diff --git a/moviepy/Effect.py b/moviepy/Effect.pynew file mode 100644index 00000000..7c9d1bab--- /dev/null+++ b/moviepy/Effect.py@@ -0,0 +1,36 @@+from abc import ABCMeta, abstractmethod+from moviepy.Clip import Clip+from dataclasses import dataclass+import copy as _copy++class Effect(metaclass=ABCMeta):++ def copy(self):+ """Return a shallow copy of an Effect.++ You must *always* copy an ``Effect`` before calling ``Effect.apply``,+ because some of them will modify their own attributes when calling apply.+ 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 times+ could lead to different properties, and different results for equivalent clips.++ By using copy, we ensure we can use the same effect object multiple times while+ maintaining the same behavior/result.++ In a way, copy make the effect himself beeing kind of indempotent."""+ return _copy.copy(self)+++ @abstractmethod+ def apply(self, clip: Clip) -> Clip:+ """Apply the current effect on a clip++ Parameters+ --------------+ clip+ The target clip to apply the effect on.+ (Internally, MoviePy will always pass a copy of the original clip)++ """+ pass\ No newline at end of filediff --git a/moviepy/__init__.py b/moviepy/__init__.pyindex 63cc74b2..67e65e4d 100644--- a/moviepy/__init__.py+++ b/moviepy/__init__.py@@ -26,6 +26,7 @@ from moviepy.video.io import ffmpeg_toolsfrom moviepy.video.io.display_in_notebook import display_in_notebookfrom moviepy.video.io.ImageSequenceClip import ImageSequenceClipfrom moviepy.video.io.VideoFileClip import VideoFileClip+from moviepy import Effectfrom moviepy.video.VideoClip import (BitmapClip,ColorClip,@@ -40,7 +41,7 @@ from moviepy.video.VideoClip import (# Transforms the effects into Clip methods so that# they can be called with clip.resize(width=500) instead of# clip.fx(vfx.resize, width=500)-audio_fxs = inspect.getmembers(afx, inspect.isfunction) + [("loop", vfx.loop)]+audio_fxs = inspect.getmembers(afx, inspect.isfunction) + [("Loop", vfx.Loop)]video_fxs = (inspect.getmembers(vfx, inspect.isfunction)+ inspect.getmembers(transfx, inspect.isfunction)diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 677e7bdf..bc07785a 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -999,9 +999,9 @@ class VideoClip(Clip):def __matmul__(self, n):if not isinstance(n, Real):return NotImplemented- from moviepy.video.fx.rotate import rotate-- return rotate(self, n)++ from moviepy.video.fx.Rotate import Rotate+ return self.with_effect(Rotate(n))def __and__(self, mask):return self.with_mask(mask)diff --git a/moviepy/video/compositing/transitions.py b/moviepy/video/compositing/transitions.pyindex cdd7acc6..22fbe283 100644--- a/moviepy/video/compositing/transitions.py+++ b/moviepy/video/compositing/transitions.py@@ -3,8 +3,8 @@ There are available as ``transfx.crossfadein`` etc."""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 moviepy.video.fx.FadeIn import FadeIn+from moviepy.video.fx.FadeOut import FadeOut__all__ = ["crossfadein", "crossfadeout", "slide_in", "slide_out"]@@ -18,7 +18,7 @@ def crossfadein(clip, duration):"""clip.mask.duration = clip.durationnew_clip = clip.copy()- new_clip.mask = clip.mask.fx(fadein, duration)+ new_clip.mask = clip.mask.with_effect(FadeIn(duration))return new_clip@@ -30,7 +30,7 @@ def crossfadeout(clip, duration):"""clip.mask.duration = clip.durationnew_clip = clip.copy()- new_clip.mask = clip.mask.fx(fadeout, duration)+ new_clip.mask = clip.mask.with_effect(FadeOut(duration))return new_clipdiff --git a/moviepy/video/fx/AccelDecel.py b/moviepy/video/fx/AccelDecel.pynew file mode 100644index 00000000..9c7991fe--- /dev/null+++ b/moviepy/video/fx/AccelDecel.py@@ -0,0 +1,72 @@+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class AccelDecel(Effect):+ """Accelerates and decelerates a clip, useful for GIF making.++ Parameters+ ----------++ 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:++ * ``-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.++ Raises+ ------++ ValueError+ When ``sooness`` argument is lower than 0.++ 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.++ .. image:: /_static/accel_decel-fx-params.png+ :alt: acced_decel FX parameters combinations+ """++ new_duration: float = None+ abruptness: float = 1.0+ soonness: float = 1.0++ def _f_accel_decel(self, t, old_duration, new_duration, abruptness=1.0, soonness=1.0):+ a = 1.0 + abruptness++ def _f(t):+ def f1(t):+ return (0.5) ** (1 - a) * (t**a)++ def f2(t):+ 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):+ if self.new_duration is None:+ self.new_duration = clip.duration++ 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)+ ).with_duration(self.new_duration)diff --git a/moviepy/video/fx/BlackAndWhite.py b/moviepy/video/fx/BlackAndWhite.pynew file mode 100644index 00000000..2c15b4b7--- /dev/null+++ b/moviepy/video/fx/BlackAndWhite.py@@ -0,0 +1,30 @@+import numpy as np+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class BlackAndWhite(Effect):+ """Desaturates the picture, makes it black and white.+ Parameter RGB allows to set weights for the different color+ channels.+ If RBG is 'CRT_phosphor' a special set of values is used.+ preserve_luminosity maintains the sum of RGB to 1.+ """++ RGB: str = None+ preserve_luminosity: bool = True++ def apply(self, clip):+ if self.RGB is None:+ self.RGB = [1, 1, 1]++ 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)++ def filter(im):+ im = R * im[:, :, 0] + G * im[:, :, 1] + B * im[:, :, 2]+ return np.dstack(3 * [im]).astype("uint8")++ return clip.image_transform(filter)diff --git a/moviepy/video/fx/Blink.py b/moviepy/video/fx/Blink.pynew file mode 100644index 00000000..b44c0e9f--- /dev/null+++ b/moviepy/video/fx/Blink.py@@ -0,0 +1,24 @@+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class Blink(Effect):+ """+ Makes the clip blink. At each blink it will be displayed ``duration_on``+ seconds and disappear ``duration_off`` seconds. Will only work in+ composite clips.+ """++ duration_on: float+ duration_off: float++ def apply(self, clip):+ if clip.mask is None:+ clip = clip.with_add_mask()++ duration = self.duration_on + self.duration_off+ 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.pynew file mode 100644index 00000000..afdca9c6--- /dev/null+++ b/moviepy/video/fx/Crop.py@@ -0,0 +1,70 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class Crop(Effect):+ 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 the+ original clip is conserved. x1,y1 indicates the top left corner and+ x2,y2 is the lower right corner of the croped region.+ All coordinates are in pixels. Float numbers are accepted.++ To crop an arbitrary rectangle:++ >>> Crop(x1=50, y1=60, x2=460, y2=275)++ Only remove the part above y=30:++ >>> Crop(y1=30)++ Crop a rectangle that starts 10 pixels left and is 200px wide++ >>> Crop(x1=10, width=200)++ Crop a rectangle centered in x,y=(300,400), width=50, height=150 :++ >>> Crop(x_center=300 , y_center=400,+ width=50, height=150)++ Any combination of the above should work, like for this rectangle+ centered in x=300, with explicit y-boundaries:++ >>> Crop(x_center=300, width=400, y1=100, y2=600)++ """++ def apply(self, clip: Clip) -> Clip:+ if self.width and self.x1 is not None:+ self.x2 = self.x1 + self.width+ elif self.width and self.x2 is not None:+ self.x1 = self.x2 - self.width++ if self.height and self.y1 is not None:+ self.y2 = self.y1 + self.height+ elif self.height and self.y2 is not None:+ self.y1 = self.y2 - self.height++ if self.x_center:+ 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.x1 = self.x1 or 0+ self.y1 = self.y1 or 0+ self.x2 = self.x2 or clip.size[0]+ 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"]+ )diff --git a/moviepy/video/fx/EvenSize.py b/moviepy/video/fx/EvenSize.pynew file mode 100644index 00000000..6b233da0--- /dev/null+++ b/moviepy/video/fx/EvenSize.py@@ -0,0 +1,33 @@++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class EvenSize(Effect):+ """Crops the clip to make dimensions even."""++ def apply(self, clip: Clip) -> Clip:+ w, h = clip.size+ w_even = w % 2 == 0+ h_even = h % 2 == 0+ if w_even and h_even:+ return clip++ if not w_even and not h_even:++ def image_filter(a):+ return a[:-1, :-1, :]++ elif h_even:++ def image_filter(a):+ return a[:, :-1, :]++ else:++ def image_filter(a):+ return a[:-1, :, :]++ return clip.image_transform(image_filter, apply_to=['mask'])+\ No newline at end of filediff --git a/moviepy/video/fx/FadeIn.py b/moviepy/video/fx/FadeIn.pynew file mode 100644index 00000000..48de1ce7--- /dev/null+++ b/moviepy/video/fx/FadeIn.py@@ -0,0 +1,35 @@+import numpy as np+++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class FadeIn(Effect):+ """Makes the clip progressively appear from some color (black by default),+ over ``duration`` seconds at the beginning of the clip. Can be used for+ masks too, where the initial color must be a number between 0 and 1.++ For cross-fading (progressive appearance or disappearance of a clip+ over another clip, see ``transfx.crossfadein``+ """++ duration: float+ initial_color: list = None++ def apply(self, clip: Clip) -> Clip:++ if self.initial_color is None:+ self.initial_color = 0 if clip.is_mask else [0, 0, 0]++ self.initial_color = np.array(self.initial_color)++ def filter(get_frame, t):+ if t >= self.duration:+ return get_frame(t)+ else:+ fading = 1.0 * t / self.duration+ return fading * get_frame(t) + (1 - fading) * self.initial_color++ return clip.transform(filter)diff --git a/moviepy/video/fx/FadeOut.py b/moviepy/video/fx/FadeOut.pynew file mode 100644index 00000000..d1937fb2--- /dev/null+++ b/moviepy/video/fx/FadeOut.py@@ -0,0 +1,36 @@+import numpy as np++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass+++class FadeOut(Effect):+ """Makes the clip progressively fade to some color (black by default),+ over ``duration`` seconds at the end of the clip. Can be used for masks too,+ where the final color must be a number between 0 and 1.++ For cross-fading (progressive appearance or disappearance of a clip over another+ clip, see ``transfx.crossfadeout``+ """++ duration: float+ final_color: list = None++ 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]++ self.final_color = np.array(self.final_color)++ def filter(get_frame, t):+ if (clip.duration - t) >= self.duration:+ return get_frame(t)+ else:+ fading = 1.0 * (clip.duration - t) / self.duration+ return fading * get_frame(t) + (1 - fading) * self.final_color++ return clip.transform(filter)diff --git a/moviepy/video/fx/Freeze.py b/moviepy/video/fx/Freeze.pynew file mode 100644index 00000000..a65a9452--- /dev/null+++ b/moviepy/video/fx/Freeze.py@@ -0,0 +1,41 @@+from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+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+ frame at time clip.duration - padding_end seconds - 1 / clip_fps).+ With ``duration`` you can specify the duration of the freeze.+ With ``total_duration`` you can specify the total duration of+ the clip and the freeze (i.e. the duration of the freeze is+ automatically computed). One of them must be provided.+ """++ t: float = 0+ freeze_duration: float = None+ total_duration: float = None+ padding_end: float = 0++ 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++ if self.freeze_duration is None:+ if self.total_duration is None:+ raise ValueError(+ "You must provide either 'freeze_duration' or 'total_duration'"+ )+ self.freeze_duration = self.total_duration - clip.duration++ 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 []+ return concatenate_videoclips(before + freeze + after)diff --git a/moviepy/video/fx/FreezeRegion.py b/moviepy/video/fx/FreezeRegion.pynew file mode 100644index 00000000..b4b0dc0c--- /dev/null+++ b/moviepy/video/fx/FreezeRegion.py@@ -0,0 +1,60 @@+from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip+from moviepy.video.fx.Crop import Crop++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class FreezeRegion(Effect):+ """Freezes one region of the clip while the rest remains animated.++ You can choose one of three methods by providing either `region`,+ `outside_region`, or `mask`.++ Parameters+ ----------++ t+ Time at which to freeze the freezed region.++ region+ A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)+ which will be freezed. You can provide outside_region or mask instead.++ outside_region+ A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)+ which will be the only non-freezed region.++ mask+ If not None, will overlay a freezed version of the clip on the current clip,+ with the provided mask. In other words, the "visible" pixels in the mask+ indicate the freezed region in the final picture.++ """++ t: float = 0+ region: tuple = None+ outside_region: tuple = None+ mask: Clip = None++ def apply(self, clip: Clip) -> Clip:+ if self.region is not None:+ x1, y1, x2, y2 = self.region+ freeze = (+ clip.with_effect(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_effect(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)+ return CompositeVideoClip([clip, freeze])diff --git a/moviepy/video/fx/GammaCorrection.py b/moviepy/video/fx/GammaCorrection.pynew file mode 100644index 00000000..035c72fd--- /dev/null+++ b/moviepy/video/fx/GammaCorrection.py@@ -0,0 +1,16 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class GammaCorrection(Effect) :+ """Gamma-correction of a video clip."""++ gamma: float++ def apply(self, clip: Clip) -> Clip:+ def filter(im):+ corrected = 255 * (1.0 * im / 255) ** self.gamma+ return corrected.astype("uint8")++ return clip.image_transform(filter)diff --git a/moviepy/video/fx/HeadBlur.py b/moviepy/video/fx/HeadBlur.pynew file mode 100644index 00000000..bc9d5b2c--- /dev/null+++ b/moviepy/video/fx/HeadBlur.py@@ -0,0 +1,42 @@+import numpy as np+from PIL import Image, ImageDraw, ImageFilter+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+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 radius+ of the blurring by ``radius`` and the intensity of the blurring by ``intensity``.+ """++ fx: callable+ fy: callable+ radius: float+ intensity: float = None++ def apply(self, clip: Clip) -> Clip:++ if self.intensity is None:+ self.intensity = int(2 * self.radius / 3)++ def filter(gf, t):+ im = gf(t).copy()+ h, w, d = im.shape+ x, y = int(self.fx(t)), int(self.fy(t))+ x1, x2 = max(0, x - self.radius), min(x + self.radius, w)+ y1, y2 = max(0, y - self.radius), min(y + self.radius, h)++ image = Image.fromarray(im)+ mask = Image.new('RGB', image.size)+ draw = ImageDraw.Draw(mask)+ 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))+ return res++ return clip.transform(filter)\ No newline at end of filediff --git a/moviepy/video/fx/InvertColors.py b/moviepy/video/fx/InvertColors.pynew file mode 100644index 00000000..8a5bc4df--- /dev/null+++ b/moviepy/video/fx/InvertColors.py@@ -0,0 +1,15 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class InvertColors(Effect) :+ """Returns the color-inversed clip.++ The values of all pixels are replaced with (255-v) or (1-v) for masks+ Black becomes white, green becomes purple, etc.+ """++ def apply(self, clip: Clip) -> Clip:+ maxi = 1.0 if clip.is_mask else 255+ return clip.image_transform(lambda f: maxi - f)diff --git a/moviepy/video/fx/Loop.py b/moviepy/video/fx/Loop.pynew file mode 100644index 00000000..9d0f4b73--- /dev/null+++ b/moviepy/video/fx/Loop.py@@ -0,0 +1,41 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class Loop(Effect) :+ """+ Returns a clip that plays the current clip in an infinite loop.+ Ideal for clips coming from GIFs.++ Parameters+ ----------++ n+ Number of times the clip should be played. If `None` the+ the clip will loop indefinitely (i.e. with no set duration).++ duration+ Total duration of the clip. Can be specified instead of n.+ """++ n: int = None+ duration: float = None++ def apply(self, clip: Clip) -> Clip:+ if clip.duration is None:+ raise ValueError("Attribute 'duration' not set")++ previous_duration = clip.duration+ clip = clip.time_transform(+ lambda t: t % previous_duration, apply_to=["mask", "audio"]+ )++ if self.n:+ self.duration = self.n * previous_duration++ if self.duration:+ 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.pynew file mode 100644index 00000000..330e666d--- /dev/null+++ b/moviepy/video/fx/LumContrast.py@@ -0,0 +1,22 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class LumContrast(Effect) :+ """Luminosity-contrast correction of a clip."""++ lum: float = 0+ contrast: float = 0+ contrast_threshold: float = 127++ def 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[corrected < 0] = 0+ corrected[corrected > 255] = 255+ return corrected.astype("uint8")++ return clip.image_transform(image_filter)diff --git a/moviepy/video/fx/MakeLoopable.py b/moviepy/video/fx/MakeLoopable.pynew file mode 100644index 00000000..9b4bf9d7--- /dev/null+++ b/moviepy/video/fx/MakeLoopable.py@@ -0,0 +1,26 @@+from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class MakeLoopable(Effect) :+ """Makes the clip fade in progressively at its own end, this way it can be+ looped indefinitely.++ Parameters+ ----------++ overlap_duration : float+ Duration of the fade-in (in seconds).+ """++ overlap_duration: float++ def apply(self, clip: Clip) -> Clip:++ clip2 = clip.crossfadein(self.overlap_duration).with_start(+ clip.duration - self.overlap_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.pynew file mode 100644index 00000000..531bf129--- /dev/null+++ b/moviepy/video/fx/Margin.py@@ -0,0 +1,88 @@+import numpy as np++from moviepy.decorators import apply_to_mask+from moviepy.video.VideoClip import ImageClip++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class Margin(Effect) :+ """Draws an external margin all around the frame.++ Parameters+ ----------++ margin_size : int, optional+ If not ``None``, then the new clip has a margin size of+ size ``margin_size`` in pixels on the left, right, top, and bottom.++ left : int, optional+ If ``margin_size=None``, margin size for the new clip in left direction.++ right : int, optional+ If ``margin_size=None``, margin size for the new clip in right direction.++ top : int, optional+ If ``margin_size=None``, margin size for the new clip in top direction.++ bottom : int, optional+ If ``margin_size=None``, margin size for the new clip in bottom direction.++ color : tuple, optional+ Color of the margin.++ opacity : float, optional+ Opacity of the margin. Setting this value to 0 yields transparent margins.+ """++ margin_size: int = None+ left: int = 0+ right: int = 0+ top: int = 0+ bottom: int = 0+ color: tuple = (0, 0, 0)+ opacity: float = 1.0++ 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()++ if self.margin_size is not None:+ self.left = self.right = self.top = self.bottom = self.margin_size++ def make_bg(w, h):+ new_w, new_h = w + self.left + self.right, h + self.top + self.bottom+ if clip.is_mask:+ shape = (new_h, new_w)+ bg = np.tile(self.opacity, (new_h, new_w)).astype(float).reshape(shape)+ else:+ shape = (new_h, new_w, 3)+ bg = np.tile(self.color, (new_h, new_w)).reshape(shape)+ return bg++ if isinstance(clip, ImageClip):+ im = make_bg(clip.w, clip.h)+ im[self.top : self.top + clip.h, self.left : self.left + clip.w] = clip.img+ return clip.image_transform(lambda pic: im)++ else:+ def filter(get_frame, t):+ pic = get_frame(t)+ h, w = pic.shape[:2]+ im = make_bg(w, h)+ im[self.top : self.top + h, self.left : self.left + w] = pic+ return im++ return clip.transform(filter)+++ def apply(self, clip: Clip) -> Clip:+ # We apply once on clip and once on mask if we have one+ clip = self.add_margin(clip=clip)++ if clip.mask :+ clip.mask = self.add_margin(clip=clip.mask)++ return clip\ No newline at end of filediff --git a/moviepy/video/fx/MaskColor.py b/moviepy/video/fx/MaskColor.pynew file mode 100644index 00000000..abea24bd--- /dev/null+++ b/moviepy/video/fx/MaskColor.py@@ -0,0 +1,40 @@+import numpy as np++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class MaskColor(Effect) :+ """Returns a new clip with a mask for transparency where the original+ 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++ 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``+ """++ color: tuple = (0, 0, 0)+ threshold: float = 0+ stiffness: float = 1++ def apply(self, clip: Clip) -> Clip:+ color = np.array(self.color)++ def hill(x):+ if self.threshold:+ return x**self.stiffness / (self.threshold ** self.stiffness + x ** self.stiffness)+ else:+ return 1.0 * (x != 0)++ def flim(im):+ return hill(np.sqrt(((im - color) ** 2).sum(axis=2)))++ mask = clip.image_transform(flim)+ mask.is_mask = True+ return clip.with_mask(mask)diff --git a/moviepy/video/fx/MasksAnd.py b/moviepy/video/fx/MasksAnd.pynew file mode 100644index 00000000..70d20bf3--- /dev/null+++ b/moviepy/video/fx/MasksAnd.py@@ -0,0 +1,44 @@+import numpy as np++from moviepy.video.VideoClip import ImageClip++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass+from typing import Union++@dataclass+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.++ Parameters+ ----------++ other_clip ImageClip or np.ndarray+ Clip used to mask the original clip.++ Examples+ --------++ >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red+ >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green+ >>> masked_clip = clip.fx(mask_and, mask) # black+ >>> masked_clip.get_frame(0)+ [[[0 0 0]]]+ """++ other_clip: Union[Clip, np.ndarray]++ def apply(self, clip: Clip) -> Clip:+ # to ensure that 'and' of two ImageClips will be an ImageClip+ if isinstance(self.other_clip, ImageClip):+ self.other_clip = self.other_clip.img++ if isinstance(self.other_clip, np.ndarray):+ 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))+ )diff --git a/moviepy/video/fx/MasksOr.py b/moviepy/video/fx/MasksOr.pynew file mode 100644index 00000000..1880d48a--- /dev/null+++ b/moviepy/video/fx/MasksOr.py@@ -0,0 +1,44 @@+import numpy as np++from moviepy.video.VideoClip import ImageClip++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass+from typing import Union++@dataclass+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.++ Parameters+ ----------++ other_clip ImageClip or np.ndarray+ Clip used to mask the original clip.++ Examples+ --------++ >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red+ >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green+ >>> masked_clip = clip.fx(mask_or, mask) # yellow+ >>> masked_clip.get_frame(0)+ [[[255 255 0]]]+ """++ other_clip: Union[Clip, np.ndarray]++ def apply(self, clip: Clip) -> Clip:+ # to ensure that 'or' of two ImageClips will be an ImageClip+ if isinstance(self.other_clip, ImageClip):+ other_clip = self.other_clip.img++ if isinstance(self.other_clip, np.ndarray):+ 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))+ )diff --git a/moviepy/video/fx/MirrorX.py b/moviepy/video/fx/MirrorX.pynew file mode 100644index 00000000..aa0dbbb5--- /dev/null+++ b/moviepy/video/fx/MirrorX.py@@ -0,0 +1,13 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass+from typing import Union, List++@dataclass+class MirrorX(Effect) :+ """Flips the clip horizontally (and its mask too, by default)."""++ apply_to: Union[List, str] = "mask"++ def apply(self, clip: Clip) -> Clip:+ return clip.image_transform(lambda img: img[:, ::-1], apply_to=self.apply_to)diff --git a/moviepy/video/fx/MirrorY.py b/moviepy/video/fx/MirrorY.pynew file mode 100644index 00000000..e5f9db3a--- /dev/null+++ b/moviepy/video/fx/MirrorY.py@@ -0,0 +1,13 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass+from typing import Union, List++@dataclass+class MirrorY(Effect) :+ """Flips the clip vertically (and its mask too, by default)."""++ apply_to: Union[List, str] = "mask"++ def apply(self, clip: Clip) -> Clip:+ return clip.image_transform(lambda img: img[::-1], apply_to=self.apply_to)diff --git a/moviepy/video/fx/MultiplyColor.py b/moviepy/video/fx/MultiplyColor.pynew file mode 100644index 00000000..fb8e4893--- /dev/null+++ b/moviepy/video/fx/MultiplyColor.py@@ -0,0 +1,19 @@+import numpy as np+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class MultiplyColor(Effect) :+ """+ Multiplies the clip's colors by the given factor, can be used+ to decrease or increase the clip's brightness (is that the+ right word ?)+ """++ factor: float++ def apply(self, clip: Clip) -> Clip:+ return clip.image_transform(+ lambda frame: np.minimum(255, (self.factor * frame)).astype("uint8")+ )diff --git a/moviepy/video/fx/MultiplySpeed.py b/moviepy/video/fx/MultiplySpeed.pynew file mode 100644index 00000000..3dee6e63--- /dev/null+++ b/moviepy/video/fx/MultiplySpeed.py@@ -0,0 +1,26 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+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+ the factor will be automatically computed. The same effect is applied to the clip's+ audio and mask if any.+ """++ factor: float = None+ final_duration: float = None++ 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"])++ if clip.duration is not None:+ new_clip = new_clip.with_duration(1.0 * clip.duration / self.factor)++ return new_clipdiff --git a/moviepy/video/fx/Painting.py b/moviepy/video/fx/Painting.pynew file mode 100644index 00000000..bb9a7b3e--- /dev/null+++ b/moviepy/video/fx/Painting.py@@ -0,0 +1,61 @@+import numpy as np+from PIL import Image, ImageFilter++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class Painting(Effect) :+ """Transforms any photo into some kind of painting.++ Transforms any photo into some kind of painting. Saturation+ tells at which point the colors of the result should be+ flashy. ``black`` gives the amount of black lines wanted.++ np_image : a numpy image+ """++ saturation: float = 1.4+ black: float = 0.006++ def to_painting(self, np_image, saturation=1.4, black=0.006):+ """Transforms any photo into some kind of painting.++ Transforms any photo into some kind of painting. Saturation+ tells at which point the colors of the result should be+ flashy. ``black`` gives the amount of black lines wanted.++ np_image : a numpy image+ """+ image = Image.fromarray(np_image)+ image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)+++ # Convert the image to grayscale+ grayscale_image = image.convert("L")++ # Find the image edges+ edges_image = grayscale_image.filter(ImageFilter.FIND_EDGES)++ # Convert the edges image to a numpy array+ edges = np.array(edges_image)++ # Create the darkening effect+ darkening = black * (255 * np.dstack(3 * [edges]))++ # Apply the painting effect+ painting = saturation * np.array(image) - darkening++ # Clip the pixel values to the valid range of 0-255+ painting = np.maximum(0, np.minimum(255, painting))++ # Convert the pixel values to unsigned 8-bit integers+ painting = painting.astype("uint8")++ return painting+++ def apply(self, clip: Clip) -> Clip:+ 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.pynew file mode 100644index 00000000..32d24cb8--- /dev/null+++ b/moviepy/video/fx/Resize.py@@ -0,0 +1,133 @@+import numbers+from PIL import Image+import numpy as np+from moviepy.Effect import Effect+++class Resize(Effect):++ def __init__(self, new_size=None, height=None, width=None, apply_to_mask=True) :+ """Returns a video clip that is a resized version of the clip.++ Parameters+ ----------++ new_size : tuple or float or function, optional+ Can be either+ - ``(width, height)`` in pixels or a float representing+ - A scaling factor, like ``0.5``.+ - A function of time returning one of these.++ width : int, optional+ Width of the new clip in pixels. The height is then computed so+ that the width/height ratio is conserved.++ height : int, optional+ Height of the new clip in pixels. The width is then computed so+ that the width/height ratio is conserved.++ Examples+ --------++ >>> myClip.with_effect(vfx.Resize((460,720))) # New resolution: (460,720)+ >>> myClip.with_effect(vfx.Resize(0.6)) # width and height multiplied by 0.6+ >>> myClip.with_effect(vfx.Resize(width=800)) # height computed automatically.+ >>> myClip.with_effect(vfx.Resize(lambda t : 1+0.02*t)) # slow swelling of the clip+ """+ self.new_size = new_size+ self.height = height+ self.width = width+ self.apply_to_mask = apply_to_mask++ def resizer(self, pic, new_size):+ new_size = list(map(int, new_size))[::-1]++ pil_img = Image.fromarray(pic)+ resized_pil = pil_img.resize(new_size[::-1], Image.ANTIALIAS)+ return np.array(resized_pil)+++ def apply(self, clip):+ w, h = clip.size++ if self.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_`+ """+ if isinstance(new_size_, numbers.Number):+ return [new_size_ * w, new_size_ * h]+ else:+ return new_size_++ if hasattr(self.new_size, "__call__"):+ # The resizing is a function of time++ def get_new_size(t):+ return translate_new_size(self.new_size(t))++ if clip.is_mask:+ def filter(get_frame, t):+ return (+ 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))++ newclip = clip.transform(+ 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 = newclip.mask.with_effect(Resize(clip.mask, self.new_size, apply_to_mask=False))++ return newclip++ else:+ new_size = translate_new_size(new_size)++ elif self.height is not None:+ if hasattr(self.height, "__call__"):++ def func(t):+ return 1.0 * int(self.height(t)) / h++ return clip.with_effect(Resize(func))++ else:+ new_size = [w * self.height / h, self.height]++ elif self.width is not None:+ if hasattr(self.width, "__call__"):++ def func(t):+ return 1.0 * self.width(t) / w++ return clip.with_effect(Resize(func))++ else:+ new_size = [self.width, h * self.width / w]+ else:+ raise ValueError("You must provide either 'new_size' or 'height' or 'width'")++ # From here, the resizing is constant (not a function of time), size=newsize+ if clip.is_mask:++ def image_filter(pic):+ return 1.0 * self.resizer((255 * pic).astype("uint8"), new_size) / 255.0++ else:++ def image_filter(pic):+ return self.resizer(pic.astype("uint8"), new_size)++ new_clip = clip.image_transform(image_filter)++ if self.apply_to_mask and clip.mask is not None:+ new_clip.mask = clip.with_effect(Resize(clip.mask, self.new_size, apply_to_mask=False))++ return new_clipdiff --git a/moviepy/video/fx/Rotate.py b/moviepy/video/fx/Rotate.pynew file mode 100644index 00000000..69980f87--- /dev/null+++ b/moviepy/video/fx/Rotate.py@@ -0,0 +1,128 @@+import math+import warnings++import numpy as np+from PIL import Image+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+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``, the package ``pillow`` must be installed,+ and there will be black borders. You can make them transparent with:++ >>> new_clip = clip.with_add_mask().rotate(72)++ Parameters+ ----------++ clip : VideoClip+ A video clip.++ 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).++ 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.++ 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.++ bg_color : tuple, optional+ An optional color for area outside the rotated image. Only has effect if+ ``expand`` is true.+ """++ angle: float+ unit: str = "deg"+ resample: str = "bicubic"+ expand: bool = False+ center: tuple = None+ translate: tuple = None+ bg_color: tuple = None++ def apply(self, clip: Clip) -> Clip:++ try:+ resample = {+ "bilinear": Image.BILINEAR,+ "nearest": Image.NEAREST,+ "bicubic": Image.BICUBIC,+ }[self.resample]+ except KeyError:+ raise ValueError(+ "'resample' argument must be either 'bilinear', 'nearest' or 'bicubic'"+ )++ if hasattr(self.angle, "__call__"):+ get_angle = self.angle+ else:+ get_angle = lambda t: self.angle++ def filter(get_frame, t):+ angle = get_angle(t)+ im = get_frame(t)++ if self.unit == "rad":+ angle = math.degrees(angle)++ angle %= 360+ if not self.center and not self.translate and not self.bg_color:+ if (angle == 0) and self.expand:+ return im+ if (angle == 90) and self.expand:+ transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]+ return np.transpose(im, axes=transpose)[::-1]+ elif (angle == 270) and self.expand:+ transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]+ 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.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 by+ # a factor 'a' for use with PIL and then back again by 'a' afterwards.+ if im.dtype == "float64":+ # this is a mask image+ a = 255.0+ else:+ a = 1++ # call PIL.rotate+ return (+ np.array(+ Image.fromarray(np.array(a * im).astype(np.uint8)).rotate(+ angle, expand=self.expand, resample=resample, **pillow_kwargs+ )+ )+ / a+ )++ return clip.transform(filter, apply_to=["mask"])diff --git a/moviepy/video/fx/Scroll.py b/moviepy/video/fx/Scroll.pynew file mode 100644index 00000000..b429096f--- /dev/null+++ b/moviepy/video/fx/Scroll.py@@ -0,0 +1,47 @@+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") :+ """+ Scrolls horizontally or vertically a clip, e.g. to make end credits++ Parameters+ ----------++ w, h+ The width and height of the final clip. Default to clip.w and clip.h++ x_speed, y_speed++ x_start, y_start+++ apply_to++ """+ self.w = w+ self.h = h+ self.x_speed = x_speed+ self.y_speed = y_speed+ self.x_start = x_start+ self.y_start = y_start+ self.apply_to = apply_to+++ def apply(self, clip) :+ if self.h is None:+ self.h = clip.h++ if self.w is None :+ self.w = clip.w++ x_max = self.w - 1+ y_max = self.h - 1++ def filter(get_frame, t):+ 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 filediff --git a/moviepy/video/fx/SuperSample.py b/moviepy/video/fx/SuperSample.pynew file mode 100644index 00000000..958a5b2f--- /dev/null+++ b/moviepy/video/fx/SuperSample.py@@ -0,0 +1,24 @@+import numpy as np++from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class SuperSample(Effect) :+ """Replaces each frame at time t by the mean of `n_frames` equally spaced frames+ taken in the interval [t-d, t+d]. This results in motion blur.+ """++ d: float+ n_frames: int++ def apply(self, clip: Clip) -> Clip:+ 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+ )+ return frame_average.astype("uint8")++ return clip.transform(filter)diff --git a/moviepy/video/fx/TimeMirror.py b/moviepy/video/fx/TimeMirror.pynew file mode 100644index 00000000..a6613afc--- /dev/null+++ b/moviepy/video/fx/TimeMirror.py@@ -0,0 +1,17 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class TimeMirror(Effect) :+ """+ Returns a clip that plays the current clip backwards.+ The clip must have its ``duration`` attribute set.+ The same effect is applied to the clip's audio and mask if any.+ """++ 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 filediff --git a/moviepy/video/fx/TimeSymmetrize.py b/moviepy/video/fx/TimeSymmetrize.pynew file mode 100644index 00000000..ed5c04ed--- /dev/null+++ b/moviepy/video/fx/TimeSymmetrize.py@@ -0,0 +1,19 @@+from moviepy.Clip import Clip+from moviepy.Effect import Effect+from dataclasses import dataclass++@dataclass+class TimeSymmetrize(Effect) :+ """+ Returns a clip that plays the current clip once forwards and+ then once backwards. This is very practival to make video that+ loop well, e.g. to create animated GIFs.+ This effect is automatically applied to the clip's mask and audio+ if they exist.+ """++ 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 d1f56ce3..057d2bb8 100644--- a/moviepy/video/fx/__init__.py+++ b/moviepy/video/fx/__init__.py@@ -1,66 +1,66 @@# import every video fx function-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.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.multiply_color import multiply_color-from moviepy.video.fx.multiply_speed import multiply_speed-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.supersample import supersample-from moviepy.video.fx.time_mirror import time_mirror-from moviepy.video.fx.time_symmetrize import time_symmetrize+from moviepy.video.fx.AccelDecel import AccelDecel+from moviepy.video.fx.BlackAndWhite import BlackAndWhite+from moviepy.video.fx.Blink import Blink+from moviepy.video.fx.Crop import Crop+from moviepy.video.fx.EvenSize import EvenSize+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.FreezeRegion import FreezeRegion+from moviepy.video.fx.GammaCorrection import GammaCorrection+from moviepy.video.fx.HeadBlur import HeadBlur+from moviepy.video.fx.InvertColors import InvertColors+from moviepy.video.fx.Loop import Loop+from moviepy.video.fx.LumContrast import LumContrast+from moviepy.video.fx.MakeLoopable import MakeLoopable+from moviepy.video.fx.Margin import Margin+from moviepy.video.fx.MasksAnd import MasksAnd+from moviepy.video.fx.MaskColor import MaskColor+from moviepy.video.fx.MasksOr import MasksOr+from moviepy.video.fx.MirrorX import MirrorX+from moviepy.video.fx.MirrorY import MirrorY+from moviepy.video.fx.MultiplyColor import MultiplyColor+from moviepy.video.fx.MultiplySpeed import MultiplySpeed+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.SuperSample import SuperSample+from moviepy.video.fx.TimeMirror import TimeMirror+from moviepy.video.fx.TimeSymmetrize import TimeSymmetrize__all__ = (- "accel_decel",- "blackwhite",- "blink",- "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",- "multiply_color",- "multiply_speed",- "painting",- "resize",- "rotate",- "scroll",- "supersample",- "time_mirror",- "time_symmetrize",-)+ "AccelDecel",+ "BlackAndWhite",+ "Blink",+ "Crop",+ "EvenSize",+ "FadeIn",+ "FadeOut",+ "Freeze",+ "FreezeRegion",+ "GammaCorrection",+ "HeadBlur",+ "InvertColors",+ "Loop",+ "LumContrast",+ "MakeLoopable",+ "Margin",+ "MasksAnd",+ "MaskColor",+ "MasksOr",+ "MirrorX",+ "MirrorY",+ "MultiplyColor",+ "MultiplySpeed",+ "Painting",+ "Resize",+ "Rotate",+ "Scroll",+ "SuperSample",+ "TimeMirror",+ "TimeSymmetrize",+)\ No newline at end of filediff --git a/moviepy/video/fx/accel_decel.py b/moviepy/video/fx/accel_decel.pydeleted file mode 100644index 8145c17c..00000000--- a/moviepy/video/fx/accel_decel.py+++ /dev/null@@ -1,62 +0,0 @@-def _f_accel_decel(t, old_duration, new_duration, abruptness=1.0, soonness=1.0):- a = 1.0 + abruptness-- def _f(t):- def f1(t):- return (0.5) ** (1 - a) * (t**a)-- def f2(t):- 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 accel_decel(clip, new_duration=None, abruptness=1.0, soonness=1.0):- """Accelerates and decelerates a clip, useful for GIF making.-- Parameters- ------------ 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:-- * ``-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.-- Raises- -------- ValueError- When ``sooness`` argument is lower than 0.-- 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.-- .. image:: /_static/accel_decel-fx-params.png- :alt: acced_decel FX parameters combinations- """- if new_duration is None:- new_duration = clip.duration- if soonness < 0:- raise ValueError("'sooness' should be a positive number")-- return clip.time_transform(- lambda t: _f_accel_decel(t, clip.duration, new_duration, abruptness, soonness)- ).with_duration(new_duration)diff --git a/moviepy/video/fx/all/__init__.py b/moviepy/video/fx/all/__init__.pydeleted file mode 100644index 34b0627d..00000000--- a/moviepy/video/fx/all/__init__.py+++ /dev/null@@ -1,12 +0,0 @@-"""-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.-"""-import warnings--from moviepy.video.fx import * # noqa F401,F403---warnings.warn(f"\nMoviePy: {__doc__}", UserWarning)diff --git a/moviepy/video/fx/blackwhite.py b/moviepy/video/fx/blackwhite.pydeleted file mode 100644index d23d7fbb..00000000--- a/moviepy/video/fx/blackwhite.py+++ /dev/null@@ -1,23 +0,0 @@-import numpy as np---def blackwhite(clip, RGB=None, preserve_luminosity=True):- """Desaturates the picture, makes it black and white.- Parameter RGB allows to set weights for the different color- channels.- If RBG is 'CRT_phosphor' a special set of values is used.- preserve_luminosity maintains the sum of RGB to 1.- """- if RGB is None:- RGB = [1, 1, 1]-- if RGB == "CRT_phosphor":- RGB = [0.2125, 0.7154, 0.0721]-- R, G, B = 1.0 * np.array(RGB) / (sum(RGB) if preserve_luminosity else 1)-- def filter(im):- im = R * im[:, :, 0] + G * im[:, :, 1] + B * im[:, :, 2]- return np.dstack(3 * [im]).astype("uint8")-- return clip.image_transform(filter)diff --git a/moviepy/video/fx/blink.py b/moviepy/video/fx/blink.pydeleted file mode 100644index c19801f2..00000000--- a/moviepy/video/fx/blink.py+++ /dev/null@@ -1,14 +0,0 @@-def blink(clip, duration_on, duration_off):- """- Makes the clip blink. At each blink it will be displayed ``duration_on``- seconds and disappear ``duration_off`` seconds. Will only work in- composite clips.- """- new_clip = clip.copy()- if new_clip.mask is None:- new_clip = new_clip.with_mask()- duration = duration_on + duration_off- new_clip.mask = new_clip.mask.transform(- lambda get_frame, t: get_frame(t) * ((t % duration) < duration_on)- )- return new_clipdiff --git a/moviepy/video/fx/crop.py b/moviepy/video/fx/crop.pydeleted file mode 100644index 85ff7d5f..00000000--- a/moviepy/video/fx/crop.py+++ /dev/null@@ -1,64 +0,0 @@-def crop(- clip,- x1=None,- y1=None,- x2=None,- y2=None,- width=None,- height=None,- x_center=None,- y_center=None,-):- """- Returns a new clip in which just a rectangular subregion of the- original clip is conserved. x1,y1 indicates the top left corner and- x2,y2 is the lower right corner of the croped region.- All coordinates are in pixels. Float numbers are accepted.-- To crop an arbitrary rectangle:-- >>> crop(clip, x1=50, y1=60, x2=460, y2=275)-- Only remove the part above y=30:-- >>> crop(clip, y1=30)-- Crop a rectangle that starts 10 pixels left and is 200px wide-- >>> crop(clip, x1=10, width=200)-- Crop a rectangle centered in x,y=(300,400), width=50, height=150 :-- >>> crop(clip, x_center=300 , y_center=400,- width=50, height=150)-- Any combination of the above should work, like for this rectangle- centered in x=300, with explicit y-boundaries:-- >>> crop(clip, x_center=300, width=400, y1=100, y2=600)-- """- if width and x1 is not None:- x2 = x1 + width- elif width and x2 is not None:- x1 = x2 - width-- if height and y1 is not None:- y2 = y1 + height- elif height and y2 is not None:- y1 = y2 - height-- if x_center:- x1, x2 = x_center - width / 2, x_center + width / 2-- if y_center:- y1, y2 = y_center - height / 2, y_center + height / 2-- x1 = x1 or 0- y1 = y1 or 0- x2 = x2 or clip.size[0]- y2 = y2 or clip.size[1]-- return clip.image_transform(- lambda frame: frame[int(y1) : int(y2), int(x1) : int(x2)], apply_to=["mask"]- )diff --git a/moviepy/video/fx/even_size.py b/moviepy/video/fx/even_size.pydeleted file mode 100644index 61ae680f..00000000--- a/moviepy/video/fx/even_size.py+++ /dev/null@@ -1,28 +0,0 @@-from moviepy.decorators import apply_to_mask---@apply_to_mask-def even_size(clip):- """Crops the clip to make dimensions even."""- w, h = clip.size- w_even = w % 2 == 0- h_even = h % 2 == 0- if w_even and h_even:- return clip-- if not w_even and not h_even:-- def image_filter(a):- return a[:-1, :-1, :]-- elif h_even:-- def image_filter(a):- return a[:, :-1, :]-- else:-- def image_filter(a):- return a[:-1, :, :]-- return clip.image_transform(image_filter)diff --git a/moviepy/video/fx/fadein.py b/moviepy/video/fx/fadein.pydeleted file mode 100644index 6a280f0c..00000000--- a/moviepy/video/fx/fadein.py+++ /dev/null@@ -1,24 +0,0 @@-import numpy as np---def fadein(clip, duration, initial_color=None):- """Makes the clip progressively appear from some color (black by default),- over ``duration`` seconds at the beginning of the clip. Can be used for- masks too, where the initial color must be a number between 0 and 1.-- For cross-fading (progressive appearance or disappearance of a clip- over another clip, see ``transfx.crossfadein``- """- if initial_color is None:- initial_color = 0 if clip.is_mask else [0, 0, 0]-- initial_color = np.array(initial_color)-- def filter(get_frame, t):- if t >= duration:- return get_frame(t)- else:- fading = 1.0 * t / duration- return fading * get_frame(t) + (1 - fading) * initial_color-- return clip.transform(filter)diff --git a/moviepy/video/fx/fadeout.py b/moviepy/video/fx/fadeout.pydeleted file mode 100644index b58600fe..00000000--- a/moviepy/video/fx/fadeout.py+++ /dev/null@@ -1,27 +0,0 @@-import numpy as np--from moviepy.decorators import requires_duration---@requires_duration-def fadeout(clip, duration, final_color=None):- """Makes the clip progressively fade to some color (black by default),- over ``duration`` seconds at the end of the clip. Can be used for masks too,- where the final color must be a number between 0 and 1.-- For cross-fading (progressive appearance or disappearance of a clip over another- clip, see ``transfx.crossfadeout``- """- if final_color is None:- final_color = 0 if clip.is_mask else [0, 0, 0]-- final_color = np.array(final_color)-- def filter(get_frame, t):- if (clip.duration - t) >= duration:- return get_frame(t)- else:- fading = 1.0 * (clip.duration - t) / duration- return fading * get_frame(t) + (1 - fading) * final_color-- return clip.transform(filter)diff --git a/moviepy/video/fx/freeze.py b/moviepy/video/fx/freeze.pydeleted file mode 100644index 21eae0c7..00000000--- a/moviepy/video/fx/freeze.py+++ /dev/null@@ -1,29 +0,0 @@-from moviepy.decorators import requires_duration-from moviepy.video.compositing.CompositeVideoClip import concatenate_videoclips---@requires_duration-def freeze(clip, t=0, freeze_duration=None, total_duration=None, padding_end=0):- """Momentarily freeze the clip at time t.-- Set `t='end'` to freeze the clip at the end (actually it will freeze on the- frame at time clip.duration - padding_end seconds - 1 / clip_fps).- With ``duration`` you can specify the duration of the freeze.- With ``total_duration`` you can specify the total duration of- the clip and the freeze (i.e. the duration of the freeze is- automatically computed). One of them must be provided.- """- if t == "end":- t = clip.duration - padding_end - 1 / clip.fps-- if freeze_duration is None:- if total_duration is None:- raise ValueError(- "You must provide either 'freeze_duration' or 'total_duration'"- )- freeze_duration = total_duration - clip.duration-- before = [clip[:t]] if (t != 0) else []- freeze = [clip.to_ImageClip(t).with_duration(freeze_duration)]- after = [clip[t:]] if (t != clip.duration) else []- return concatenate_videoclips(before + freeze + after)diff --git a/moviepy/video/fx/freeze_region.py b/moviepy/video/fx/freeze_region.pydeleted file mode 100644index a067ccfe..00000000--- a/moviepy/video/fx/freeze_region.py+++ /dev/null@@ -1,49 +0,0 @@-from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip-from moviepy.video.fx.crop import crop---def freeze_region(clip, t=0, region=None, outside_region=None, mask=None):- """Freezes one region of the clip while the rest remains animated.-- You can choose one of three methods by providing either `region`,- `outside_region`, or `mask`.-- Parameters- ------------ t- Time at which to freeze the freezed region.-- region- A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)- which will be freezed. You can provide outside_region or mask instead.-- outside_region- A tuple (x1, y1, x2, y2) defining the region of the screen (in pixels)- which will be the only non-freezed region.-- mask- If not None, will overlay a freezed version of the clip on the current clip,- with the provided mask. In other words, the "visible" pixels in the mask- indicate the freezed region in the final picture.-- """- if region is not None:- x1, y1, x2, y2 = region- freeze = (- clip.fx(crop, *region)- .to_ImageClip(t=t)- .with_duration(clip.duration)- .with_position((x1, y1))- )- return CompositeVideoClip([clip, freeze])-- elif outside_region is not None:- x1, y1, x2, y2 = outside_region- animated_region = clip.fx(crop, *outside_region).with_position((x1, y1))- freeze = clip.to_ImageClip(t=t).with_duration(clip.duration)- return CompositeVideoClip([freeze, animated_region])-- elif mask is not None:- freeze = clip.to_ImageClip(t=t).with_duration(clip.duration).with_mask(mask)- return CompositeVideoClip([clip, freeze])diff --git a/moviepy/video/fx/gamma_corr.py b/moviepy/video/fx/gamma_corr.pydeleted file mode 100644index c3dbd863..00000000--- a/moviepy/video/fx/gamma_corr.py+++ /dev/null@@ -1,8 +0,0 @@-def gamma_corr(clip, gamma):- """Gamma-correction of a video clip."""-- def filter(im):- corrected = 255 * (1.0 * im / 255) ** gamma- return corrected.astype("uint8")-- return clip.image_transform(filter)diff --git a/moviepy/video/fx/headblur.py b/moviepy/video/fx/headblur.pydeleted file mode 100644index 9f6b1ccd..00000000--- a/moviepy/video/fx/headblur.py+++ /dev/null@@ -1,30 +0,0 @@-import numpy as np-from PIL import Image, ImageDraw, ImageFilter--def headblur(clip, fx, fy, radius, intensity=None):- """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 radius- of the blurring by ``radius`` and the intensity of the blurring by ``intensity``.- """- if intensity is None:- intensity = int(2 * radius / 3)-- def filter(gf, t):- im = gf(t).copy()- h, w, d = im.shape- x, y = int(fx(t)), int(fy(t))- x1, x2 = max(0, x - radius), min(x + radius, w)- y1, y2 = max(0, y - radius), min(y + radius, h)-- image = Image.fromarray(im)- mask = Image.new('RGB', image.size)- draw = ImageDraw.Draw(mask)- draw.ellipse([x1, y1, x2, y2],fill=(255,255,255))-- blurred = image.filter(ImageFilter.GaussianBlur(radius=15))-- res = np.where(np.array(mask) > 0, np.array(blurred), np.array(image))- return res-- return clip.transform(filter)\ No newline at end of filediff --git a/moviepy/video/fx/invert_colors.py b/moviepy/video/fx/invert_colors.pydeleted file mode 100644index 15e675f0..00000000--- a/moviepy/video/fx/invert_colors.py+++ /dev/null@@ -1,8 +0,0 @@-def invert_colors(clip):- """Returns the color-inversed clip.-- The values of all pixels are replaced with (255-v) or (1-v) for masks- Black becomes white, green becomes purple, etc.- """- maxi = 1.0 if clip.is_mask else 255- return clip.image_transform(lambda f: maxi - f)diff --git a/moviepy/video/fx/loop.py b/moviepy/video/fx/loop.pydeleted file mode 100644index 310c52a6..00000000--- a/moviepy/video/fx/loop.py+++ /dev/null@@ -1,28 +0,0 @@-from moviepy.decorators import requires_duration---@requires_duration-def loop(clip, n=None, duration=None):- """- Returns a clip that plays the current clip in an infinite loop.- Ideal for clips coming from GIFs.-- Parameters- ------------ n- Number of times the clip should be played. If `None` the- the clip will loop indefinitely (i.e. with no set duration).-- duration- Total duration of the clip. Can be specified instead of n.- """- previous_duration = clip.duration- clip = clip.time_transform(- lambda t: t % previous_duration, apply_to=["mask", "audio"]- )- if n:- duration = n * previous_duration- if duration:- clip = clip.with_duration(duration)- return clipdiff --git a/moviepy/video/fx/lum_contrast.py b/moviepy/video/fx/lum_contrast.pydeleted file mode 100644index 4dd494f5..00000000--- a/moviepy/video/fx/lum_contrast.py+++ /dev/null@@ -1,11 +0,0 @@-def lum_contrast(clip, lum=0, contrast=0, contrast_threshold=127):- """Luminosity-contrast correction of a clip."""-- def image_filter(im):- im = 1.0 * im # float conversion- corrected = im + lum + contrast * (im - float(contrast_threshold))- corrected[corrected < 0] = 0- corrected[corrected > 255] = 255- return corrected.astype("uint8")-- return clip.image_transform(image_filter)diff --git a/moviepy/video/fx/make_loopable.py b/moviepy/video/fx/make_loopable.pydeleted file mode 100644index 65aeee82..00000000--- a/moviepy/video/fx/make_loopable.py+++ /dev/null@@ -1,20 +0,0 @@-import moviepy.video.compositing.transitions as transfx-from moviepy.decorators import requires_duration-from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip---@requires_duration-def make_loopable(clip, overlap_duration):- """Makes the clip fade in progressively at its own end, this way it can be- looped indefinitely.-- Parameters- ------------ overlap_duration : float- Duration of the fade-in (in seconds).- """- clip2 = clip.fx(transfx.crossfadein, overlap_duration).with_start(- clip.duration - overlap_duration- )- return CompositeVideoClip([clip, clip2]).with_subclip(overlap_duration, clip.duration)diff --git a/moviepy/video/fx/margin.py b/moviepy/video/fx/margin.pydeleted file mode 100644index bacba5b2..00000000--- a/moviepy/video/fx/margin.py+++ /dev/null@@ -1,76 +0,0 @@-import numpy as np--from moviepy.decorators import apply_to_mask-from moviepy.video.VideoClip import ImageClip---@apply_to_mask-def margin(- clip,- margin_size=None,- left=0,- right=0,- top=0,- bottom=0,- color=(0, 0, 0),- opacity=1.0,-):- """- Draws an external margin all around the frame.-- Parameters- ------------ margin_size : int, optional- If not ``None``, then the new clip has a margin size of- size ``margin_size`` in pixels on the left, right, top, and bottom.-- left : int, optional- If ``margin_size=None``, margin size for the new clip in left direction.-- right : int, optional- If ``margin_size=None``, margin size for the new clip in right direction.-- top : int, optional- If ``margin_size=None``, margin size for the new clip in top direction.-- bottom : int, optional- If ``margin_size=None``, margin size for the new clip in bottom direction.-- color : tuple, optional- Color of the margin.-- opacity : float, optional- Opacity of the margin. Setting this value to 0 yields transparent margins.- """- if (opacity != 1.0) and (clip.mask is None) and not (clip.is_mask):- clip = clip.with_add_mask()-- if margin_size is not None:- left = right = top = bottom = margin_size-- def make_bg(w, h):- new_w, new_h = w + left + right, h + top + bottom- if clip.is_mask:- shape = (new_h, new_w)- bg = np.tile(opacity, (new_h, new_w)).astype(float).reshape(shape)- else:- shape = (new_h, new_w, 3)- bg = np.tile(color, (new_h, new_w)).reshape(shape)- return bg-- if isinstance(clip, ImageClip):- im = make_bg(clip.w, clip.h)- im[top : top + clip.h, left : left + clip.w] = clip.img- return clip.image_transform(lambda pic: im)-- else:-- def filter(get_frame, t):- pic = get_frame(t)- h, w = pic.shape[:2]- im = make_bg(w, h)- im[top : top + h, left : left + w] = pic- return im-- return clip.transform(filter)diff --git a/moviepy/video/fx/mask_and.py b/moviepy/video/fx/mask_and.pydeleted file mode 100644index 8e61eb78..00000000--- a/moviepy/video/fx/mask_and.py+++ /dev/null@@ -1,35 +0,0 @@-import numpy as np--from moviepy.video.VideoClip import ImageClip---def mask_and(clip, other_clip):- """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.-- Parameters- ------------ other_clip ImageClip or np.ndarray- Clip used to mask the original clip.-- Examples- ---------- >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red- >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green- >>> masked_clip = clip.fx(mask_and, mask) # black- >>> masked_clip.get_frame(0)- [[[0 0 0]]]- """- # to ensure that 'and' of two ImageClips will be an ImageClip- if isinstance(other_clip, ImageClip):- other_clip = other_clip.img-- if isinstance(other_clip, np.ndarray):- return clip.image_transform(lambda frame: np.minimum(frame, other_clip))- else:- return clip.transform(- lambda get_frame, t: np.minimum(get_frame(t), other_clip.get_frame(t))- )diff --git a/moviepy/video/fx/mask_color.py b/moviepy/video/fx/mask_color.pydeleted file mode 100644index cc82e2f6..00000000--- a/moviepy/video/fx/mask_color.py+++ /dev/null@@ -1,34 +0,0 @@-import numpy as np---def mask_color(clip, color=None, threshold=0, stiffness=1):- """Returns a new clip with a mask for transparency where the original- 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-- 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``- """- if color is None:- color = [0, 0, 0]-- color = np.array(color)-- def hill(x):- if threshold:- return x**stiffness / (threshold**stiffness + x**stiffness)- else:- return 1.0 * (x != 0)-- def flim(im):- return hill(np.sqrt(((im - color) ** 2).sum(axis=2)))-- mask = clip.image_transform(flim)- mask.is_mask = True- new_clip = clip.with_mask(mask)- return new_clipdiff --git a/moviepy/video/fx/mask_or.py b/moviepy/video/fx/mask_or.pydeleted file mode 100644index b435ff65..00000000--- a/moviepy/video/fx/mask_or.py+++ /dev/null@@ -1,35 +0,0 @@-import numpy as np--from moviepy.video.VideoClip import ImageClip---def mask_or(clip, other_clip):- """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.-- Parameters- ------------ other_clip ImageClip or np.ndarray- Clip used to mask the original clip.-- Examples- ---------- >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red- >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green- >>> masked_clip = clip.fx(mask_or, mask) # yellow- >>> masked_clip.get_frame(0)- [[[255 255 0]]]- """- # to ensure that 'or' of two ImageClips will be an ImageClip- if isinstance(other_clip, ImageClip):- other_clip = other_clip.img-- if isinstance(other_clip, np.ndarray):- return clip.image_transform(lambda frame: np.maximum(frame, other_clip))- else:- return clip.transform(- lambda get_frame, t: np.maximum(get_frame(t), other_clip.get_frame(t))- )diff --git a/moviepy/video/fx/mirror_x.py b/moviepy/video/fx/mirror_x.pydeleted file mode 100644index e0779e84..00000000--- a/moviepy/video/fx/mirror_x.py+++ /dev/null@@ -1,3 +0,0 @@-def mirror_x(clip, apply_to="mask"):- """Flips the clip horizontally (and its mask too, by default)."""- return clip.image_transform(lambda img: img[:, ::-1], apply_to=apply_to)diff --git a/moviepy/video/fx/mirror_y.py b/moviepy/video/fx/mirror_y.pydeleted file mode 100644index fea9e2a3..00000000--- a/moviepy/video/fx/mirror_y.py+++ /dev/null@@ -1,3 +0,0 @@-def mirror_y(clip, apply_to="mask"):- """Flips the clip vertically (and its mask too, by default)."""- return clip.image_transform(lambda img: img[::-1], apply_to=apply_to)diff --git a/moviepy/video/fx/multiply_color.py b/moviepy/video/fx/multiply_color.pydeleted file mode 100644index 655268eb..00000000--- a/moviepy/video/fx/multiply_color.py+++ /dev/null@@ -1,12 +0,0 @@-import numpy as np---def multiply_color(clip, factor):- """- Multiplies the clip's colors by the given factor, can be used- to decrease or increase the clip's brightness (is that the- right word ?)- """- return clip.image_transform(- lambda frame: np.minimum(255, (factor * frame)).astype("uint8")- )diff --git a/moviepy/video/fx/multiply_speed.py b/moviepy/video/fx/multiply_speed.pydeleted file mode 100644index 0a6d3e42..00000000--- a/moviepy/video/fx/multiply_speed.py+++ /dev/null@@ -1,16 +0,0 @@-def multiply_speed(clip, factor=None, final_duration=None):- """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- the factor will be automatically computed. The same effect is applied to the clip's- audio and mask if any.- """- if final_duration:- factor = 1.0 * clip.duration / final_duration-- new_clip = clip.time_transform(lambda t: factor * t, apply_to=["mask", "audio"])-- if clip.duration is not None:- new_clip = new_clip.with_duration(1.0 * clip.duration / factor)-- return new_clipdiff --git a/moviepy/video/fx/painting.py b/moviepy/video/fx/painting.pydeleted file mode 100644index 92fd2904..00000000--- a/moviepy/video/fx/painting.py+++ /dev/null@@ -1,48 +0,0 @@-import numpy as np-from PIL import Image, ImageFilter--def to_painting(np_image, saturation=1.4, black=0.006):- """Transforms any photo into some kind of painting.-- Transforms any photo into some kind of painting. Saturation- tells at which point the colors of the result should be- flashy. ``black`` gives the amount of black lines wanted.-- np_image : a numpy image- """- image = Image.fromarray(np_image)- image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)--- # Convert the image to grayscale- grayscale_image = image.convert("L")-- # Find the image edges- edges_image = grayscale_image.filter(ImageFilter.FIND_EDGES)-- # Convert the edges image to a numpy array- edges = np.array(edges_image)-- # Create the darkening effect- darkening = black * (255 * np.dstack(3 * [edges]))-- # Apply the painting effect- painting = saturation * np.array(image) - darkening-- # Clip the pixel values to the valid range of 0-255- painting = np.maximum(0, np.minimum(255, painting))-- # Convert the pixel values to unsigned 8-bit integers- painting = painting.astype("uint8")-- return painting---def painting(clip, saturation=1.4, black=0.006):- """- Transforms any photo into some kind of painting. Saturation- tells at which point the colors of the result should be- flashy. ``black`` gives the amount of black lines wanted.- """- return clip.image_transform(lambda im: to_painting(im, saturation, black))-diff --git a/moviepy/video/fx/rotate.py b/moviepy/video/fx/rotate.pydeleted file mode 100644index f6190ab8..00000000--- a/moviepy/video/fx/rotate.py+++ /dev/null@@ -1,166 +0,0 @@-import math-import warnings--import numpy as np---try:- import PIL-- PIL_rotate_kwargs_supported = {- # [moviepy rotate argument name,- # PIL.rotate argument supported,- # minimum PIL version required]- "fillcolor": ["bg_color", False, (5, 2, 0)],- "center": ["center", False, (4, 0, 0)],- "translate": ["translate", False, (4, 0, 0)],- }-- if hasattr(PIL, "__version__"):- # check support for PIL.rotate arguments- PIL__version_info__ = tuple(int(n) for n in PIL.__version__ if n.isdigit())-- for PIL_rotate_kw_name, support_data in PIL_rotate_kwargs_supported.items():- if PIL__version_info__ >= support_data[2]:- PIL_rotate_kwargs_supported[PIL_rotate_kw_name][1] = True-- Image = PIL.Image--except ImportError: # pragma: no cover- Image = None---def rotate(- clip,- angle,- unit="deg",- resample="bicubic",- expand=True,- center=None,- translate=None,- bg_color=None,-):- """- 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``, the package ``pillow`` must be installed,- and there will be black borders. You can make them transparent with:-- >>> new_clip = clip.with_add_mask().rotate(72)-- Parameters- ------------ clip : VideoClip- A video clip.-- 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).-- 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.-- 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.-- bg_color : tuple, optional- An optional color for area outside the rotated image. Only has effect if- ``expand`` is true.- """- if Image:- try:- resample = {- "bilinear": Image.BILINEAR,- "nearest": Image.NEAREST,- "bicubic": Image.BICUBIC,- }[resample]- except KeyError:- raise ValueError(- "'resample' argument must be either 'bilinear', 'nearest' or 'bicubic'"- )-- if hasattr(angle, "__call__"):- get_angle = angle- else:- get_angle = lambda t: angle-- def filter(get_frame, t):- angle = get_angle(t)- im = get_frame(t)-- if unit == "rad":- angle = math.degrees(angle)-- angle %= 360- if not center and not translate and not bg_color:- if (angle == 0) and expand:- return im- if (angle == 90) and expand:- transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]- return np.transpose(im, axes=transpose)[::-1]- elif (angle == 270) and expand:- transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]- return np.transpose(im, axes=transpose)[:, ::-1]- elif (angle == 180) and expand:- return im[::-1, ::-1]-- if not Image:- raise ValueError(- 'Without "Pillow" installed, only angles that are a multiple of 90'- " without centering, translation and background color transformations"- ' are supported, please install "Pillow" with `pip install pillow`'- )-- # build PIL.rotate kwargs- kwargs, _locals = ({}, locals())- for PIL_rotate_kw_name, (- kw_name,- supported,- min_version,- ) in PIL_rotate_kwargs_supported.items():- # get the value passed to rotate FX from `locals()` dictionary- kw_value = _locals[kw_name]-- if supported: # if argument supported by PIL version- kwargs[PIL_rotate_kw_name] = kw_value- else:- if kw_value is not None: # if not default value- warnings.warn(- f"rotate '{kw_name}' argument is not supported"- " by your Pillow version and is being ignored. Minimum"- " Pillow version required:"- f" v{'.'.join(str(n) for n in min_version)}",- UserWarning,- )-- # PIL expects uint8 type data. However a mask image has values in the- # range [0, 1] and is of float type. To handle this we scale it up by- # a factor 'a' for use with PIL and then back again by 'a' afterwards.- if im.dtype == "float64":- # this is a mask image- a = 255.0- else:- a = 1-- # call PIL.rotate- return (- np.array(- Image.fromarray(np.array(a * im).astype(np.uint8)).rotate(- angle, expand=expand, resample=resample, **kwargs- )- )- / a- )-- return clip.transform(filter, apply_to=["mask"])diff --git a/moviepy/video/fx/scroll.py b/moviepy/video/fx/scroll.pydeleted file mode 100644index ea70d114..00000000--- a/moviepy/video/fx/scroll.py+++ /dev/null@@ -1,34 +0,0 @@-def scroll(- clip, 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-- Parameters- ------------ w, h- The width and height of the final clip. Default to clip.w and clip.h-- x_speed, y_speed-- x_start, y_start--- apply_to-- """- if h is None:- h = clip.h- if w is None:- w = clip.w-- x_max = w - 1- y_max = h - 1-- def filter(get_frame, t):- x = int(max(0, min(x_max, x_start + round(x_speed * t))))- y = int(max(0, min(y_max, y_start + round(y_speed * t))))- return get_frame(t)[y : y + h, x : x + w]-- return clip.transform(filter, apply_to=apply_to)diff --git a/moviepy/video/fx/supersample.py b/moviepy/video/fx/supersample.pydeleted file mode 100644index c622d819..00000000--- a/moviepy/video/fx/supersample.py+++ /dev/null@@ -1,16 +0,0 @@-import numpy as np---def supersample(clip, d, n_frames):- """Replaces each frame at time t by the mean of `n_frames` equally spaced frames- taken in the interval [t-d, t+d]. This results in motion blur.- """-- def filter(get_frame, t):- timings = np.linspace(t - d, t + d, n_frames)- frame_average = np.mean(- 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/time_mirror.py b/moviepy/video/fx/time_mirror.pydeleted file mode 100644index 93e1d521..00000000--- a/moviepy/video/fx/time_mirror.py+++ /dev/null@@ -1,13 +0,0 @@-from moviepy.decorators import apply_to_audio, apply_to_mask, requires_duration---@requires_duration-@apply_to_mask-@apply_to_audio-def time_mirror(clip):- """- Returns a clip that plays the current clip backwards.- The clip must have its ``duration`` attribute set.- The same effect is applied to the clip's audio and mask if any.- """- return clip[::-1]diff --git a/moviepy/video/fx/time_symmetrize.py b/moviepy/video/fx/time_symmetrize.pydeleted file mode 100644index 65cfdf51..00000000--- a/moviepy/video/fx/time_symmetrize.py+++ /dev/null@@ -1,13 +0,0 @@-from moviepy.decorators import requires_duration---@requires_duration-def time_symmetrize(clip):- """- Returns a clip that plays the current clip once forwards and- then once backwards. This is very practival to make video that- loop well, e.g. to create animated GIFs.- This effect is automatically applied to the clip's mask and audio- if they exist.- """- return clip + clip[::-1]diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex cbae415a..f53df14d 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -133,6 +133,8 @@ class FFMPEG_VideoWriter:cmd.extend(["-pix_fmt", "yuv420p"])cmd.extend([filename])+ print(' '.join(cmd))+popen_params = cross_platform_popen_params({"stdout": sp.DEVNULL, "stderr": logfile, "stdin": sp.PIPE})diff --git a/moviepy/video/tools/credits.py b/moviepy/video/tools/credits.pyindex f5b04025..b7d58798 100644--- a/moviepy/video/tools/credits.py+++ b/moviepy/video/tools/credits.py@@ -3,7 +3,7 @@ difficult to fill everyone needs in this matter."""from moviepy.decorators import convert_path_to_stringfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip-from moviepy.video.fx.resize import resize+from moviepy.video.fx.Resize import Resizefrom moviepy.video.VideoClip import ImageClip, TextClip@@ -132,7 +132,7 @@ class CreditsClip(TextClip):)# Scale to the required size- scaled = resize(both_columns, width=width)+ scaled = both_columns.with_effect(Resize(width=width))# Transform the CompositeVideoClip into an ImageClip