Video editing with Python
More tests cleanup
Mark Beacomb0be36b0f41f
diff --git a/.gitignore b/.gitignoreindex 805b40e9..9f7132ca 100644--- a/.gitignore+++ b/.gitignore@@ -20,6 +20,7 @@ develop-eggsliblib64__pycache__+.cache/# Sublime.sublime-projectdiff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 5b0f6626..bd231e21 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -4,44 +4,27 @@ main subclasses:- Animated clips: VideofileClip, ImageSequenceClip- Static image clips: ImageClip, ColorClip, TextClip,"""-import osimport subprocess as sp-import multiprocessingimport tempfile-from copy import copyimport warnings-from tqdm import tqdmimport numpy as np-from imageio import imread, imsave+from tqdm import tqdm-import moviepy.audio.io as aio-from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video-from .io.ffmpeg_tools import ffmpeg_merge_video_audio-from .io.gif_writers import (write_gif,- write_gif_with_tempfiles,- write_gif_with_image_io)-from .tools.drawing import blitfrom ..Clip import Clip+from ..compat import DEVNULL, PY3from ..config import get_setting--from ..tools import (subprocess_call,- verbose_print,- is_string,- deprecated_version_of,- extensions_dict, find_extension)--from ..decorators import (apply_to_mask,- requires_duration,- outplace,- add_mask_if_none,- convert_to_seconds,- convert_masks_to_RGB,- use_clip_fps_by_default)--from ..compat import PY3, DEVNULL+from ..decorators import (add_mask_if_none, apply_to_mask,+ convert_masks_to_RGB, convert_to_seconds, outplace,+ requires_duration, use_clip_fps_by_default)+from ..tools import (deprecated_version_of, extensions_dict, find_extension,+ is_string, subprocess_call, verbose_print)+from .io.ffmpeg_writer import ffmpeg_write_video+from .io.gif_writers import (write_gif, write_gif_with_image_io,+ write_gif_with_tempfiles)+from .tools.drawing import blitclass VideoClip(Clip):@@ -107,26 +90,21 @@ class VideoClip(Clip):self.duration = durationself.end = duration-@propertydef w(self):return self.size[0]-@propertydef h(self):return self.size[1]-@propertydef aspect_ratio(self):return self.w / float(self.h)-# ===============================================================# EXPORT OPERATIONS-@convert_to_seconds(['t'])@convert_masks_to_RGBdef save_frame(self, filename, t=0, withmask=True):@@ -151,7 +129,6 @@ class VideoClip(Clip):imsave(filename, im)-@requires_duration@use_clip_fps_by_default@convert_masks_to_RGB@@ -165,7 +142,6 @@ class VideoClip(Clip):write_logfile=False, verbose=True,threads=None, ffmpeg_params=None,progress_bar=True):-"""Write the clip to a videofile.Parameters@@ -261,7 +237,7 @@ class VideoClip(Clip):If true, will write log files for the audio and the video.These will be files ending with '.log' with the name of theoutput file in them.-+verboseBoolean indicating whether to print infomation@@ -276,7 +252,6 @@ class VideoClip(Clip):>>> clip.write_videofile("my_new_video.mp4")"""-name, ext = os.path.splitext(os.path.basename(filename))ext = ext[1:].lower()@@ -353,7 +328,6 @@ class VideoClip(Clip):verbose_print(verbose, "[MoviePy] >>>> Video ready: %s \n\n"%filename)-@requires_duration@use_clip_fps_by_default@convert_masks_to_RGB@@ -361,7 +335,6 @@ class VideoClip(Clip):withmask=True, progress_bar=True):""" Writes the videoclip to a sequence of image files.-Parameters-----------@@ -399,7 +372,6 @@ class VideoClip(Clip):``ImageSequenceClip``."""-verbose_print(verbose, "[MoviePy] Writing frames %s." % (nameformat))tt = np.arange(0, self.duration, 1.0 / fps)@@ -416,8 +388,6 @@ class VideoClip(Clip):return filenames--@requires_duration@convert_masks_to_RGBdef write_gif(self, filename, fps=None, program='imageio',@@ -428,7 +398,6 @@ class VideoClip(Clip):Converts a VideoClip into an animated GIF using ImageMagickor ffmpeg.-Parameters-----------@@ -466,7 +435,6 @@ class VideoClip(Clip):>>> myClip.speedx(0.5).to_gif('myClip.gif')"""-# A little sketchy at the moment, maybe move all that in write_gif,# refactor a little... we will see.@@ -493,10 +461,8 @@ class VideoClip(Clip):# -----------------------------------------------------------------# F I L T E R I N G--def subfx(self, fx, ta=0, tb=None, **kwargs):- """ Apply a transformation to a part of the clip.+ """Apply a transformation to a part of the clip.Returns a new clip in which the function ``fun`` (clip->clip)has been applied to the subclip between times `ta` and `tb`@@ -510,7 +476,6 @@ class VideoClip(Clip):>>> newclip = clip.subapply(lambda c:c.speedx(0.5) , 3,6)"""-left = None if (ta == 0) else self.subclip(0, ta)center = self.subclip(ta, tb).fx(fx, **kwargs)right = None if (tb is None) else self.subclip(t_start=tb)@@ -524,7 +489,6 @@ class VideoClip(Clip):# IMAGE FILTERS-def fl_image(self, image_func, apply_to=[]):"""Modifies the images of a clip by replacing the frame@@ -535,7 +499,6 @@ class VideoClip(Clip):# --------------------------------------------------------------# C O M P O S I T I N G-def fill_array(self, pre_array, shape=(0, 0)):pre_shape = pre_array.shapedx = shape[0] - pre_shape[0]@@ -553,14 +516,12 @@ class VideoClip(Clip):post_array = np.hstack((post_array, x_1))return post_array-def blit_on(self, picture, t):"""Returns the result of the blit of the clip's frame at time `t`on the given `picture`, the position of the clip being givenby the clip's ``pos`` attribute. Meant for compositing."""-hf, wf = framesize = picture.shape[:2]if self.ismask and picture.max() != 0:@@ -610,9 +571,8 @@ class VideoClip(Clip):return blit(img, picture, pos, mask=mask, ismask=self.ismask)-def add_mask(self):- """ Add a mask VideoClip to the VideoClip.+ """Add a mask VideoClip to the VideoClip.Returns a copy of the clip with a completely opaque mask(made of ones). This makes computations slower compared to@@ -629,10 +589,9 @@ class VideoClip(Clip):mask = VideoClip(ismask=True, make_frame=make_frame)return self.set_mask(mask.set_duration(self.duration))-def on_color(self, size=None, color=(0, 0, 0), pos=None,col_opacity=None):- """ Place the clip on a colored background.+ """Place the clip on a colored background.Returns a clip made of the current clip overlaid on a colorclip of a possibly bigger size. Can serve to flatten transparent@@ -682,10 +641,9 @@ class VideoClip(Clip):return result-@outplacedef set_make_frame(self, mf):- """ Change the clip's ``get_frame``.+ """Change the clip's ``get_frame``.Returns a copy of the VideoClip instance, with the make_frameattribute set to `mf`.@@ -693,43 +651,39 @@ class VideoClip(Clip):self.make_frame = mfself.size = self.get_frame(0).shape[:2][::-1]-@outplacedef set_audio(self, audioclip):- """ Attach an AudioClip to the VideoClip.+ """Attach an AudioClip to the VideoClip.Returns a copy of the VideoClip instance, with the `audio`attribute set to ``audio``, which must be an AudioClip instance."""self.audio = audioclip-@outplacedef set_mask(self, mask):- """ Set the clip's mask.+ """Set the clip's mask.Returns a copy of the VideoClip with the mask attribute set to``mask``, which must be a greyscale (values in 0-1) VideoClip"""assert ( (mask is None) or mask.ismask )self.mask = mask-@add_mask_if_none@outplacedef set_opacity(self, op):- """ Set the opacity/transparency level of the clip.+ """Set the opacity/transparency level of the clip.Returns a semi-transparent copy of the clip where the mask ismultiplied by ``op`` (any float, normally between 0 and 1)."""-self.mask = self.mask.fl_image(lambda pic: op * pic)@apply_to_mask@outplacedef set_position(self, pos, relative=False):- """ Set the clip's position in compositions.+ """Set the clip's position in compositions.Sets the position that the clip will have when includedin compositions. The argument ``pos`` can be either a couple@@ -752,19 +706,15 @@ class VideoClip(Clip):>>> clip.set_pos(lambda t: ('center', 50+t) )"""-self.relative_pos = relativeif hasattr(pos, '__call__'):self.pos = poselse:self.pos = lambda t: pos-#--------------------------------------------------------------# CONVERSIONS TO OTHER TYPES--@convert_to_seconds(['t'])def to_ImageClip(self, t=0, with_mask=True):"""@@ -779,9 +729,7 @@ class VideoClip(Clip):def to_mask(self, canal=0):- """- Returns a mask a video clip made from the clip.- """+ """Return a mask a video clip made from the clip."""if self.ismask:return selfelse:@@ -790,11 +738,8 @@ class VideoClip(Clip):newclip.ismask = Truereturn newclip-def to_RGB(self):- """- Returns a non-mask video clip made from the mask video clip.- """+ """Return a non-mask video clip made from the mask video clip."""if self.ismask:f = lambda pic: np.dstack(3 * [255 * pic]).astype('uint8')newclip = self.fl_image(f)@@ -806,20 +751,18 @@ class VideoClip(Clip):#----------------------------------------------------------------# Audio-@outplacedef without_audio(self):- """ Remove the clip's audio.+ """Remove the clip's audio.Return a copy of the clip with audio set to None."""self.audio = None-@outplacedef afx(self, fun, *a, **k):- """ Transform the clip's audio.+ """Transform the clip's audio.Return a new clip whose audio has been transformed by ``fun``.@@ -827,7 +770,6 @@ class VideoClip(Clip):self.audio = self.audio.fx(fun, *a, **k)-class DataVideoClip(VideoClip):"""Class of video clips whose successive frames are functions@@ -858,11 +800,8 @@ class DataVideoClip(VideoClip):duration=1.0*len(data)/fps, has_constant_size=has_constant_size)--class UpdatedVideoClip(VideoClip):"""-Class of clips whose make_frame requires some objects tobe updated. Particularly practical in science where somealgorithm needs to make some steps before a new frame can@@ -894,9 +833,7 @@ class UpdatedVideoClip(VideoClip):"""-def __init__(self, world, ismask=False, duration=None):-self.world = worlddef make_frame(t):while self.world.clip_t < t:@@ -906,10 +843,6 @@ class UpdatedVideoClip(VideoClip):ismask=ismask, duration=duration)----"""---------------------------------------------------------------------ImageClip (base class for all 'static clips') and its subclasses@@ -921,7 +854,7 @@ class UpdatedVideoClip(VideoClip):class ImageClip(VideoClip):- """ Class for non-moving VideoClips.+ """Class for non-moving VideoClips.A video clip originating from a picture. This clip will simplydisplay the given picture at all times.@@ -954,10 +887,8 @@ class ImageClip(VideoClip):"""-def __init__(self, img, ismask=False, transparent=True,fromalpha=False, duration=None):-VideoClip.__init__(self, ismask=ismask, duration=duration)if PY3:@@ -987,14 +918,12 @@ class ImageClip(VideoClip):self.size = img.shape[:2][::-1]self.img = img-def fl(self, fl, apply_to=[], keep_duration=True):- """ General transformation filter.+ """General transformation filter.Equivalent to VideoClip.fl . The result is no more anImageClip, it has the class VideoClip (since it may be animated)"""-# When we use fl on an image clip it may become animated.# Therefore the result is not an ImageClip, just a VideoClip.newclip = VideoClip.fl(self, fl, apply_to=apply_to,@@ -1002,16 +931,14 @@ class ImageClip(VideoClip):newclip.__class__ = VideoClipreturn newclip-@outplacedef fl_image(self, image_func, apply_to=[]):- """ Image-transformation filter.+ """Image-transformation filter.Does the same as VideoClip.fl_image, but for ImageClip thetranformed clip is computed once and for all at the beginning,and not for each 'frame'."""-arr = image_func(self.get_frame(0))self.size = arr.shape[:2][::-1]self.make_frame = lambda t: arr@@ -1024,11 +951,10 @@ class ImageClip(VideoClip):new_a = a.fl_image(image_func)setattr(self, attr, new_a)-@outplacedef fl_time(self, time_func, apply_to=['mask', 'audio'],keep_duration=False):- """ Time-transformation filter.+ """Time-transformation filter.Applies a transformation to the clip's timeline(see Clip.fl_time).@@ -1036,7 +962,6 @@ class ImageClip(VideoClip):This method does nothing for ImageClips (but it may affect theirmasks or their audios). The result is still an ImageClip."""-for attr in apply_to:if hasattr(self, attr):a = getattr(self, attr)@@ -1060,7 +985,7 @@ VideoClip.to_images_sequence = deprecated_version_of(VideoClip.write_images_sequclass ColorClip(ImageClip):- """ An ImageClip showing just one color.+ """An ImageClip showing just one color.Parameters-----------@@ -1083,7 +1008,7 @@ class ColorClip(ImageClip):def __init__(self, size, color=None, ismask=False, duration=None, col=None):if col is not None:warnings.warn("The `ColorClip` parameter `col` has been deprecated."- " Please use `color` instead", DeprecationWarning)+ " Please use `color` instead.", DeprecationWarning)if color is not None:warnings.warn("The arguments `color` and `col` have both been ""passed to `ColorClip` so `col` has been ignored.",@@ -1097,7 +1022,7 @@ 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.Requires ImageMagick.@@ -1160,7 +1085,6 @@ class TextClip(ImageClip):"""-def __init__(self, txt=None, filename=None, size=None, color='black',bg_color='transparent', fontsize=None, font='Courier',stroke_color=None, stroke_width=1, method='label',@@ -1169,7 +1093,6 @@ class TextClip(ImageClip):transparent=True, remove_temp=True,print_cmd=False):-if txt is not None:if temptxt is None:temptxt_fd, temptxt = tempfile.mkstemp(suffix='.txt')@@ -1239,10 +1162,9 @@ class TextClip(ImageClip):if os.path.exists(temptxt):os.remove(temptxt)-@staticmethoddef list(arg):- """ Returns the list of all valid entries for the argument of+ """Returns the list of all valid entries for the argument of``TextClip`` given (can be ``font``, ``color``, etc...) """popen_params = {"stdout": sp.PIPE,@@ -1267,7 +1189,7 @@ class TextClip(ImageClip):@staticmethoddef search(string, arg):- """ Returns the of all valid entries which contain ``string`` for the+ """Returns the of all valid entries which contain ``string`` for theargument ``arg`` of ``TextClip``, for instance>>> # Find all the available fonts which contain "Courier"diff --git a/tests/download_media.py b/tests/download_media.pyindex 0cc75d29..a9a10981 100644--- a/tests/download_media.py+++ b/tests/download_media.py@@ -1,53 +1,42 @@+# -*- coding: utf-8 -*-+"""Handle retrieving media assets for testing."""import os-from moviepy.editor import *+from moviepy.video.io.downloader import download_webfile+def download_url(url, filename):+ """Download a file."""if not os.path.exists(filename):- print("\nDownloading %s\n" % filename)+ print('\nDownloading {}\n'.format(filename))download_webfile(url, filename)- print("Downloading complete...\n")+ print('Downloading complete...\n')def download_youtube_video(youtube_id, filename):+ """Download a video from youtube."""# FYI.. travis-ci doesn't like youtube-dldownload_url(youtube_id, filename)def download():- if not os.path.exists("media"):- os.mkdir("media")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/images/python_logo.png",- "media/python_logo.png")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/images/matplotlib_demo1.png",- "media/matplotlib_demo1.png")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/images/afterimage.png",- "media/afterimage.png")-- download_url("https://github.com/earney/moviepy_media/blob/master/tests/videos/big_buck_bunny_0_30.webm?raw=true",- "media/big_buck_bunny_0_30.webm")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/videos/big_buck_bunny_432_433.webm",- "media/big_buck_bunny_432_433.webm")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/sounds/crunching.mp3",- "media/crunching.mp3")-- download_url("https://raw.githubusercontent.com/earney/moviepy_media/master/tests/subtitles/subtitles1.srt",- "media/subtitles1.srt")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/images/pigs_in_a_polka.gif",- "media/pigs_in_a_polka.gif")-- download_url("https://data.vision.ee.ethz.ch/cvl/video2gif/kAKZeIzs0Ag.mp4",- "media/video_with_failing_audio.mp4")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/videos/fire2.mp4",- "media/fire2.mp4")-- download_url("https://raw.githubusercontent.com/earney/moviepy_media/master/tests/misc/traj.txt",- "media/traj.txt")-- download_url("https://github.com/earney/moviepy_media/raw/master/tests/images/vacation_2017.jpg",- "media/vacation_2017.jpg")\ No newline at end of file+ """Initiate the media asset downloads."""+ if not os.path.exists('media'):+ os.mkdir('media')++ # Define url prefix and path for all media assets.+ github_prefix = 'https://github.com/earney/moviepy_media/raw/master/tests/'+ output = 'media/{}'+ urls = ['/images/python_logo.png', '/images/matplotlib_demo1.png',+ '/images/afterimage.png', '/videos/big_buck_bunny_432_433.webm',+ '/sounds/crunching.mp3', '/images/pigs_in_a_polka.gif',+ '/videos/fire2.mp4', '/videos/big_buck_bunny_0_30.webm',+ '/subtitles/subtitles1.srt', '/misc/traj.txt',+ '/images/vacation_2017.jpg']++ # Loop through download url strings, build out path, and download the asset.+ for url in urls:+ _, tail = os.path.split(url)+ download_url('{}/{}'.format(github_prefix, url), output.format(tail))++ # Download remaining asset.+ download_url('https://data.vision.ee.ethz.ch/cvl/video2gif/kAKZeIzs0Ag.mp4',+ 'media/video_with_failing_audio.mp4')diff --git a/tests/test_PR.py b/tests/test_PR.pyindex aba1c3e5..668161b3 100644--- a/tests/test_PR.py+++ b/tests/test_PR.py@@ -1,21 +1,22 @@-"""-Tests meant to be run with pytest-"""--import sys+# -*- coding: utf-8 -*-+"""Pull request tests meant to be run with pytest."""import os-import pytest--from moviepy.editor import *+import sys+import pytest+from moviepy.video.fx.scroll import scroll+from moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.tools.interpolators import Trajectory+from moviepy.video.VideoClip import ColorClip, ImageClip, TextClip++from test_helper import TMP_DIR, TRAVIS-import syssys.path.append("tests")-import download_media-from test_helper import PYTHON_VERSION, TMP_DIR, TRAVIS+def test_download_media(capsys):+ """Test downloading."""+ import download_mediawith capsys.disabled():download_media.download()@@ -30,22 +31,16 @@ def test_PR_306():with pytest.raises(Exception, message="Expecting Exception"):TextClip.list('blah')-def test_PR_339():if TRAVIS:return- #in caption mode- overlay = TextClip(txt='foo',- color='white', font="Liberation-Mono",- size=(640, 480),- method='caption',- align='center',- fontsize=25)-- #in_label_mode- overlay = TextClip(txt='foo', font="Liberation-Mono", method='label')+ # In caption mode.+ TextClip(txt='foo', color='white', font="Liberation-Mono", size=(640, 480),+ method='caption', align='center', fontsize=25)+ # In label mode.+ TextClip(txt='foo', font="Liberation-Mono", method='label')def test_PR_373():result = Trajectory.load_list("media/traj.txt")@@ -66,22 +61,38 @@ def test_PR_373():for i in range(len(result[0].yy)):assert result[0].yy[i] == result1[0].yy[i]-def test_PR_424():+ """Ensure deprecation and user warnings are triggered."""+ import warnings+ warnings.simplefilter('always') # Alert us of deprecation warnings.+# Recommended use- clip = ColorClip([1000, 600], color=(60, 60, 60), duration=10)- # Uses `col` so should work the same as above, but give warning- clip = ColorClip([1000, 600], col=(60, 60, 60), duration=10)- # Should give 2 warnings and use `color`, not `col`- clip = ColorClip([1000, 600], color=(60, 60, 60), duration=10, col=(2,2,2))+ ColorClip([1000, 600], color=(60, 60, 60), duration=10)++ with pytest.warns(DeprecationWarning):+ # Uses `col` so should work the same as above, but give warning.+ ColorClip([1000, 600], col=(60, 60, 60), duration=10)+ # Catch all warnings as record.+ with pytest.warns(None) as record:+ # Should give 2 warnings and use `color`, not `col`+ ColorClip([1000, 600], color=(60, 60, 60), duration=10, col=(2,2,2))++ message1 = 'The `ColorClip` parameter `col` has been deprecated. ' + \+ 'Please use `color` instead.'+ message2 = 'The arguments `color` and `col` have both been passed to ' + \+ '`ColorClip` so `col` has been ignored.'++ # Assert that two warnings popped and validate the message text.+ assert len(record) == 2+ assert str(record[0].message) == message1+ assert str(record[1].message) == message2def test_PR_458():clip = ColorClip([1000, 600], color=(60, 60, 60), duration=10)clip.write_videofile(os.path.join(TMP_DIR, "test.mp4"),progress_bar=False, fps=30)-def test_PR_515():# Won't actually work until video is in download_mediaclip = VideoFileClip("media/fire2.mp4", fps_source='tbr')@@ -89,18 +100,18 @@ def test_PR_515():clip = VideoFileClip("media/fire2.mp4", fps_source='fps')assert clip.fps == 10.51-+def test_PR_528():clip = ImageClip("media/vacation_2017.jpg")- new_clip = vfx.scroll(clip, w=1000, x_speed=50)+ new_clip = scroll(clip, w=1000, x_speed=50)new_clip = new_clip.set_duration(20)new_clip.fps = 24new_clip.write_videofile(os.path.join(TMP_DIR, "pano.mp4"))-+def test_PR_529():video_clip = VideoFileClip("media/fire2.mp4")- assert video_clip.rotation ==180+ assert video_clip.rotation == 180if __name__ == '__main__':diff --git a/tests/test_compositing.py b/tests/test_compositing.pyindex a1f4bd52..49504ca7 100644--- a/tests/test_compositing.py+++ b/tests/test_compositing.py@@ -1,5 +1,9 @@+# -*- coding: utf-8 -*-+"""Compositing tests for use with pytest."""import pytest-from moviepy.editor import *+from moviepy.video.compositing.CompositeVideoClip import clips_array+from moviepy.video.VideoClip import ColorClip+def test_clips_array():red = ColorClip((1024,800), color=(255,0,0))@@ -12,8 +16,7 @@ def test_clips_array():message="Expecting ValueError (duration not set)"):video.resize(width=480).write_videofile("/tmp/test_clips_array.mp4")--def test_clips_array():+def test_clips_array_duration():red = ColorClip((1024,800), color=(255,0,0))green = ColorClip((1024,800), color=(0,255,0))blue = ColorClip((1024,800), color=(0,0,255))diff --git a/tests/test_examples.py b/tests/test_examples.pyindex b9bc5235..87ee3cf6 100644--- a/tests/test_examples.py+++ b/tests/test_examples.py@@ -1,3 +1,5 @@+# -*- coding: utf-8 -*-+"""Example tests for use with pytest."""import osimport sys@@ -21,8 +23,8 @@ def test_matplotlib():import matplotlib.pyplot as pltimport numpy as np- from moviepy.editor import VideoClipfrom moviepy.video.io.bindings import mplfig_to_npimage+ from moviepy.video.VideoClip import VideoClipx = np.linspace(-2, 2, 200)