Video editing with Python
Add support for path-like objects with a decorator (#1137)
Tom Burrows57f1110b0f6e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0069aef8..542b9d2c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Support removed for Python versions 2.7, 3.4 & 3.5 [#1103, #1106]### Added <!-- for new features -->+- Support for path-like objects as an option wherever filenames are passed in as arguments- Optional `encoding` parameter in `SubtitlesClip` [#1043]### Changed <!-- for changes in existing functionality -->diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex 508ab743..a15624a8 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -5,7 +5,7 @@ import proglogfrom moviepy.audio.io.ffmpeg_audiowriter import ffmpeg_audiowritefrom moviepy.Clip import Clip-from moviepy.decorators import requires_duration+from moviepy.decorators import requires_duration, convert_path_to_stringfrom moviepy.tools import extensions_dict@@ -159,6 +159,7 @@ class AudioClip(Clip):return maxi@requires_duration+ @convert_path_to_string("filename")def write_audiofile(self,filename,@@ -178,11 +179,11 @@ class AudioClip(Clip):-----------filename- Name of the output file+ Name of the output file, as a string or a path-like object.fpsFrames per second. If not set, it will try default to self.fps if- already set, otherwise it will default to 44100+ already set, otherwise it will default to 44100.nbytesSample width (set to 2 for 16-bit sound, 4 for 32-bit sound)diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.pyindex 41919c99..58dcacf6 100644--- a/moviepy/audio/io/AudioFileClip.py+++ b/moviepy/audio/io/AudioFileClip.py@@ -2,6 +2,7 @@ from __future__ import divisionfrom moviepy.audio.AudioClip import AudioClipfrom moviepy.audio.io.readers import FFMPEG_AudioReader+from moviepy.decorators import convert_path_to_stringclass AudioFileClip(AudioClip):@@ -18,6 +19,7 @@ class AudioFileClip(AudioClip):filenameEither a soundfile name (of any extension supported by ffmpeg)+ as a string or a path-like object,or an array representing a sound. If the soundfile is not a .wav,it will be converted to .wav first, using the ``fps`` and``bitrate`` arguments.@@ -62,6 +64,7 @@ class AudioFileClip(AudioClip):"""+ @convert_path_to_string("filename")def __init__(self, filename, buffersize=200000, nbytes=2, fps=44100):AudioClip.__init__(self)@@ -74,6 +77,7 @@ class AudioFileClip(AudioClip):self.duration = self.reader.durationself.end = self.reader.durationself.buffersize = self.reader.buffersize+ self.filename = filenameself.make_frame = lambda t: self.reader.get_frame(t)self.nchannels = self.reader.nchannelsdiff --git a/moviepy/decorators.py b/moviepy/decorators.pyindex a994e646..436e7aba 100644--- a/moviepy/decorators.py+++ b/moviepy/decorators.py@@ -1,6 +1,7 @@"""all decorators used in moviepy go there"""+import osimport decorator@@ -81,7 +82,8 @@ def preprocess_args(fun, varnames):names = func_code.co_varnamesnew_a = [- fun(arg) if (name in varnames) else arg for (arg, name) in zip(a, names)+ fun(arg) if (name in varnames) and (arg is not None) else arg+ for (arg, name) in zip(a, names)]new_kw = {k: fun(v) if k in varnames else v for (k, v) in kw.items()}return f(*new_a, **new_kw)@@ -90,10 +92,15 @@ def preprocess_args(fun, varnames):def convert_to_seconds(varnames):- "Converts the specified variables to seconds"+ """Converts the specified variables to seconds"""return preprocess_args(cvsecs, varnames)+def convert_path_to_string(varnames):+ """Converts the specified variables to a path string"""+ return preprocess_args(os.fspath, varnames)++@decorator.decoratordef add_mask_if_none(f, clip, *a, **k):""" Add a mask to the clip if there is none. """diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex b97db58c..4444a117 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -23,6 +23,7 @@ from moviepy.decorators import (outplace,requires_duration,use_clip_fps_by_default,+ convert_path_to_string,)from moviepy.tools import (extensions_dict,@@ -143,6 +144,7 @@ class VideoClip(Clip):@requires_duration@use_clip_fps_by_default@convert_masks_to_RGB+ @convert_path_to_string("filename")def write_videofile(self,filename,@@ -170,7 +172,7 @@ class VideoClip(Clip):-----------filename- Name of the video file to write in.+ Name of the video file to write in, as a string or a path-like object.The extension must correspond to the "codec" used (see below),or simply be '.avi' (which will work with any codec).@@ -399,6 +401,7 @@ class VideoClip(Clip):@requires_duration@convert_masks_to_RGB+ @convert_path_to_string("filename")def write_gif(self,filename,@@ -421,7 +424,7 @@ class VideoClip(Clip):-----------filename- Name of the resulting gif file.+ Name of the resulting gif file, as a string or a path-like object.fpsNumber of frames per second (see note below). If it@@ -930,8 +933,8 @@ class ImageClip(VideoClip):-----------img- Any picture file (png, tiff, jpeg, etc.) or any array representing- an RGB image (for instance a frame from a VideoClip).+ Any picture file (png, tiff, jpeg, etc.) as a string or a path-like object,+ or any array representing an RGB image (for instance a frame from a VideoClip).ismaskSet this parameter to `True` if the clip is a mask.@@ -953,7 +956,8 @@ class ImageClip(VideoClip):):VideoClip.__init__(self, ismask=ismask, duration=duration)- if isinstance(img, str):+ if not isinstance(img, np.ndarray):+ # img is a string or path-like object, so read it in from diskimg = imread(img)if len(img.shape) == 3: # img is (now) a RGB(a) numpy array@@ -1070,7 +1074,8 @@ class TextClip(ImageClip):``filename``.filename- The name of a file in which there is the text to write.+ The name of a file in which there is the text to write,+ as a string or a path-like object.Can be provided instead of argument ``txt``size@@ -1120,6 +1125,7 @@ class TextClip(ImageClip):"""+ @convert_path_to_string("filename")def __init__(self,txt=None,diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.pyindex 9fa30bc8..db9b9a00 100644--- a/moviepy/video/io/VideoFileClip.py+++ b/moviepy/video/io/VideoFileClip.py@@ -2,6 +2,7 @@ import osfrom moviepy.audio.io.AudioFileClip import AudioFileClipfrom moviepy.Clip import Clip+from moviepy.decorators import convert_path_to_stringfrom moviepy.video.io.ffmpeg_reader import FFMPEG_VideoReaderfrom moviepy.video.VideoClip import VideoClip@@ -22,8 +23,9 @@ class VideoFileClip(VideoClip):------------filename:- The name of the video file. It can have any extension supported- by ffmpeg: .ogv, .mp4, .mpeg, .avi, .mov etc.+ The name of the video file, as a string or a path-like object.+ It can have any extension supported by ffmpeg:+ .ogv, .mp4, .mpeg, .avi, .mov etc.has_mask:Set this to 'True' if there is a mask included in the videofile.@@ -75,6 +77,7 @@ class VideoFileClip(VideoClip):"""+ @convert_path_to_string("filename")def __init__(self,filename,@@ -108,7 +111,7 @@ class VideoFileClip(VideoClip):self.size = self.reader.sizeself.rotation = self.reader.rotation- self.filename = self.reader.filename+ self.filename = filenameif has_mask:diff --git a/moviepy/video/io/ffmpeg_tools.py b/moviepy/video/io/ffmpeg_tools.pyindex 8128de90..29806f37 100644--- a/moviepy/video/io/ffmpeg_tools.py+++ b/moviepy/video/io/ffmpeg_tools.py@@ -5,9 +5,11 @@ import subprocess as spimport sysfrom moviepy.config import get_setting+from moviepy.decorators import convert_path_to_stringfrom moviepy.tools import subprocess_call+@convert_path_to_string("filename")def ffmpeg_movie_from_frames(filename, folder, fps, digits=6, bitrate="v"):"""Writes a movie out of the frames (picture files) in a folder.@@ -33,6 +35,7 @@ def ffmpeg_movie_from_frames(filename, folder, fps, digits=6, bitrate="v"):subprocess_call(cmd)+@convert_path_to_string(("filename", "targetname"))def ffmpeg_extract_subclip(filename, t1, t2, targetname=None):""" Makes a new video file playing video file ``filename`` betweenthe times ``t1`` and ``t2``. """@@ -62,6 +65,7 @@ def ffmpeg_extract_subclip(filename, t1, t2, targetname=None):subprocess_call(cmd)+@convert_path_to_string(("video", "audio", "output"))def ffmpeg_merge_video_audio(video,audio,@@ -90,6 +94,7 @@ def ffmpeg_merge_video_audio(subprocess_call(cmd, logger=logger)+@convert_path_to_string(("inputfile", "output"))def ffmpeg_extract_audio(inputfile, output, bitrate=3000, fps=44100):""" extract the sound from a video file and save it in ``output`` """cmd = [@@ -106,6 +111,7 @@ def ffmpeg_extract_audio(inputfile, output, bitrate=3000, fps=44100):subprocess_call(cmd)+@convert_path_to_string(("video", "output"))def ffmpeg_resize(video, output, size):""" resizes ``video`` to new size ``size`` and write the resultin file ``output``. """diff --git a/moviepy/video/tools/credits.py b/moviepy/video/tools/credits.pyindex 5403eb41..edebd9dd 100644--- a/moviepy/video/tools/credits.py+++ b/moviepy/video/tools/credits.py@@ -3,12 +3,13 @@ This module contains different functions to make end and openingcredits, even though it is difficult to fill everyone needs in thismatter."""-+from moviepy.decorators import convert_path_to_stringfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClipfrom moviepy.video.fx.resize import resizefrom moviepy.video.VideoClip import ImageClip, TextClip+@convert_path_to_string("creditfile")def credits1(creditfile,width,@@ -26,7 +27,8 @@ def credits1(-----------creditfile- A text file whose content must be as follows: ::+ A string or path like object pointing to a text file+ whose content must be as follows: ::# This is a comment# The next line says : leave 4 blank linesdiff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.pyindex d0ae3974..9ec857d7 100644--- a/moviepy/video/tools/subtitles.py+++ b/moviepy/video/tools/subtitles.py@@ -4,6 +4,7 @@ import reimport numpy as np+from moviepy.decorators import convert_path_to_stringfrom moviepy.tools import cvsecsfrom moviepy.video.VideoClip import TextClip, VideoClip@@ -19,7 +20,8 @@ class SubtitlesClip(VideoClip):==========subtitles- Either the name of a file, or a list+ Either the name of a file as a string or path-like object, or a list+encodingOptional, specifies srt file encoding.Any standard Python encoding is allowed (listed at https://docs.python.org/3.8/library/codecs.html#standard-encodings)@@ -42,7 +44,8 @@ class SubtitlesClip(VideoClip):VideoClip.__init__(self, has_constant_size=False)- if isinstance(subtitles, str):+ if not isinstance(subtitles, list):+ # `subtitles` is a string or path-like objectsubtitles = file_to_subtitles(subtitles, encoding=encoding)# subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]@@ -148,6 +151,7 @@ class SubtitlesClip(VideoClip):f.write(str(self))+@convert_path_to_string("filename")def file_to_subtitles(filename, encoding=None):""" Converts a srt file into subtitles.diff --git a/tests/test_PR.py b/tests/test_PR.pyindex 3cabb888..4dd8ef5f 100644--- a/tests/test_PR.py+++ b/tests/test_PR.py@@ -2,21 +2,23 @@"""Pull request tests meant to be run with pytest."""import osimport sys+from pathlib import Pathimport pytest+from moviepy.audio.io.AudioFileClip import AudioFileClipfrom moviepy.utils import close_all_clipsfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClipfrom moviepy.video.fx.scroll import scrollfrom moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.tools.interpolators import Trajectoryfrom moviepy.video.VideoClip import ColorClip, ImageClip, TextClip+from moviepy.video.tools.subtitles import SubtitlesClipfrom .test_helper import FONT, TMP_DIRdef test_PR_306():-assert TextClip.list("font") != []assert TextClip.list("color") != []@@ -100,5 +102,48 @@ def test_PR_610():assert composite.fps == 25+def test_PR_1137_video():+ """+ Test support for path-like objects as arguments for VideoFileClip.+ """+ with VideoFileClip(Path("media/big_buck_bunny_432_433.webm")) as video:+ video.write_videofile(Path(TMP_DIR) / "pathlike.mp4")+ assert isinstance(video.filename, str)+++def test_PR_1137_audio():+ """+ Test support for path-like objects as arguments for AudioFileClip.+ """+ with AudioFileClip(Path("media/crunching.mp3")) as audio:+ audio.write_audiofile(Path(TMP_DIR) / "pathlike.mp3")+ assert isinstance(audio.filename, str)+++def test_PR_1137_image():+ """+ Test support for path-like objects as arguments for ImageClip.+ """+ ImageClip(Path("media/vacation_2017.jpg")).close()+++def test_PR_1137_subtitles():+ """+ Test support for path-like objects as arguments for SubtitlesClip.+ """++ def make_textclip(txt):+ return TextClip(+ txt,+ font=FONT,+ fontsize=24,+ color="white",+ stroke_color="black",+ stroke_width=0.5,+ )++ SubtitlesClip(Path("media/subtitles1.srt"), make_textclip=make_textclip).close()++if __name__ == "__main__":pytest.main()