Skip to content

Video editing with Python

Rename ipython_display to display_in_notebook

osaajani3da8b0ed7f2c
diff --git a/moviepy/__init__.py b/moviepy/__init__.py
index 6b8f9ae0..63cc74b2 100644
--- a/moviepy/__init__.py
+++ b/moviepy/__init__.py
@@ -23,7 +23,7 @@ from moviepy.video import fx as vfx, tools as videotools
from moviepy.video.compositing import transitions as transfx
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip, clips_array, concatenate_videoclips
from moviepy.video.io import ffmpeg_tools
-from moviepy.video.io.downloader import download_webfile
+from moviepy.video.io.display_in_notebook import display_in_notebook
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.VideoClip import (
@@ -53,23 +53,12 @@ for name, function in video_fxs:
for name, function in audio_fxs:
setattr(AudioClip, name, function)
-
-def preview(self, *args, **kwargs):
- """NOT AVAILABLE: clip.preview requires importing from moviepy.editor"""
- raise ImportError("clip.preview requires importing from moviepy.editor")
-
-
-def show(self, *args, **kwargs):
- """NOT AVAILABLE: clip.show requires importing from moviepy.editor"""
- raise ImportError("clip.show requires importing from moviepy.editor")
-
-
-VideoClip.preview = preview
-VideoClip.show = show
-AudioClip.preview = preview
+# Add display in notebook to video and audioclip
+VideoClip.display_in_notebook = display_in_notebook
+AudioClip.display_in_notebook = display_in_notebook
# Cleanup namespace
-del audio_fxs, video_fxs, name, function, preview, show
+del audio_fxs, video_fxs, name, function
del inspect
# Importing with `from moviepy import *` will only import these names
@@ -87,7 +76,6 @@ __all__ = [
"clips_array",
"ImageSequenceClip",
"concatenate_videoclips",
- "download_webfile",
"AudioClip",
"AudioArrayClip",
"CompositeAudioClip",
diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.py
index d779873a..22681e9a 100644
--- a/moviepy/audio/AudioClip.py
+++ b/moviepy/audio/AudioClip.py
@@ -11,6 +11,7 @@ import numpy as np
import proglog
from moviepy.audio.io.ffmpeg_audiowriter import ffmpeg_audiowrite
+from moviepy.audio.io.ffplay_audiopreviewer import ffplay_audiopreview
from moviepy.Clip import Clip
from moviepy.decorators import convert_path_to_string, requires_duration
from moviepy.tools import extensions_dict
@@ -264,6 +265,43 @@ class AudioClip(Clip):
ffmpeg_params=ffmpeg_params,
logger=logger,
)
+
+ @requires_duration
+ def audiopreview(
+ self,
+ fps=None,
+ buffersize=2000,
+ nbytes=2,
+ audio_flag=None,
+ video_flag=None
+ ):
+ """
+ Preview an AudioClip using ffplay
+
+ Parameters
+ ----------
+
+ fps
+ Frame rate of the sound. 44100 gives top quality, but may cause
+ problems if your computer is not fast enough and your clip is
+ complicated. If the sound jumps during the preview, lower it
+ (11025 is still fine, 5000 is tolerable).
+
+ buffersize
+ The sound is not generated all at once, but rather made by bunches
+ of frames (chunks). ``buffersize`` is the size of such a chunk.
+ Try varying it if you meet audio problems (but you shouldn't
+ have to).
+
+ nbytes:
+ Number of bytes to encode the sound: 1 for 8bit sound, 2 for
+ 16bit, 4 for 32bit sound. 2 bytes is fine.
+
+ audio_flag, video_flag:
+ Instances of class threading events that are used to synchronize
+ video and audio during ``VideoClip.preview()``.
+ """
+ ffplay_audiopreview(clip=self, fps=fps, buffersize=buffersize, nbytes=nbytes, audio_flag=audio_flag, video_flag=video_flag)
def __add__(self, other):
if isinstance(other, AudioClip):
diff --git a/moviepy/audio/io/ffplay_audiopreviewer.py b/moviepy/audio/io/ffplay_audiopreviewer.py
index 2416eedc..0ecd2aaf 100644
--- a/moviepy/audio/io/ffplay_audiopreviewer.py
+++ b/moviepy/audio/io/ffplay_audiopreviewer.py
@@ -2,9 +2,7 @@
import subprocess as sp
-import proglog
-
-from moviepy.config import FFMPEG_BINARY, FFPLAY_BINARY
+from moviepy.config import FFPLAY_BINARY
from moviepy.decorators import requires_duration
from moviepy.tools import cross_platform_popen_params
diff --git a/moviepy/editor.py b/moviepy/editor.py
deleted file mode 100644
index 0a8f64b2..00000000
--- a/moviepy/editor.py
+++ /dev/null
@@ -1,63 +0,0 @@
-"""
-Module meant to make it easy to load the features of MoviePy that you will use
-for live editing by simply typing:
-
->>> from moviepy.editor import *
-
-- Enables ``clip.ipython_display()`` if in an IPython Notebook
-- Allows the use of ``sliders`` if Matplotlib is installed
-"""
-
-import os
-
-import moviepy # So that we can access moviepy.__all__ later
-from moviepy import *
-from moviepy.video.io.html_tools import ipython_display
-
-
-
-try:
- from moviepy.video.io.sliders import sliders
-except ImportError:
-
- def sliders(*args, **kwargs):
- """NOT AVAILABLE: sliders requires matplotlib installed."""
- raise ImportError("sliders requires matplotlib installed")
-
-
-# adds easy ipython integration
-VideoClip.ipython_display = ipython_display
-AudioClip.ipython_display = ipython_display
-
-
-# Add methods preview and show (only if pygame installed)
-try:
- from moviepy.video.io.preview import show, preview
-except ImportError:
-
- def preview(self, *args, **kwargs):
- """NOT AVAILABLE: clip.preview requires Pygame installed."""
- raise ImportError("clip.preview requires Pygame installed")
-
- def show(self, *args, **kwargs):
- """NOT AVAILABLE: clip.show requires Pygame installed."""
- raise ImportError("clip.show requires Pygame installed")
-
-
-VideoClip.preview = preview
-VideoClip.show = show
-
-try:
- from moviepy.audio.io.ffplay_audiopreviewer import ffplay_audiopreview
-except ImportError:
-
- def preview(self, *args, **kwargs):
- """NOT AVAILABLE: clip.preview requires Pygame installed."""
- raise ImportError("clip.preview requires Pygame installed")
-
-
-AudioClip.preview = ffplay_audiopreview
-
-__all__ = moviepy.__all__ + ["ipython_display", "sliders"]
-
-del show, preview, ffplay_audiopreview
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index 47fcce81..677e7bdf 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -6,8 +6,6 @@
import copy as _copy
import os
-import subprocess as sp
-import tempfile
from numbers import Real
import numpy as np
@@ -15,7 +13,10 @@ import proglog
from imageio import imread, imsave
from PIL import Image, ImageDraw, ImageFont
-from typing import List, Dict
+import threading
+from moviepy.video.io.ffplay_previewer import ffplay_preview_video
+
+from typing import List
from moviepy.Clip import Clip
from moviepy.decorators import (
@@ -29,11 +30,10 @@ from moviepy.decorators import (
requires_fps,
use_clip_fps_by_default,
)
+
from moviepy.tools import (
- cross_platform_popen_params,
extensions_dict,
find_extension,
- subprocess_call,
)
from moviepy.video.io.ffmpeg_writer import ffmpeg_write_video
from moviepy.video.io.gif_writers import (
@@ -507,6 +507,114 @@ class VideoClip(Clip):
logger=logger,
)
+
+ # ===============================================================
+ # PREVIEW OPERATIONS
+
+ @convert_masks_to_RGB
+ @convert_parameter_to_seconds(["t"])
+ def show(self, t=0, with_mask=True):
+ """
+ Splashes the frame of clip corresponding to time ``t``.
+
+ Parameters
+ ----------
+
+ t : float or tuple or str, optional
+ Time in seconds of the frame to display.
+
+ with_mask : bool, optional
+ ``False`` if the clip has a mask but you want to see the clip without
+ the mask.
+
+ Examples
+ --------
+
+ >>> from moviepy import *
+ >>>
+ >>> clip = VideoFileClip("media/chaplin.mp4")
+ >>> clip.show(t=4, interactive=True)
+ """
+ clip = self.copy()
+ if with_mask and (self.mask is not None):
+ # Hate it, but cannot figure a better way with python awful circular dependency
+ from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
+
+ clip = CompositeVideoClip([self.with_position((0, 0))])
+
+ img = clip.get_frame(t)
+ pil_img = Image.fromarray(img)
+
+ pil_img.show()
+
+
+ @requires_duration
+ @convert_masks_to_RGB
+ def preview(
+ self,
+ fps=15,
+ audio=True,
+ audio_fps=22050,
+ audio_buffersize=3000,
+ audio_nbytes=2
+ ):
+ """
+ Displays the clip in a window, at the given frames per second (of movie)
+ rate. It will avoid that the clip be played faster than normal, but it
+ cannot avoid the clip to be played slower than normal if the computations
+ are complex. In this case, try reducing the ``fps``.
+
+ Parameters
+ ----------
+
+ fps : int, optional
+ Number of frames per seconds in the displayed video. Default to ``15``.
+
+ audio : bool, optional
+ ``True`` (default) if you want the clip's audio be played during
+ the preview.
+
+ audio_fps : int, optional
+ The frames per second to use when generating the audio sound.
+
+ audio_buffersize : int, optional
+ The sized of the buffer used generating the audio sound.
+
+ audio_nbytes : int, optional
+ The number of bytes used generating the audio sound.
+
+ Examples
+ --------
+
+ >>> from moviepy import *
+ >>>
+ >>> clip = VideoFileClip("media/chaplin.mp4")
+ >>> clip.preview(fps=10, audio=False)
+ """
+
+ audio = audio and (self.audio is not None)
+ audio_flag = None
+ video_flag = None
+
+ if audio:
+ # the sound will be played in parallel. We are not
+ # parralellizing it on different CPUs because it seems that
+ # ffplay use several cpus.
+
+ # two synchro-flags to tell whether audio and video are ready
+ video_flag = threading.Event()
+ audio_flag = threading.Event()
+ # launch the thread
+ audiothread = threading.Thread(
+ target=self.audio.preview,
+ args=(audio_fps, audio_buffersize, audio_nbytes, audio_flag, video_flag),
+ )
+ audiothread.start()
+
+ # passthrough to ffmpeg, passing flag for ffmpeg to set
+ ffplay_preview_video(clip=self, fps=fps, audio_flag=audio_flag, video_flag=video_flag)
+
+
# -----------------------------------------------------------------
# F I L T E R I N G
diff --git a/moviepy/video/io/bindings.py b/moviepy/video/io/bindings.py
deleted file mode 100644
index 0a016dda..00000000
--- a/moviepy/video/io/bindings.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""Implements all the functions to communicate with other Python modules (PIL,
-matplotlib, mayavi, etc.)
-"""
-
-import numpy as np
-
-
-def mplfig_to_npimage(fig):
- """Converts a matplotlib figure to a RGB frame after updating the canvas."""
- # only the Agg backend now supports the tostring_rgb function
- from matplotlib.backends.backend_agg import FigureCanvasAgg
-
- canvas = FigureCanvasAgg(fig)
- canvas.draw() # update/draw the elements
-
- # get the width and the height to resize the matrix
- l, b, w, h = canvas.figure.bbox.bounds
- w, h = int(w), int(h)
-
- # exports the canvas to a string buffer and then to a numpy nd.array
- buf = canvas.tostring_rgb()
- image = np.frombuffer(buf, dtype=np.uint8)
- return image.reshape(h, w, 3)
diff --git a/moviepy/video/io/html_tools.py b/moviepy/video/io/display_in_notebook.py
similarity index 91%
rename from moviepy/video/io/html_tools.py
rename to moviepy/video/io/display_in_notebook.py
index d18b6a4e..156719fc 100644
--- a/moviepy/video/io/html_tools.py
+++ b/moviepy/video/io/display_in_notebook.py
@@ -1,9 +1,9 @@
-"""Implements ``ipython_display``, a function to embed images/videos/audio in the
-IPython Notebook.
+"""Implements ``display_in_notebook``, a function to embed images/videos/audio in the
+Jupyter Notebook.
"""
# Notes:
-# All media are physically embedded in the IPython Notebook
+# All media are physically embedded in the Jupyter Notebook
# (instead of simple links to the original files)
# That is because most browsers use a cache system and they won't
# properly refresh the media when the original files are changed.
@@ -89,7 +89,7 @@ def html_embed(
Examples
--------
- >>> from moviepy.editor import *
+ >>> from moviepy import *
>>> # later ...
>>> html_embed(clip, width=360)
>>> html_embed(clip.audio)
@@ -149,7 +149,7 @@ def html_embed(
raise ValueError(
"No file type is known for the provided file. Please provide "
"argument `filetype` (one of 'image', 'video', 'sound') to the "
- "ipython display function."
+ "display_in_notebook function."
)
if filetype == "video":
@@ -162,7 +162,7 @@ def html_embed(
except Exception:
raise ValueError(
"This video extension cannot be displayed in the "
- "IPython Notebook. Allowed extensions: " + allowed_exts
+ "Jupyter Notebook. Allowed extensions: " + allowed_exts
)
if filetype in ["audio", "video"]:
@@ -172,7 +172,7 @@ def html_embed(
(
"The duration of video %s (%.1f) exceeds the 'maxduration'"
" attribute. You can increase 'maxduration', by passing"
- " 'maxduration' parameter to ipython_display function."
+ " 'maxduration' parameter to display_in_notebook function."
" But note that embedding large videos may take all the memory"
" away!"
)
@@ -191,7 +191,7 @@ def html_embed(
return result
-def ipython_display(
+def display_in_notebook(
clip,
filetype=None,
maxduration=60,
@@ -201,7 +201,7 @@ def ipython_display(
center=True,
**html_kwargs,
):
- """Displays clip content in an IPython Notebook.
+ """Displays clip content in an Jupyter Notebook.
Remarks: If your browser doesn't support HTML5, this should warn you.
If nothing is displayed, maybe your file or filename is wrong.
@@ -246,19 +246,19 @@ def ipython_display(
Examples
--------
- >>> from moviepy.editor import *
+ >>> from moviepy import *
>>> # later ...
- >>> clip.ipython_display(width=360)
- >>> clip.audio.ipython_display()
+ >>> clip.display_in_notebook(width=360)
+ >>> clip.audio.display_in_notebook()
>>> clip.write_gif("test.gif")
- >>> ipython_display('test.gif')
+ >>> display_in_notebook('test.gif')
>>> clip.save_frame("first_frame.jpeg")
- >>> ipython_display("first_frame.jpeg")
+ >>> display_in_notebook("first_frame.jpeg")
"""
if not ipython_available:
- raise ImportError("Only works inside an IPython Notebook")
+ raise ImportError("Only works inside an Jupyter Notebook")
if rd_kwargs is None:
rd_kwargs = {}
diff --git a/moviepy/video/io/downloader.py b/moviepy/video/io/downloader.py
deleted file mode 100644
index 293c86fe..00000000
--- a/moviepy/video/io/downloader.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""Utilities to get a file from the internet."""
-
-import os
-import shutil
-import urllib.request
-
-from moviepy.tools import subprocess_call
-
-
-def download_webfile(url, filename, overwrite=False):
- """Small utility to download the file at ``url`` under name ``filename``.
-
- Parameters
- ----------
-
- url : str
- If url is a youtube video ID like z410eauCnH it will download the video
- using youtube-dl. Requires youtube-dl (pip install youtube-dl).
-
- filename : str
- Path to the new downloaded file location.
-
- overwrite : bool, optional
- If the filename already exists and overwrite=False, nothing will happen.
- Use it to force destination file overwriting.
-
- Examples
- --------
-
- >>> from moviepy.io.downloader import download_website
- >>>
- >>> download_website(
- ... "http://localhost:8000/media/chaplin.mp4",
- ... "media/chaplin-copy.mp4",
- ... )
- >>>
- """
- if os.path.exists(filename) and not overwrite: # pragma: no cover
- return
-
- if "." in url:
- with urllib.request.urlopen(url) as req, open(filename, "wb") as f:
- shutil.copyfileobj(req, f, 128)
-
- else:
- try:
- subprocess_call(["youtube-dl", url, "-o", filename])
- except OSError as e:
- raise OSError(
- (
- "Error running youtube-dl.\n%sA possible reason is that"
- " youtube-dl is not installed on your computer. Install it "
- " with 'pip install youtube_dl'."
- )
- % ((e.message + "\n" if hasattr(e, "message") else ""))
- )
diff --git a/moviepy/video/io/preview.py b/moviepy/video/io/preview.py
deleted file mode 100644
index a187b0b1..00000000
--- a/moviepy/video/io/preview.py
+++ /dev/null
@@ -1,115 +0,0 @@
-"""Video preview functions for MoviePy editor."""
-
-import threading
-import time
-import numpy as np
-from PIL import Image
-
-from moviepy.decorators import (
- convert_masks_to_RGB,
- convert_parameter_to_seconds,
- requires_duration,
-)
-from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
-
-from moviepy.video.io.ffplay_previewer import ffplay_preview_video
-
-
-@convert_masks_to_RGB
-@convert_parameter_to_seconds(["t"])
-def show(clip, t=0, with_mask=True):
- """
- Splashes the frame of clip corresponding to time ``t``.
-
- Parameters
- ----------
-
- t : float or tuple or str, optional
- Time in seconds of the frame to display.
-
- with_mask : bool, optional
- ``False`` if the clip has a mask but you want to see the clip without
- the mask.
-
- Examples
- --------
-
- >>> from moviepy.editor import *
- >>>
- >>> clip = VideoFileClip("media/chaplin.mp4")
- >>> clip.show(t=4, interactive=True)
- """
- if with_mask and (clip.mask is not None):
- clip = CompositeVideoClip([clip.with_position((0, 0))])
-
- img = clip.get_frame(t)
- pil_img = Image.fromarray(img)
-
- pil_img.show()
-
-
-@requires_duration
-@convert_masks_to_RGB
-def preview(
- clip,
- fps=15,
- audio=True,
- audio_fps=22050,
- audio_buffersize=3000,
- audio_nbytes=2
-):
- """
- Displays the clip in a window, at the given frames per second (of movie)
- rate. It will avoid that the clip be played faster than normal, but it
- cannot avoid the clip to be played slower than normal if the computations
- are complex. In this case, try reducing the ``fps``.
-
- Parameters
- ----------
-
- fps : int, optional
- Number of frames per seconds in the displayed video. Default to ``15``.
-
- audio : bool, optional
- ``True`` (default) if you want the clip's audio be played during
- the preview.
-
- audio_fps : int, optional
- The frames per second to use when generating the audio sound.
-
- audio_buffersize : int, optional
- The sized of the buffer used generating the audio sound.
-
- audio_nbytes : int, optional
- The number of bytes used generating the audio sound.
-
- Examples
- --------
-
- >>> from moviepy.editor import *
- >>>
- >>> clip = VideoFileClip("media/chaplin.mp4")
- >>> clip.preview(fps=10, audio=False)
- """
-
- audio = audio and (clip.audio is not None)
- audio_flag = None
- video_flag = None
-
- if audio:
- # the sound will be played in parallel. We are not
- # parralellizing it on different CPUs because it seems that
- # ffplay use several cpus.
-
- # two synchro-flags to tell whether audio and video are ready
- video_flag = threading.Event()
- audio_flag = threading.Event()
- # launch the thread
- audiothread = threading.Thread(
- target=clip.audio.preview,
- args=(audio_fps, audio_buffersize, audio_nbytes, audio_flag, video_flag),
- )
- audiothread.start()
-
- # passthrough to ffmpeg, passing flag for ffmpeg to set
- ffplay_preview_video(clip=clip, fps=fps, audio_flag=audio_flag, video_flag=video_flag)
diff --git a/moviepy/video/io/sliders.py b/moviepy/video/io/sliders.py
deleted file mode 100644
index d8172407..00000000
--- a/moviepy/video/io/sliders.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""GUI matplotlib utility to tune the outputs of a function."""
-
-import matplotlib.pyplot as plt
-from matplotlib.widgets import Slider
-
-
-def sliders(func, sliders_properties, wait_for_validation=False):
- """A light GUI to manually explore and tune the outputs of a function.
-
- ``slider_properties`` is a list of dicts (arguments for Slider)::
-
- def volume(x,y,z):
- return x*y*z
-
- intervals = [ { 'label' : 'width', 'valmin': 1 , 'valmax': 5 },
- { 'label' : 'height', 'valmin': 1 , 'valmax': 5 },
- { 'label' : 'depth', 'valmin': 1 , 'valmax': 5 } ]
- inputExplorer(volume, intervals)
-
- """
- n_vars = len(sliders_properties)
- slider_width = 1.0 / n_vars
-
- # CREATE THE CANVAS
-
- figure, ax = plt.subplots(1)
- figure.canvas.set_window_title("Inputs for '%s'" % (func.func_name))
-
- # choose an appropriate height
-
- width, height = figure.get_size_inches()
- height = min(0.5 * n_vars, 8)
- figure.set_size_inches(width, height, forward=True)
-
- # hide the axis
- ax.set_frame_on(False)
- ax.get_xaxis().set_visible(False)
- ax.get_yaxis().set_visible(False)
-
- # CREATE THE SLIDERS
-
- sliders = []
-
- for i, properties in enumerate(sliders_properties):
- ax = plt.axes(
- [0.1, 0.95 - 0.9 * (i + 1) * slider_width, 0.8, 0.8 * slider_width]
- )
- if not isinstance(properties, dict):
- properties = dict(zip(["label", "valmin", "valmax", "valinit"], properties))
- sliders.append(Slider(ax=ax, **properties))
-
- # CREATE THE CALLBACK FUNCTIONS
-
- def on_changed(event):
- res = func(*(s.val for s in sliders))
- if res is not None:
- print(res)
-
- def on_key_press(event):
- if event.key == "enter":
- on_changed(event)
-
- figure.canvas.mpl_connect("key_press_event", on_key_press)
-
- # AUTOMATIC UPDATE ?
-
- if not wait_for_validation:
- for s in sliders:
- s.on_changed(on_changed)
-
- # DISPLAY THE SLIDERS
- plt.show()
diff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.py
index 3fb16350..6d09979f 100644
--- a/moviepy/video/tools/cuts.py
+++ b/moviepy/video/tools/cuts.py
@@ -28,7 +28,7 @@ def find_video_period(clip, fps=None, start_time=0.3):
Examples
--------
- >>> from moviepy.editor import *
+ >>> from moviepy import *
>>> from moviepy.video.tools.cuts import find_video_period
>>>
>>> clip = VideoFileClip("media/chaplin.mp4").with_subclip(0, 1).loop(2)
@@ -339,7 +339,7 @@ class FramesMatches(list):
--------
>>> from pprint import pprint
- >>> from moviepy.editor import *
+ >>> from moviepy import *
>>> from moviepy.video.tools.cuts import FramesMatches
>>>
>>> ch_clip = VideoFileClip("media/chaplin.mp4").with_subclip(1, 4)
@@ -426,7 +426,7 @@ class FramesMatches(list):
>>> import os
>>> from pprint import pprint
- >>> from moviepy.editor import *
+ >>> from moviepy import *
>>> from moviepy.video.tools.cuts import FramesMatches
>>>
>>> ch_clip = VideoFileClip("media/chaplin.mp4").with_subclip(1, 4)