Video editing with Python
Improve code format and readability (#1077)
Martín Gaitánf22e663e6e90
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dc1a4be1..a326a159 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -91,7 +91,7 @@- New version of imageio with imageio\_ffmpeg for python 3.4+ [\#907](https://github.com/Zulko/moviepy/pull/907) ([Zulko](https://github.com/Zulko))- fix typo that introduces audio regression [\#894](https://github.com/Zulko/moviepy/pull/894) ([chrox](https://github.com/chrox))-- fixing the git remote syntax in documentions [\#887](https://github.com/Zulko/moviepy/pull/887) ([ishandutta2007](https://github.com/ishandutta2007))+- fixing the git remote syntax in documentations [\#887](https://github.com/Zulko/moviepy/pull/887) ([ishandutta2007](https://github.com/ishandutta2007))- modified max duration error for better understanding [\#875](https://github.com/Zulko/moviepy/pull/875) ([kapilkd13](https://github.com/kapilkd13))- Fixed typo in docstring for VideoClip class [\#871](https://github.com/Zulko/moviepy/pull/871) ([Armcollector](https://github.com/Armcollector))- Fix a small typing error [\#845](https://github.com/Zulko/moviepy/pull/845) ([yuvallanger](https://github.com/yuvallanger))diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex 315024b4..24bc3b2c 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -143,11 +143,10 @@ class Clip:apply_to = [apply_to]for attr in apply_to:- if hasattr(newclip, attr):- a = getattr(newclip, attr)- if a is not None:- new_a = a.fl(fun, keep_duration=keep_duration)- setattr(newclip, attr, new_a)+ a = getattr(newclip, attr, None)+ if a is not None:+ new_a = a.fl(fun, keep_duration=keep_duration)+ setattr(newclip, attr, new_a)return newclipdiff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex 8fd7b9f6..122d9b2e 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -318,10 +318,6 @@ def concatenate_audioclips(clips):result = CompositeAudioClip(newclips).set_duration(tt[-1])- fpss = [c.fps for c in clips if hasattr(c, 'fps') and c.fps is not None]- if len(fpss) == 0:- result.fps = None- else:- result.fps = max(fpss)-+ fpss = [c.fps for c in clips if getattr(c, 'fps', None)]+ result.fps = max(fpss) if fpss else Nonereturn resultdiff --git a/moviepy/decorators.py b/moviepy/decorators.pyindex 44f346eb..277276ca 100644--- a/moviepy/decorators.py+++ b/moviepy/decorators.py@@ -27,7 +27,7 @@ def apply_to_mask(f, clip, *a, **k):the clip created with f """newclip = f(clip, *a, **k)- if hasattr(newclip, 'mask') and (newclip.mask is not None):+ if getattr(newclip, 'mask', None):newclip.mask = f(newclip.mask, *a, **k)return newclip@@ -39,7 +39,7 @@ def apply_to_audio(f, clip, *a, **k):the clip created with f """newclip = f(clip, *a, **k)- if hasattr(newclip, 'audio') and (newclip.audio is not None):+ if getattr(newclip, 'audio', None):newclip.audio = f(newclip.audio, *a, **k)return newclip@@ -112,14 +112,12 @@ def use_clip_fps_by_default(f, clip, *a, **k):def fun(fps):if fps is not None:return fps- else:- if hasattr(clip, 'fps') and clip.fps is not None:- return clip.fps- else:- raise AttributeError("No 'fps' (frames per second) attribute specified"+ elif getattr(clip, 'fps', None):+ return clip.fps+ raise AttributeError("No 'fps' (frames per second) attribute specified"" for function %s and the clip has no 'fps' attribute. Either"" provide e.g. fps=24 in the arguments of the function, or define"- " the clip's fps with `clip.fps=24`"%f.__name__)+ " the clip's fps with `clip.fps=24`" % f.__name__)if hasattr(f, "func_code"):diff --git a/moviepy/tools.py b/moviepy/tools.pyindex e5e6b9cf..5357c3a6 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -1,9 +1,7 @@"""Misc. useful functions that can be used at many places in the program."""-import os-import reimport subprocess as spimport sysimport warnings@@ -13,6 +11,7 @@ import proglogfrom .compat import DEVNULL+def sys_write_flush(s):""" Writes and flushes without delay a text in the console """# Reason for not using `print` is that in some consoles "print"@@ -66,39 +65,41 @@ def is_string(obj):except NameError:return isinstance(obj, str)+def cvsecs(time):- """ Will convert any time into seconds.- Here are the accepted formats:-- >>> cvsecs(15.4) -> 15.4 # seconds- >>> cvsecs( (1,21.5) ) -> 81.5 # (min,sec)- >>> cvsecs( (1,1,2) ) -> 3662 # (hr, min, sec)- >>> cvsecs('01:01:33.5') -> 3693.5 #(hr,min,sec)- >>> cvsecs('01:01:33.045') -> 3693.045- >>> cvsecs('01:01:33,5') #coma works too+ """ Will convert any time into seconds.++ If the type of `time` is not valid,+ it's returned as is.++ Here are the accepted formats::++ >>> cvsecs(15.4) # seconds+ 15.4+ >>> cvsecs((1, 21.5)) # (min,sec)+ 81.5+ >>> cvsecs((1, 1, 2)) # (hr, min, sec)+ 3662+ >>> cvsecs('01:01:33.045')+ 3693.045+ >>> cvsecs('01:01:33,5') # coma works too+ 3693.5+ >>> cvsecs('1:33,5') # only minutes and secs+ 99.5+ >>> cvsecs('33.5') # only secs+ 33.5"""+ factors = (1, 60, 3600)++ if is_string(time):+ time = [float(f.replace(',', '.')) for f in time.split(':')]- if is_string(time):- if (',' not in time) and ('.' not in time):- time = time + '.0'- expr = r"(\d+):(\d+):(\d+)[,|.](\d+)"- finds = re.findall(expr, time)[0]- nums = list( map(float, finds) )- return ( 3600*int(finds[0])- + 60*int(finds[1])- + int(finds[2])- + nums[3]/(10**len(finds[3])))-- elif isinstance(time, tuple):- if len(time)== 3:- hr, mn, sec = time- elif len(time)== 2:- hr, mn, sec = 0, time[0], time[1]- return 3600*hr + 60*mn + sec-- else:+ if not isinstance(time, (tuple, list)):return time+ return sum(mult * part for mult, part in zip(factors, reversed(time)))++def deprecated_version_of(f, oldname, newname=None):""" Indicates that a function is deprecated and has a new name.@@ -159,8 +160,18 @@ extensions_dict = { "mp4": {'type':'video', 'codec':['libx264','libmpeg4', 'aacfor ext in ["jpg", "jpeg", "png", "bmp", "tiff"]:extensions_dict[ext] = {'type':'image'}+def find_extension(codec):+ if codec in extensions_dict:+ # codec is already the extension+ return codec+for ext,infos in extensions_dict.items():- if ('codec' in infos) and codec in infos['codec']:+ if codec in infos.get('codec', []):return ext- raise ValueError+ raise ValueError(+ "The audio_codec you chose is unknown by MoviePy. "+ "You should report this. In the meantime, you can "+ "specify a temp_audiofile with the right extension "+ "in write_videofile."+ )diff --git a/moviepy/utils.py b/moviepy/utils.pyindex 5979ccbc..705cb495 100644--- a/moviepy/utils.py+++ b/moviepy/utils.py@@ -3,17 +3,18 @@ from moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.VideoClip import ImageClip+CLIP_TYPES = {+ 'audio': AudioFileClip,+ 'video': VideoFileClip,+ 'image': ImageClip,+}+def close_all_clips(objects='globals', types=('audio', 'video', 'image')):if objects == 'globals':objects = globals()if hasattr(objects, 'values'):objects = objects.values()- types_tuple = tuple([- {'audio': AudioFileClip,- 'video': VideoFileClip,- 'image': ImageClip}[t]- for t in types- ])+ types_tuple = tuple(CLIP_TYPES[key] for key in types)for obj in objects:if isinstance(obj, types_tuple):obj.close()diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 667c985f..d19d2535 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -81,7 +81,7 @@ class VideoClip(Clip):self.audio = Noneself.pos = lambda t: (0, 0)self.relative_pos = False- if make_frame is not None:+ if make_frame:self.make_frame = make_frameself.size = self.get_frame(0).shape[:2][::-1]self.ismask = ismask@@ -120,7 +120,6 @@ class VideoClip(Clip):"""im = self.get_frame(t)-if withmask and self.mask is not None:mask = 255 * self.mask.get_frame(t)im = np.dstack([im, mask]).astype('uint8')@@ -280,30 +279,12 @@ class VideoClip(Clip):make_audio = ((audiofile is None) and (audio == True) and(self.audio is not None))- if make_audio:+ if make_audio and temp_audiofile:# The audio will be the clip's audio- if temp_audiofile is not None:- audiofile = temp_audiofile-- else:-- # make a name for the temporary audio file-- if audio_codec in extensions_dict:- audio_ext = audio_codec- else:- try:- audio_ext = find_extension(audio_codec)- except ValueError:-- raise ValueError(- "The audio_codec you chose is unknown by MoviePy. "- "You should report this. In the meantime, you can "- "specify a temp_audiofile with the right extension "- "in write_videofile.")-- audiofile = (name + Clip._TEMP_FILES_PREFIX +- "wvf_snd.%s" % audio_ext)+ audiofile = temp_audiofile+ elif make_audio:+ audio_ext = find_extension(audio_codec)+ audiofile = (name + Clip._TEMP_FILES_PREFIX + "wvf_snd.%s" % audio_ext)# enough cpu for multiprocessing ? USELESS RIGHT NOW, WILL COME AGAIN# enough_cpu = (multiprocessing.cpu_count() > 1)@@ -380,7 +361,6 @@ class VideoClip(Clip):tt = np.arange(0, self.duration, 1.0 / fps)filenames = []- total = int(self.duration / fps) + 1for i, t in logger.iter_bar(t=list(enumerate(tt))):name = nameformat % ifilenames.append(name)@@ -455,26 +435,18 @@ class VideoClip(Clip):elif tempfiles:# convert imageio opt variable to something that can be used with# ImageMagick- opt1 = opt- if opt1 == 'nq':- opt1 ='optimizeplus'- else:- opt1 ='OptimizeTransparency'+ opt = 'optimizeplus' if opt == 'nq' else 'OptimizeTransparency'write_gif_with_tempfiles(self, filename, fps=fps,- program=program, opt=opt1, fuzz=fuzz,+ program=program, opt=opt, fuzz=fuzz,verbose=verbose, loop=loop,dispose=dispose, colors=colors,logger=logger)else:# convert imageio opt variable to something that can be used with# ImageMagick- opt1 = opt- if opt1 == 'nq':- opt1 ='optimizeplus'- else:- opt1 ='OptimizeTransparency'+ opt = 'optimizeplus' if opt == 'nq' else 'OptimizeTransparency'write_gif(self, filename, fps=fps, program=program,- opt=opt1, fuzz=fuzz, verbose=verbose, loop=loop,+ opt=opt, fuzz=fuzz, verbose=verbose, loop=loop,dispose=dispose, colors=colors,logger=logger)@@ -496,11 +468,11 @@ class VideoClip(Clip):>>> newclip = clip.subapply(lambda c:c.speedx(0.5) , 3,6)"""- left = None if (ta == 0) else self.subclip(0, ta)+ left = self.subclip(0, ta) if ta else Nonecenter = self.subclip(ta, tb).fx(fx, **kwargs)- right = None if (tb is None) else self.subclip(t_start=tb)+ right = self.subclip(t_start=tb) if tb else None- clips = [c for c in [left, center, right] if c is not None]+ clips = [c for c in (left, center, right) if c]# beurk, have to find other solutionfrom moviepy.video.compositing.concatenate import concatenate_videoclips@@ -514,8 +486,7 @@ class VideoClip(Clip):Modifies the images of a clip by replacing the frame`get_frame(t)` by another frame, `image_func(get_frame(t))`"""- if apply_to is None:- apply_to = []+ apply_to = apply_to or []return self.fl(lambda gf, t: image_func(gf(t)), apply_to)# --------------------------------------------------------------@@ -546,7 +517,7 @@ class VideoClip(Clip):"""hf, wf = framesize = picture.shape[:2]- if self.ismask and picture.max() != 0:+ if self.ismask and picture.max():return np.minimum(1, picture + self.blit_on(np.zeros(framesize), t))ct = t - self.start # clip time@@ -554,15 +525,14 @@ class VideoClip(Clip):# GET IMAGE AND MASK IF ANYimg = self.get_frame(ct)- mask = (None if (self.mask is None) else- self.mask.get_frame(ct))- if mask is not None:- if (img.shape[0] != mask.shape[0]) or (img.shape[1] != mask.shape[1]):- img = self.fill_array(img, mask.shape)+ mask = self.mask.get_frame(ct) if self.mask else None++ if mask is not None and ((img.shape[0] != mask.shape[0]) or (img.shape[1] != mask.shape[1])):+ img = self.fill_array(img, mask.shape)+hi, wi = img.shape[:2]# SET POSITION-pos = self.pos(ct)# preprocess short writings of the position@@ -688,7 +658,7 @@ class VideoClip(Clip):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 )+ assert mask is None or mask.ismaskself.mask = mask@add_mask_if_none@@ -969,11 +939,10 @@ class ImageClip(VideoClip):self.img = arrfor attr in apply_to:- if hasattr(self, attr):- a = getattr(self, attr)- if a is not None:- new_a = a.fl_image(image_func)- setattr(self, attr, new_a)+ a = getattr(self, attr, None)+ if a is not None:+ new_a = a.fl_image(image_func)+ setattr(self, attr, new_a)@outplacedef fl_time(self, time_func, apply_to=None,@@ -987,13 +956,12 @@ class ImageClip(VideoClip):masks or their audios). The result is still an ImageClip."""if apply_to is None:- apply_to = ['mask', 'audio']+ apply_to = ['mask', 'audio']for attr in apply_to:- if hasattr(self, attr):- a = getattr(self, attr)- if a is not None:- new_a = a.fl_time(time_func)- setattr(self, attr, new_a)+ a = getattr(self, attr, None)+ if a is not None:+ new_a = a.fl_time(time_func)+ setattr(self, attr, new_a)# ##diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex 284648c8..080cd377 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -60,16 +60,8 @@ class CompositeVideoClip(VideoClip):if bg_color is None:bg_color = 0.0 if ismask else (0, 0, 0)- fpss = [- c.fps- for c in clips- if hasattr(c, 'fps')- and c.fps is not None- ]- if len(fpss) == 0:- self.fps = None- else:- self.fps = max(fpss)+ fpss = [c.fps for c in clips if getattr(c, 'fps', None)]+ self.fps = max(fpss) if fpss else NoneVideoClip.__init__(self)@@ -88,16 +80,16 @@ class CompositeVideoClip(VideoClip):self.created_bg = True-# compute durationends = [c.end for c in self.clips]- if not any([(e is None) for e in ends]):- self.duration = max(ends)- self.end = max(ends)+ if None not in ends:+ duration = max(ends)+ self.duration = duration+ self.end = duration# compute audioaudioclips = [v.audio for v in self.clips if v.audio is not None]- if len(audioclips) > 0:+ if audioclips:self.audio = CompositeAudioClip(audioclips)# compute mask if necessary@@ -138,8 +130,6 @@ class CompositeVideoClip(VideoClip):--def clips_array(array, rows_widths=None, cols_widths=None,bg_color = None):@@ -171,17 +161,16 @@ def clips_array(array, rows_widths=None, cols_widths=None,xx = np.cumsum([0]+list(cols_widths))yy = np.cumsum([0]+list(rows_widths))- for j,(x,cw) in list(enumerate(zip(xx[:-1],cols_widths))):- for i,(y,rw) in list(enumerate(zip(yy[:-1],rows_widths))):- clip = array[i,j]- w,h = clip.size+ for j, (x, cw) in enumerate(zip(xx[:-1], cols_widths)):+ for i, (y, rw) in enumerate(zip(yy[:-1], rows_widths)):+ clip = array[i, j]+ w, h = clip.sizeif (w < cw) or (h < rw):clip = (CompositeVideoClip([clip.set_position('center')],size = (cw,rw),bg_color = bg_color).set_duration(clip.duration))- array[i,j] = clip.set_position((x,y))+ array[i, j] = clip.set_position((x, y))- return CompositeVideoClip(array.flatten(), size = (xx[-1],yy[-1]),- bg_color = bg_color)+ return CompositeVideoClip(array.flatten(), size=(xx[-1], yy[-1]), bg_color=bg_color)diff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.pyindex f7882089..53526087 100644--- a/moviepy/video/compositing/concatenate.py+++ b/moviepy/video/compositing/concatenate.py@@ -12,7 +12,6 @@ except NameError: # Python 3from functools import reduce-def concatenate_videoclips(clips, method="chain", transition=None,bg_color=None, ismask=False, padding = 0):""" Concatenates several video clips@@ -73,10 +72,10 @@ def concatenate_videoclips(clips, method="chain", transition=None,sizes = [v.size for v in clips]- w = max([r[0] for r in sizes])- h = max([r[1] for r in sizes])+ w = max(r[0] for r in sizes)+ h = max(r[1] for r in sizes)- tt = np.maximum(0, tt + padding*np.arange(len(tt)))+ tt = np.maximum(0, tt + padding * np.arange(len(tt)))if method == "chain":def make_frame(t):@@ -108,17 +107,13 @@ def concatenate_videoclips(clips, method="chain", transition=None,result.start_times = tt[:-1]result.start, result.duration, result.end = 0, tt[-1] , tt[-1]- audio_t = [(c.audio,t) for c,t in zip(clips,tt) if c.audio is not None]- if len(audio_t)>0:+ audio_t = [(c.audio, t) for c, t in zip(clips,tt) if c.audio is not None]+ if audio_t:result.audio = CompositeAudioClip([a.set_start(t)for a,t in audio_t])- fpss = [c.fps for c in clips if hasattr(c,'fps') and c.fps is not None]- if len(fpss) == 0:- result.fps = None- else:- result.fps = max(fpss)-+ fpss = [c.fps for c in clips if getattr(c, 'fps', None) is not None]+ result.fps = max(fpss) if fpss else Nonereturn resultdiff --git a/moviepy/video/fx/crop.py b/moviepy/video/fx/crop.pyindex ae884e2c..8066418b 100644--- a/moviepy/video/fx/crop.py+++ b/moviepy/video/fx/crop.py@@ -1,6 +1,4 @@-def crop(clip, x1=None, y1=None, x2=None, y2=None,- width = None, height=None,- x_center= None, y_center=None):+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 theoriginal clip is conserved. x1,y1 indicates the top left corner and@@ -30,35 +28,26 @@ def crop(clip, x1=None, y1=None, x2=None, y2=None,>>> crop(x_center=300, width=400, y1=100, y2=600)"""--- if width and (x1 is not None or x2 is not None):- if x1 is not None:- x2 = x1+width- else:- x1 = x2-width-- if height and (y1 is not None or y2 is not None):- if y1 is not None:- y2 = y1+height- else:- y1 = y2 - height-++ 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-+ x1, x2 = x_center - width / 2, x_center + width / 2+if y_center:- y1, y2 = y_center - height/2, y_center + height/2-- if x1 is None:- x1 = 0- if y1 is None:- y1 = 0- if x2 is None:- x2 = clip.size[0]- if y2 is None:- y2 = clip.size[1]-- return clip.fl_image(- lambda pic: pic[int(y1):int(y2), int(x1):int(x2)],- apply_to=['mask'])+ 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.fl_image(lambda pic: pic[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.pyindex 04189a4c..c7290b8e 100644--- a/moviepy/video/fx/even_size.py+++ b/moviepy/video/fx/even_size.py@@ -1,22 +1,20 @@-import numpy as np-from moviepy.decorators import apply_to_mask@apply_to_maskdef even_size(clip):- """ Crops the clip to make dimensions even.-+ """+ Crops the clip to make dimensions even."""-- w,h = clip.size-- if (w%2 == 0) and (h%2==0):+ w, h = clip.size+ w_even = w % 2 == 0+ h_even = h % 2 == 0+ if w_even and h_even:return clip- if (w%2 != 0) and (h%2!=0):+ if not w_even and not h_even:fl_image = lambda a : a[:-1,:-1,:]- elif (w%2 != 0):+ elif w_even:fl_image = lambda a : a[:,:-1,:]else:fl_image = lambda a : a[:-1,:,:]diff --git a/moviepy/video/fx/freeze.py b/moviepy/video/fx/freeze.pyindex fab0549b..ff4d4aa8 100644--- a/moviepy/video/fx/freeze.py+++ b/moviepy/video/fx/freeze.py@@ -25,4 +25,5 @@ def freeze(clip, t=0, freeze_duration=None, total_duration=None,before = [clip.subclip(0,t)] if (t!=0) else []freeze = [clip.to_ImageClip(t).set_duration(freeze_duration)]after = [clip.subclip(t)] if (t !=clip.duration) else []- return concatenate_videoclips(before+freeze+after)+ return concatenate_videoclips(before + freeze + after)+\ No newline at end of filediff --git a/moviepy/video/fx/mask_color.py b/moviepy/video/fx/mask_color.pyindex fa385189..fba87dda 100644--- a/moviepy/video/fx/mask_color.py+++ b/moviepy/video/fx/mask_color.py@@ -10,16 +10,24 @@ def mask_color(clip, color=None, thr=0, s=1):color is d, the transparency will bed**s / (thr**s + d**s)+which is 1 when d>>thr and 0 for d<<thr, the stiffness of the effect beingparametrized by s"""if color is None:color = [0,0,0]- # code a little sloppy, it just works.- hill = lambda x: (1.0*(x!=0) if (thr==0) else (x**s/ (thr**s+x**s)))color = np.array(color)- flim = lambda im: hill(np.sqrt(((im-color)**2).sum(axis=2)))++ def hill(x):+ if thr:+ return x**s / (thr**s + x**s)+ else:+ return 1.0 * (x != 0)++ def flim(im):+ return hill(np.sqrt(((im-color)**2).sum(axis=2)))+mask = clip.fl_image(flim)mask.ismask= Truenewclip = clip.set_mask(mask)diff --git a/moviepy/video/io/bindings.py b/moviepy/video/io/bindings.pyindex 2545ff2b..4b206f75 100644--- a/moviepy/video/io/bindings.py+++ b/moviepy/video/io/bindings.py@@ -28,5 +28,5 @@ def mplfig_to_npimage(fig):# exports the canvas to a string buffer and then to a numpy nd.arraybuf = canvas.tostring_rgb()- image= np.fromstring(buf,dtype=np.uint8)+ image= np.frombuffer(buf, dtype=np.uint8)return image.reshape(h,w,3)diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex b8ba8be6..7ef5b2d1 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -59,10 +59,7 @@ class FFMPEG_VideoReader:self.infos = infosself.pix_fmt = pix_fmt- if pix_fmt == 'rgba':- self.depth = 4- else:- self.depth = 3+ self.depth = 4 if pix_fmt == 'rgba' else 3if bufsize is None:w, h = self.size@@ -179,15 +176,14 @@ class FFMPEG_VideoReader:if pos == self.pos:return self.lastread- else:- if (pos < self.pos) or (pos > self.pos + 100):- self.initialize(t)- self.pos = pos- else:- self.skip_frames(pos-self.pos-1)- result = self.read_frame()+ elif (pos < self.pos) or (pos > self.pos + 100):+ self.initialize(t)self.pos = pos- return result+ else:+ self.skip_frames(pos-self.pos-1)+ result = self.read_frame()+ self.pos = pos+ return resultdef close(self):if self.proc:@@ -223,10 +219,7 @@ def ffmpeg_read_image(filename, with_mask=True):this layer as the mask of the returned ImageClip"""- if with_mask:- pix_fmt = 'rgba'- else:- pix_fmt = "rgb24"+ pix_fmt = 'rgba' if with_mask else "rgb24"reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt, check_duration=False)im = reader.lastreaddel readerdiff --git a/moviepy/video/tools/credits.py b/moviepy/video/tools/credits.pyindex 77f0397d..a5adfbb1 100644--- a/moviepy/video/tools/credits.py+++ b/moviepy/video/tools/credits.py@@ -73,39 +73,37 @@ def credits1(creditfile, width, stretch=30, color='white', stroke_color='black',"""# PARSE THE TXT FILE-- with open(creditfile) as f:- lines = f.readlines()-- lines = filter(lambda x: not x.startswith('\n'), lines)texts = []oneline = True- for l in lines:- if not l.startswith('#'):- if l.startswith('.blank'):++ with open(creditfile) as f:+ for l in f:+ if l.startswith(('\n', '#')):+ # exclude blank lines or comments+ continue+ elif l.startswith('.blank'):+ # ..blank nfor i in range(int(l.split(' ')[1])):texts.append(['\n', '\n'])elif l.startswith('..'):texts.append([l[2:], ''])oneline = True+ elif oneline:+ texts.append(['', l])+ oneline = Falseelse:- if oneline:- texts.append(['', l])- oneline = False- else:- texts.append(['\n', l])-- left, right = ["".join(l) for l in zip(*texts)]-- # MAKE TWO COLUMNS FOR THE CREDITS+ texts.append(['\n', l])++ left, right = ("".join(l) for l in zip(*texts))+ # MAKE TWO COLUMNS FOR THE CREDITSleft, right = [TextClip(txt, color=color, stroke_color=stroke_color,stroke_width=stroke_width, font=font,fontsize=fontsize, align=al)for txt, al in [(left, 'East'), (right, 'West')]]- cc = CompositeVideoClip([left, right.set_position((left.w+gap, 0))],- size=(left.w+right.w+gap, right.h),+ cc = CompositeVideoClip([left, right.set_position((left.w + gap, 0))],+ size=(left.w + right.w + gap, right.h),bg_color=None)# SCALE TO THE REQUIRED SIZEdiff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.pyindex 0c0afcef..de75f788 100644--- a/moviepy/video/tools/cuts.py+++ b/moviepy/video/tools/cuts.py@@ -12,9 +12,8 @@ from moviepy.decorators import use_clip_fps_by_defaultdef find_video_period(clip,fps=None,tmin=.3):""" Finds the period of a video based on frames correlation """-frame = lambda t: clip.get_frame(t).flatten()- tt = np.arange(tmin,clip.duration,1.0/ fps)[1:]+ tt = np.arange(tmin, clip.duration, 1.0/ fps)[1:]ref = frame(0)corrs = [ np.corrcoef(ref, frame(t))[0,1] for t in tt]return tt[np.argmax(corrs)]@@ -57,7 +56,7 @@ class FramesMatch:self.t1, self.t2, self.d_min, self.d_max)def __iter__(self):- return [self.t1, self.t2, self.d_min, self.d_max].__iter__()+ return iter((self.t1, self.t2, self.d_min, self.d_max))class FramesMatches(list):@@ -219,7 +218,6 @@ class FramesMatches(list):if nomatch_thr is None:nomatch_thr = match_thr-dict_starts = defaultdict(lambda : [])for (start, end, d_min, d_max) in self:dict_starts[start].append([end, d_min, d_max])@@ -243,33 +241,27 @@ class FramesMatches(list):if (end-start)>min_time_span]- if (great_long_matches == []):+ if not great_long_matches:continue # No GIF can be made starting at this time- poor_matches = set([end for (end,d_min, d_max) in ends_distances- if d_min>nomatch_thr])- short_matches = [end for end in ends- if (end-start)<=0.6]+ poor_matches = {end for (end,d_min, d_max) in ends_distances if d_min > nomatch_thr}+ short_matches = {end for end in ends if (end-start) <= 0.6}- if len( poor_matches.intersection(short_matches) ) == 0 :+ if not poor_matches.intersection(short_matches):continue-- end = max([end for (end, d_min, d_max) in great_long_matches])- end, d_min, d_max = [e for e in great_long_matches if e[0]==end][0]+ end = max(end for (end, d_min, d_max) in great_long_matches)+ end, d_min, d_max = next(e for e in great_long_matches if e[0]==end)+result.append(FramesMatch(start, end, d_min, d_max))min_start = start + time_distance- return FramesMatches( result )+ return FramesMatches(result)def write_gifs(self, clip, gif_dir):- """-- """-for (start, end, _, _) in self:- name = "%s/%08d_%08d.gif"%(gif_dir, 100*start, 100*end)+ name = "%s/%08d_%08d.gif" % (gif_dir, 100*start, 100*end)clip.subclip(start, end).write_gif(name, verbose=False)@@ -316,11 +308,8 @@ def detect_scenes(clip=None, luminosities=None, thr=10,Must be provided if you provide no clip or a clip withoutfps attribute.---- """-++ """if luminosities is None:luminosities = [f.sum() for f in clip.iter_frames(fps=fps, dtype='uint32', logger=logger)]diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.pyindex 8713a545..fdc37055 100644--- a/moviepy/video/tools/drawing.py+++ b/moviepy/video/tools/drawing.py@@ -37,22 +37,21 @@ def blit(im1, im2, pos=None, mask=None, ismask=False):new_im2 = +im2- if mask is not None:+ if mask is None:+ new_im2[yp1:yp2, xp1:xp2] = blitted+ else:mask = mask[y1:y2, x1:x2]if len(im1.shape) == 3:mask = np.dstack(3 * [mask])blit_region = new_im2[yp1:yp2, xp1:xp2]- new_im2[yp1:yp2, xp1:xp2] = (- 1.0 * mask * blitted + (1.0 - mask) * blit_region)- else:- new_im2[yp1:yp2, xp1:xp2] = blitted-+ new_im2[yp1:yp2, xp1:xp2] = (1.0 * mask * blitted + (1.0 - mask) * blit_region)+return new_im2.astype('uint8') if (not ismask) else new_im2def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,- shape='linear', offset = 0):+ shape='linear', offset = 0):"""Draw a linear, bilinear, or radial gradient.The result is a picture of size ``size``, whose color varies@@ -67,47 +66,47 @@ def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,------------size- Size (width, height) in pixels of the final picture/array.+ Size (width, height) in pixels of the final picture/array.p1, p2- Coordinates (x,y) in pixels of the limit point for ``col1``- and ``col2``. The color 'before' ``p1`` is ``col1`` and it- gradually changes in the direction of ``p2`` until it is ``col2``- when it reaches ``p2``.+ Coordinates (x,y) in pixels of the limit point for ``col1``+ and ``col2``. The color 'before' ``p1`` is ``col1`` and it+ gradually changes in the direction of ``p2`` until it is ``col2``+ when it reaches ``p2``.vector- A vector [x,y] in pixels that can be provided instead of ``p2``.- ``p2`` is then defined as (p1 + vector).+ A vector [x,y] in pixels that can be provided instead of ``p2``.+ ``p2`` is then defined as (p1 + vector).col1, col2- Either floats between 0 and 1 (for gradients used in masks)- or [R,G,B] arrays (for colored gradients).-+ Either floats between 0 and 1 (for gradients used in masks)+ or [R,G,B] arrays (for colored gradients).+shape- 'linear', 'bilinear', or 'circular'.- In a linear gradient the color varies in one direction,- from point ``p1`` to point ``p2``.- In a bilinear gradient it also varies symetrically form ``p1``- in the other direction.- In a circular gradient it goes from ``col1`` to ``col2`` in all- directions.+ 'linear', 'bilinear', or 'circular'.+ In a linear gradient the color varies in one direction,+ from point ``p1`` to point ``p2``.+ In a bilinear gradient it also varies symetrically form ``p1``+ in the other direction.+ In a circular gradient it goes from ``col1`` to ``col2`` in all+ directions.offset- Real number between 0 and 1 indicating the fraction of the vector- at which the gradient actually starts. For instance if ``offset``- is 0.9 in a gradient going from p1 to p2, then the gradient will- only occur near p2 (before that everything is of color ``col1``)- If the offset is 0.9 in a radial gradient, the gradient will- occur in the region located between 90% and 100% of the radius,- this creates a blurry disc of radius d(p1,p2).+ Real number between 0 and 1 indicating the fraction of the vector+ at which the gradient actually starts. For instance if ``offset``+ is 0.9 in a gradient going from p1 to p2, then the gradient will+ only occur near p2 (before that everything is of color ``col1``)+ If the offset is 0.9 in a radial gradient, the gradient will+ occur in the region located between 90% and 100% of the radius,+ this creates a blurry disc of radius d(p1,p2).Returns--------image- An Numpy array of dimensions (W,H,ncolors) of type float- representing the image of the gradient.-+ An Numpy array of dimensions (W,H,ncolors) of type float+ representing the image of the gradient.+Examples---------@@ -119,16 +118,18 @@ def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,# np-arrayize and change x,y coordinates to y,xw,h = size- col1, col2 = map(lambda x : np.array(x).astype(float), [col1, col2])+ col1 = np.array(col1).astype(float)+ col2 = np.array(col2).astype(float)if shape == 'bilinear':if vector is None:vector = np.array(p2) - np.array(p1)- m1,m2 = [ color_gradient(size, p1, vector=v, col1 = 1.0, col2 = 0,- shape = 'linear', offset= offset)- for v in [vector,-vector]]-- arr = np.maximum(m1,m2)++ m1, m2 = [ color_gradient(size, p1, vector=v, col1 = 1.0, col2 = 0,+ shape = 'linear', offset= offset)+ for v in [vector,-vector]]++ arr = np.maximum(m1, m2)if col1.size > 1:arr = np.dstack(3*[arr])return arr*col1 + (1-arr)*col2@@ -136,15 +137,14 @@ def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,p1 = np.array(p1[::-1]).astype(float)- if vector is None:- if p2 is not None:- p2 = np.array(p2[::-1])- vector = p2-p1+ if vector is None and p2:+ p2 = np.array(p2[::-1])+ vector = p2-p1else:vector = np.array(vector[::-1])p2 = p1 + vector- if vector is not None:+ if vector:norm = np.linalg.norm(vector)M = np.dstack(np.meshgrid(range(w),range(h))[::-1]).astype(float)@@ -162,21 +162,22 @@ def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,elif shape == 'radial':if r is None:- r = norm- if r==0:+ r = norm++ if r == 0:arr = np.ones((h,w))else:- arr = (np.sqrt(((M- p1)**2).sum(axis=2)))-offset*r+ arr = (np.sqrt(((M - p1) ** 2).sum(axis=2))) - offset * rarr = arr / ((1-offset)*r)- arr = np.minimum(1.0,np.maximum(0, arr) )-+ arr = np.minimum(1.0, np.maximum(0, arr))+if col1.size > 1:arr = np.dstack(3*[arr])return (1-arr)*col1 + arr*col2-+def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,- col1=0,col2=1.0, grad_width=0):+ col1=0,col2=1.0, grad_width=0):"""Make an image splitted in 2 colored regions.Returns an array of size ``size`` divided in two regions called 1 and@@ -187,27 +188,27 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,-----------x: (int)- If provided, the image is splitted horizontally in x, the left- region being region 1.-+ If provided, the image is splitted horizontally in x, the left+ region being region 1.+y: (int)- If provided, the image is splitted vertically in y, the top region- being region 1.+ If provided, the image is splitted vertically in y, the top region+ being region 1.p1,p2:- Positions (x1,y1),(x2,y2) in pixels, where the numbers can be- floats. Region 1 is defined as the whole region on the left when- going from ``p1`` to ``p2``.+ Positions (x1,y1),(x2,y2) in pixels, where the numbers can be+ floats. Region 1 is defined as the whole region on the left when+ going from ``p1`` to ``p2``.p1, vector:- ``p1`` is (x1,y1) and vector (v1,v2), where the numbers can be- floats. Region 1 is then the region on the left when starting- in position ``p1`` and going in the direction given by ``vector``.-+ ``p1`` is (x1,y1) and vector (v1,v2), where the numbers can be+ floats. Region 1 is then the region on the left when starting+ in position ``p1`` and going in the direction given by ``vector``.+gradient_width- If not zero, the split is not sharp, but gradual over a region of- width ``gradient_width`` (in pixels). This is preferable in many- situations (for instance for antialiasing).+ If not zero, the split is not sharp, but gradual over a region of+ width ``gradient_width`` (in pixels). This is preferable in many+ situations (for instance for antialiasing).Examples@@ -220,7 +221,7 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,>>> color_split(size, x=50, col1=[255,0,0], col2=[0,255,0])>>> # An image splitted along an arbitrary line (see below)>>> color_split(size, p1=[20,50], p2=[25,70] col1=0, col2=1)-+"""if grad_width or ( (x is None) and (y is None)):@@ -236,12 +237,11 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,x,y = vectorvector = np.array([y,-x]).astype('float')norm = np.linalg.norm(vector)- vector = max(0.1,grad_width)*vector/norm+ vector = max(0.1, grad_width) * vector / normreturn color_gradient(size,p1,vector=vector,- col1 = col1, col2 = col2, shape='linear')+ col1 = col1, col2 = col2, shape='linear')else:-- w,h = size+ w, h = sizeshape = (h, w) if np.isscalar(col1) else (h, w, len(col1))arr = np.zeros(shape)if x:@@ -250,13 +250,12 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,elif y:arr[:y] = col1arr[y:] = col2-return arr# if we are here, it means we didn't exit with a proper 'return'print( "Arguments in color_split not understood !" )raise-+def circle(screensize, center, radius, col1=1.0, col2=0, blur=1):""" Draw an image with a circle.@@ -265,6 +264,6 @@ def circle(screensize, center, radius, col1=1.0, col2=0, blur=1):with a radius ``radius`` but slightly blurred on the border by ``blur``pixels"""+ offset = 1.0*(radius-blur)/radius if radius else 0return color_gradient(screensize,p1=center,r=radius, col1=col1,- col2=col2, shape='radial', offset = 0 if (radius==0) else- 1.0*(radius-blur)/radius)+ col2=col2, shape='radial', offset=offset)diff --git a/moviepy/video/tools/segmenting.py b/moviepy/video/tools/segmenting.pyindex 935dd497..1e6c06bf 100644--- a/moviepy/video/tools/segmenting.py+++ b/moviepy/video/tools/segmenting.py@@ -15,19 +15,22 @@ def findObjects(clip,rem_thr=500, preview=False):"""image = clip.get_frame(0)- if clip.mask is None:+ if not clip.mask:clip = clip.add_mask()mask = clip.mask.get_frame(0)labelled, num_features = ndi.measurements.label(image[:,:,0])#find the objects- slices = ndi.find_objects(labelled)- # cool trick to remove letter holes (in o,e,a, etc.)- slices = [e for e in slices if mask[e[0],e[1]].mean() >0.2]- # remove very small slices- slices = [e for e in slices if image[e[0],e[1]].size > rem_thr]- # Sort the slices from left to right+ slices = []+ for e in ndi.find_objects(labelled):+ if mask[e[0],e[1]].mean() <= 0.2:+ # remove letter holes (in o,e,a, etc.)+ continue+ if image[e[0],e[1]].size <= rem_thr:+ # remove very small slices+ continue+ slices.append(e)islices = sorted(enumerate(slices), key = lambda s : s[1][1].start)letters = []diff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.pyindex fc396c1a..34a8615c 100644--- a/moviepy/video/tools/subtitles.py+++ b/moviepy/video/tools/subtitles.py@@ -4,7 +4,6 @@ import reimport numpy as np-from moviepy.decorators import convert_to_secondsfrom moviepy.tools import cvsecsfrom moviepy.video.VideoClip import TextClip, VideoClip@@ -39,7 +38,7 @@ class SubtitlesClip(VideoClip):VideoClip.__init__(self, has_constant_size=False)- if isinstance( subtitles, str):+ if isinstance(subtitles, str):subtitles = file_to_subtitles(subtitles)#subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]@@ -62,10 +61,10 @@ class SubtitlesClip(VideoClip):false. """sub =[((ta,tb),txt) for ((ta,tb),txt) in self.textclips.keys()if (ta<=t<tb)]- if sub == []:+ if not sub:sub = [((ta,tb),txt) for ((ta,tb),txt) in self.subtitles if(ta<=t<tb)]- if sub == []:+ if not sub:return Falsesub = sub[0]if sub not in self.textclips.keys():@@ -84,8 +83,8 @@ class SubtitlesClip(VideoClip):else np.array([[0]]))self.make_frame = make_frame- hasmask = (self.make_textclip('T').mask is not None)- self.mask = (VideoClip(make_mask_frame, ismask=True) if hasmask else None)+ hasmask = bool(self.make_textclip('T').mask)+ self.mask = VideoClip(make_mask_frame, ismask=True) if hasmask else Nonedef in_subclip(self, t_start= None, t_end= None):""" Returns a sequence of [(t1,t2), txt] covering all the given subclip@@ -108,7 +107,7 @@ class SubtitlesClip(VideoClip):def __iter__(self):- return self.subtitles.__iter__()+ return iter(self.subtitles)@@ -121,10 +120,11 @@ class SubtitlesClip(VideoClip):def to_srt(sub_element):(ta, tb), txt = sub_element- fta, ftb = map(time_to_string, (ta, tb))+ fta = cvsecs(ta)+ ftb = cvsecs(tb)return "%s - %s\n%s"%(fta, ftb, txt)- return "\n\n".join(map(to_srt, self.subtitles))+ return "\n\n".join(to_srt(s) for s in self.subtitles)@@ -147,20 +147,17 @@ def file_to_subtitles(filename):Only works for '.srt' format for the moment."""-- with open(filename,'r') as f:- lines = f.readlines()-times_texts = []- current_times , current_text = None, ""-- for line in lines:- times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line)- if times != []:- current_times = list(map(cvsecs, times))- elif line.strip() == '':- times_texts.append((current_times, current_text.strip('\n')))- current_times, current_text = None, ""- elif current_times is not None:- current_text = current_text + line+ current_times = None+ current_text = ""+ with open(filename,'r') as f:+ for line in f:+ times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line)+ if times:+ current_times = [cvsecs(t) for t in times]+ elif line.strip() == '':+ times_texts.append((current_times, current_text.strip('\n')))+ current_times, current_text = None, ""+ elif current_times:+ current_text += linereturn times_textsdiff --git a/moviepy/video/tools/tracking.py b/moviepy/video/tools/tracking.pyindex 459c4e82..fd5247f5 100644--- a/moviepy/video/tools/tracking.py+++ b/moviepy/video/tools/tracking.py@@ -11,7 +11,6 @@ of the tracking time interval).import numpy as npfrom moviepy.decorators import convert_to_seconds, use_clip_fps_by_default-from scipy.interpolate import interp1dfrom ..io.preview import imdisplayfrom .interpolators import Trajectorydiff --git a/tests/test_AudioClips.py b/tests/test_AudioClips.pyindex 6f6953a8..70fb9307 100644--- a/tests/test_AudioClips.py+++ b/tests/test_AudioClips.py@@ -12,11 +12,13 @@ from moviepy.audio.io.AudioFileClip import AudioFileClipfrom .test_helper import TMP_DIR+skip_if_windows = pytest.mark.skipif(+ sys.platform.startswith("win"),+ reason="Temporarily skipping on windows because otherwise test suite fails with Invalid Handle Error"+)+@skip_if_windowsdef test_audio_coreader():- if sys.platform.startswith("win"):- pytest.skip("Temporarily skipping on windows because otherwise test suite fails with Invalid Handle Error")-sound = AudioFileClip("media/crunching.mp3")sound = sound.subclip(1, 4)sound2 = AudioFileClip("media/crunching.mp3")@@ -28,9 +30,6 @@ def test_audioclip():clip.write_audiofile(os.path.join(TMP_DIR, "audioclip.mp3"))def test_audioclip_concat():- if sys.platform.startswith("win"):- pytest.skip("Temporarily skipping on windows because otherwise test suite fails with Invalid Handle Error")-make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]make_frame_880 = lambda t: [sin(880 * 2 * pi * t)]@@ -48,10 +47,8 @@ def test_audioclip_concat():concat_clip.write_audiofile(os.path.join(TMP_DIR, "concat_audioclip.mp3"))+@skip_if_windowsdef test_audioclip_with_file_concat():- if sys.platform.startswith("win"):- pytest.skip("Temporarily skipping on windows because otherwise test suite fails with Invalid Handle Error")-make_frame_440 = lambda t: [sin(440 * 2 * pi * t)]clip1 = AudioClip(make_frame_440, duration=1, fps=44100)@@ -67,9 +64,6 @@ def test_audioclip_with_file_concat():def test_audiofileclip_concat():- if sys.platform.startswith("win"):- pytest.skip("Temporarily skipping on windows because otherwise test suite fails with Invalid Handle Error")-sound = AudioFileClip("media/crunching.mp3")sound = sound.subclip(1, 4)@@ -79,5 +73,6 @@ def test_audiofileclip_concat():concat.write_audiofile(os.path.join(TMP_DIR, "concat_audio_file.mp3"))+if __name__ == "__main__":pytest.main()diff --git a/tests/test_examples.py b/tests/test_examples.pyindex ef877327..73218d31 100644--- a/tests/test_examples.py+++ b/tests/test_examples.py@@ -1,45 +1,36 @@# -*- coding: utf-8 -*--"""Example tests for use with pytest.+import os-TODO:- * Resolve matplotlib errors during automated testing.-"""-# import os-# import sys-#-# import pytest-#-# from .test_helper import PYTHON_VERSION, TMP_DIR, TRAVIS-#-#-#-#-# def test_matplotlib():-# #for now, python 3.5 installs a version of matplotlib that complains-# #about $DISPLAY variable, so lets just ignore for now.-# if PYTHON_VERSION in ('2.7', '3.3') or (PYTHON_VERSION == '3.5' and TRAVIS):-# return-#-# import matplotlib-# import numpy as np-# from moviepy.video.io.bindings import mplfig_to_npimage-# from moviepy.video.VideoClip import VideoClip-#-# x = np.linspace(-2, 2, 200)-#-# duration = 2-#-# matplotlib.use('Agg')-# fig, ax = matplotlib.plt.subplots()-#-# def make_frame(t):-# ax.clear()-# ax.plot(x, np.sinc(x**2) + np.sin(x + 2*np.pi/duration * t), lw=3)-# ax.set_ylim(-1.5, 2.5)-# return mplfig_to_npimage(fig)-#-# animation = VideoClip(make_frame, duration=duration)-# animation.write_gif(os.path.join(TMP_DIR, 'matplotlib.gif'), fps=20)-#-# if __name__ == '__main__':-# pytest.main()+import pytest+import numpy as np+try:+ import matplotlib+except ImportError:+ matplotlib = None+from moviepy.video.io.bindings import mplfig_to_npimage+from moviepy.video.VideoClip import VideoClip+from .test_helper import PYTHON_VERSION, TMP_DIR, TRAVIS++[email protected](not matplotlib, reason="no mpl")[email protected](PYTHON_VERSION in ('2.7', '3.3'), reason="version")[email protected](PYTHON_VERSION == '3.5' and TRAVIS, reason="travis py35")+def test_matplotlib():+ #for now, python 3.5 installs a version of matplotlib that complains+ #about $DISPLAY variable, so lets just ignore for now.++ x = np.linspace(-2, 2, 200)++ duration = 2++ matplotlib.use('Agg')+ fig, ax = matplotlib.pyplot.subplots()++ def make_frame(t):+ ax.clear()+ ax.plot(x, np.sinc(x**2) + np.sin(x + 2*np.pi/duration * t), lw=3)+ ax.set_ylim(-1.5, 2.5)+ return mplfig_to_npimage(fig)++ animation = VideoClip(make_frame, duration=duration)+ animation.write_gif(os.path.join(TMP_DIR, 'matplotlib.gif'), fps=20)diff --git a/tests/test_tools.py b/tests/test_tools.pyindex 707881ef..63e9bc64 100644--- a/tests/test_tools.py+++ b/tests/test_tools.py@@ -7,61 +7,57 @@ import pytestimport moviepy.tools as tools-def test_ext():[email protected]('given, expected', [+ ("libx264", "mp4"),+ ("libmpeg4", "mp4"),+ ("libtheora", "ogv"),+ ("libvpx", "webm")+])+def test_find_extensions(given, expected):"""Test for find_extension function."""- lefts = ['libx264', 'libmpeg4', 'libtheora', 'libvpx']- rights = ['mp4', 'mp4', 'ogv', 'webm']- for i in range(len(lefts)):- left = tools.find_extension(lefts[i])- right = rights[i]- message = "{0} did not get associated with {1}".format(left, right)- assert left == right, message+ assert tools.find_extension(given) == expected-def test_2():- """Test for raising erre if codec not in dictionaries."""+def test_find_extensions_not_found():+ """Test for raising error if codec not in dictionaries."""with pytest.raises(ValueError): # asking for a silly video formattools.find_extension('flashvideo')-def test_3():+[email protected]('given, expected', [+ (15.4, 15.4),+ ((1, 21.5), 81.5),+ ((1, 1, 2), 3662),+ ([1, 1, 2], 3662),+ ('01:01:33.5', 3693.5),+ ('01:01:33.045', 3693.045),+ ('01:01:33,5', 3693.5),+ ('1:33', 93.0),+ ('33.4', 33.4),+ (None, None)+])+def test_cvsecs(given, expected):"""Test the cvsecs funtion outputs correct times as per the docstring."""- lefts = [15.4, (1,21.5), (1,1,2), '01:01:33.5', '01:01:33.045' ]- rights = [15.4, 81.5, 3662, 3693.5, 3693.045]- for i in range(len(lefts)):- left = tools.cvsecs(lefts[i])- right = rights[i]- message = "{0} resulted in {1}, but {2} was expected"\- .format(lefts[i],left, right)- assert left == right, message+ assert tools.cvsecs(given) == expected-def test_4():[email protected]("given, expected", [+ ("hello straight string", True),+ (r'hello raw string', True),+ (42, False),+ (True, False),+ (b'hello bytes', sys.version_info[0] < 3),+])+def test_is_string(given, expected):"""Test the is_string function in tools."""- lefts = ["hello straight string", r'hello raw string',42, True ]- rights = [True, True, False, False]- for i in range(len(lefts)):- left = tools.is_string(lefts[i])- right = rights[i]- message = "{0} resulted in {1}, but {2} was expected"\- .format(lefts[i],left, right)- assert left == right, message---def test_4a():- """Test for the different behaviour of byte strings between python 2/3."""- version = sys.version_info[0]- answer = version < 3 #True for py2, else False- left = tools.is_string(b'hello bytes')- right = answer- message = "{0} resulted in {1}, but {2} was expected"\- .format(b'hello bytes',left, right)- assert left == right, message---def test_5():+ assert tools.is_string(given) == expected+++def test_sys_write_flush():"""Test for sys_write-flush function. Check that stdout has no content after flushing."""tools.sys_write_flush("hello world")+file = sys.stdout.read()assert file == b""