Video editing with Python
Changed doc theme, simplified to_gif command for Windows compatibility, made function call_subprocess
Zulkocda376a884e0
diff --git a/docs/_themes/flask/layout.html b/docs/_themes/flask/layout.htmlindex 56ae04bc..0039546d 100644--- a/docs/_themes/flask/layout.html+++ b/docs/_themes/flask/layout.html@@ -7,7 +7,9 @@<link media="only screen and (max-device-width: 480px)" href="{{pathto('_static/small_flask.css', 1) }}" type= "text/css" rel="stylesheet" />{% endblock %}+{%- block relbar2 %}{% endblock %}+{% block header %}{{ super() }}{% if pagename == 'index' %}diff --git a/docs/_themes/flask/static/flasky.css_t b/docs/_themes/flask/static/flasky.css_tindex b5ca39bc..08bb88c0 100644--- a/docs/_themes/flask/static/flasky.css_t+++ b/docs/_themes/flask/static/flasky.css_t@@ -162,6 +162,15 @@ div.body h6 {padding: 0;}++div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }+div.body h2 { font-size: 180%; }+div.body h3 { font-size: 150%; }+div.body h4 { font-size: 130%; }+div.body h5 { font-size: 100%; }+div.body h6 { font-size: 100%; }++{% if theme_index_logo %}div.indexwrapper h1 {text-indent: -999999px;@@ -170,12 +179,6 @@ div.indexwrapper h1 {}{% endif %}-div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }-div.body h2 { font-size: 180%; }-div.body h3 { font-size: 150%; }-div.body h4 { font-size: 130%; }-div.body h5 { font-size: 100%; }-div.body h6 { font-size: 100%; }a.headerlink {color: #ddd;diff --git a/docs/conf.py b/docs/conf.pyindex 93f309f6..d20e6018 100644--- a/docs/conf.py+++ b/docs/conf.py@@ -97,7 +97,7 @@ pygments_style = 'sphinx'sys.path.append(os.path.abspath('_themes'))sys.path.append("../moviepy")html_theme_path = ['_themes']-html_theme = 'flask'+html_theme = 'kr'# Theme options are theme-specific and customize the look and feel of a theme# further. For a list of options available for each theme, see thediff --git a/docs/index.rst b/docs/index.rstindex 12242400..9eb9d531 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -1,7 +1,9 @@MoviePy=======-MoviePy is a Python module for script-based movie editing, which enables basic operations (cuts, concatenations, title insertions) to be done in a few lines, but can also be used for advanced compositing and special effects. Let me put together the clips in my demonstration folder (you will find the code for most clips in the :ref:`examples`): ::+MoviePy is a Python module for script-based movie editing. It enables basic operations (cuts, concatenations, title insertions) to be done in a few lines, and can be used for advanced compositing and special effects.++Let us put together a few demonstration clips (you will find the code for most clips in the :ref:`examples`): ::import osfrom moviepy.editor import *diff --git a/moviepy/decorators.py b/moviepy/decorators.pyindex b73bf812..81787772 100644--- a/moviepy/decorators.py+++ b/moviepy/decorators.py@@ -5,6 +5,7 @@ all decorators used in moviepy go thereimport decoratorfrom moviepy.tools import cvsecs+@decorator.decoratordef apply_to_mask(f, clip, *a, **k):""" This decorator will apply the same function f to the mask ofdiff --git a/moviepy/tools.py b/moviepy/tools.pyindex 88a18305..4104ddc8 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -2,6 +2,37 @@Misc. useful functions that can be used at many places in the program."""+import subprocess as sp+import sys++def sys_write_flush(s):+ """ writes and flushes witout delay a text in the console """+ sys.stdout.write(s)+ sys.stdout.flush()+++def subprocess_call(cmd, stdout=None, stdin = None,+ stderr = sp.PIPE, verbose=True, errorprint=True):+ """+ executes the subprocess command+ """++ verboseprint = sys_write_flush if verbose else (lambda *a : None)++ verboseprint( "\nMoviePy Running:\n>>> "+ " ".join(cmd) )++ proc = sp.Popen(cmd, stdout=stdout,+ stdin = stdin,+ stderr = stderr)+ proc.wait()++ if proc.returncode and errorprint:+ sys_write_flush( "\nWARNING: this command returned an error:")+ sys_write_flush( proc.stderr.read().decode('utf8'))+ else:+ verboseprint( "\n... command successful.\n")++def cvsecs(*args):"""Converts a time to second. Either cvsecs(min,secs) ordiff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 8ac13399..3811d584 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -17,7 +17,10 @@ from tqdm import tqdmimport numpy as np-from moviepy.decorators import apply_to_mask, requires_duration+from moviepy.decorators import (apply_to_mask,+ requires_duration)++from moviepy.tools import subprocess_call, sys_write_flushimport moviepy.audio.io as aiofrom .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video@@ -186,12 +189,8 @@ class VideoClip(Clip):elif audio_codec == 'raw32':audio_codec = 'pcm_s32le'- if verbose:- def verbose_print(s):- sys.stdout.write(s)- sys.stdout.flush()- else:- verbose_print = lambda *a : None+ verbose_print = (sys_write_flush if verbose+ else (lambda *a : None) )if isinstance(audio, str):# audio is some audiofile it is maybe not a wav file. It is@@ -291,9 +290,11 @@ class VideoClip(Clip):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 given- by the clip's ``pos`` attribute. Meant for compositing. """+ """+ Returns the result of the blit of the clip's frame at time `t`+ on the given `picture`, the position of the clip being given+ by the clip's ``pos`` attribute. Meant for compositing.+ """hf, wf = sizef = picture.shape[:2]@@ -387,7 +388,7 @@ class VideoClip(Clip):for i, t in enumerate(tt):- name = "%s_TEMP%04d.png"%(fileName,i+1)+ name = "%s_GIFTEMP%04d.png"%(fileName,i+1)tempfiles.append(name)self.save_frame(name, t, savemask=True)@@ -395,35 +396,29 @@ class VideoClip(Clip):if program == "ImageMagick":- cmd = ("convert -delay %d"%delay +- " -dispose %d"%(2 if dispose else 1)+- " -loop %d"%loop+- " `seq -f %s"%fileName +"_TEMP%04g.png"+- " 1 1 %d`"%len(tt) +- " -coalesce -fuzz %02d"%fuzz + "%"+- " -layers %s %s"%(opt,filename))-- verboseprint("running %s"%cmd)-- os.system(cmd)+ cmd = ["convert",+ '-delay' , '%d'%delay,+ "-dispose" ,"%d"%(2 if dispose else 1),+ "-loop" , "%d"%loop,+ "%s_GIFTEMP*.png"%fileName,+ "-coalesce",+ "-fuzz", "%02d"%fuzz + "%",+ "-layers", "%s"%opt,+ "%s"%filename]elif program == "ffmpeg":- cmd = [FFMPEG_BINARY,'-y', '-f', 'image2',- '-i', fileName+'_TEMP%04d.png',+ cmd = [FFMPEG_BINARY, '-y',+ '-f', 'image2',+ '-i', fileName+'_GIFTEMP%04d.png','-r',str(fps),filename]-- proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE)- proc.wait()- print( proc.stderr )-+++ subprocess_call( cmd )+for f in tempfiles:os.remove(f)-- verboseprint('GIF generated !')#-----------------------------------------------------------------# F I L T E R I N G@@ -867,11 +862,7 @@ class TextClip(ImageClip):if print_cmd:print( " ".join(cmd) )- proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)- proc.wait()- if proc.returncode:- print ("Error: problem in the generation of the text file"+- "by ImageMagick. Certainly wrong arguments in TextClip")+ subprocess_call(cmd)ImageClip.__init__(self, tempfile, transparent=transparent)self.txt = txtdiff --git a/moviepy/video/fx/crop.py b/moviepy/video/fx/crop.pyindex a60e7659..29d3b475 100644--- a/moviepy/video/fx/crop.py+++ b/moviepy/video/fx/crop.py@@ -8,19 +8,25 @@ def crop(clip, x1=None, y1=None, x2=None, y2=None,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:- Rectangle centered in x=300, with explicit y-boundaries:+ >>> 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(x_center=300, width=400, y1=100, y2=600)"""diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.pyindex 90495351..57370b47 100644--- a/moviepy/video/fx/resize.py+++ b/moviepy/video/fx/resize.py@@ -9,6 +9,7 @@ try:except ImportError:+try:from PIL import Image@@ -35,6 +36,8 @@ except ImportError:except ImportError:resize_possible = False++from moviepy.decorators import apply_to_maskdiff --git a/moviepy/video/io/ffmpeg_tools.py b/moviepy/video/io/ffmpeg_tools.pyindex b85e4774..0d74ecae 100644--- a/moviepy/video/io/ffmpeg_tools.py+++ b/moviepy/video/io/ffmpeg_tools.py@@ -4,40 +4,26 @@ import osimport sysimport subprocess as sp+from moviepy.tools import subprocess_call+-import decorator---def subprocess_call(f, *a, **k):+def ffmpeg_movie_from_frames(filename, folder, fps, digits=6):"""- executes the outputed subprocess command+ Writes a movie out of the frames (picture files) in a folder.+ Almost deprecated."""- cmd = f(*a, **k)- sys.stdout.write( "\nRunning:\n>>> "+ " ".join(cmd))- sys.stdout.flush()- proc = sp.Popen(cmd, stdout=sp.PIPE, stdin = sp.PIPE, stderr = sp.PIPE)- proc.wait()- if proc.returncode:- sys.stdout.write( "\nWARNING: this command returned an error:")- sys.stdout.write(proc.stderr.read().decode('utf8'))- else:- sys.stdout.write( "\n... ffmpeg command successful.\n")- sys.stdout.flush()--@subprocess_call-def movie_from_frames(filename, folder, fps, digits=6):- """ Writes a movie out of the frames (picture files) in a folder """s = "%" + "%02d" % digits + "d.png"- return ["ffmpeg", "-y", "-f","image2",+ cmd = ["ffmpeg", "-y", "-f","image2","-r", "%d"%fps,"-i", os.path.join(folder,folder) + '/' + s,"-b", "%dk"%bitrate,"-r", "%d"%self.fps,filename]++ subprocess_call(cmd, stdin=None, stdout=None)-@subprocess_call-def extract_subclip(filename, t1, t2, targetname=None):++def ffmpeg_extract_subclip(filename, t1, t2, targetname=None):""" makes a new video file playing video file ``filename`` betweenthe times ``t1`` and ``t2``. """name,ext = os.path.splitext(filename)@@ -45,31 +31,37 @@ def extract_subclip(filename, t1, t2, targetname=None):T1, T2 = [int(1000*t) for t in [t1, t2]]targetname = name+ "%sSUB%d_%d.%s"(name, T1, T2, ext)- return ["ffmpeg","-y",+ cmd = ["ffmpeg","-y","-i", filename,"-ss", "%0.2f"%t1,"-t", "%0.2f"%(t2-t1),"-vcodec", "copy", "-acodec", "copy", targetname]-++ subprocess_call(cmd, stdin=None, stdout=None)+-@subprocess_calldef ffmpeg_merge_video_audio(video,audio,output,vcodec='copy', acodec='copy', ffmpeg_output=False):""" merges video file ``video`` and audio file ``audio`` into onemovie file ``output``. """- return ["ffmpeg", "-y", "-i", audio,"-i", video,+ cmd = ["ffmpeg", "-y", "-i", audio,"-i", video,"-vcodec", vcodec, "-acodec", acodec, output]++ subprocess_call(cmd, stdin=None, stdout=None)-@subprocess_call-def extract_audio(inputfile,output,bitrate=3000,fps=44100):++def ffmpeg_extract_audio(inputfile,output,bitrate=3000,fps=44100):""" extract the sound from a video file and save it in ``output`` """- return ["ffmpeg", "-y", "-i", inputfile, "-ab", "%dk"%bitrate,+ cmd = ["ffmpeg", "-y", "-i", inputfile, "-ab", "%dk"%bitrate,"-ar", "%d"%fps, output]+ subprocess_call(cmd, stdin=None, stdout=None)-@subprocess_call-def resize(video,output,size):++def ffmpeg_resize(video,output,size):""" resizes ``video`` to new size ``size`` and write the resultin file ``output``. """- return ["ffmpeg", "-i", video, "-vf", "scale=%d:%d"%(res[0], res[1]),+ cmd= ["ffmpeg", "-i", video, "-vf", "scale=%d:%d"%(res[0], res[1]),output]++ subprocess_call(cmd, stdin=None, stdout=None)diff --git a/moviepy/video/io/imageMagick_tools.py b/moviepy/video/io/imageMagick_tools.pyindex f9bd3674..17938a5d 100644--- a/moviepy/video/io/imageMagick_tools.py+++ b/moviepy/video/io/imageMagick_tools.py@@ -1,8 +1,7 @@import osimport subprocess-from moviepy.conf import FFMPEG_BINARY+from moviepy.tools import subprocess_call-@subprocess_calldef gif_to_directory(gif_file,dirName=None):"""Stores all the frames of the given .gif file@@ -27,5 +26,5 @@ def gif_to_directory(gif_file,dirName=None):except:pass- return ["convert", "-coalesce", gif_file,- os.path.join(dirName,"%04d.png")]+ subprocess_call ["convert", "-coalesce", gif_file,+ os.path.join(dirName,"%04d.png")])