Video editing with Python
Add tests for HTML tools (#1592)
Álvaro Mondéjar9b09ada04998
diff --git a/moviepy/video/io/html_tools.py b/moviepy/video/io/html_tools.pyindex b496381d..706cc6c7 100644--- a/moviepy/video/io/html_tools.py+++ b/moviepy/video/io/html_tools.py@@ -8,6 +8,7 @@ IPython Notebook.# That is because most browsers use a cache system and they won't# properly refresh the media when the original files are changed.+import inspectimport osfrom base64 import b64encode@@ -17,7 +18,7 @@ from moviepy.video.io.ffmpeg_reader import ffmpeg_parse_infosfrom moviepy.video.VideoClip import ImageClip, VideoClip-try:+try: # pragma: no coverfrom IPython.display import HTMLipython_available = True@@ -28,6 +29,10 @@ try:except ImportError:++ def HTML2(content): # noqa D103+ return content+ipython_available = False@@ -50,21 +55,33 @@ templates = {def html_embed(clip, filetype=None, maxduration=60, rd_kwargs=None, center=True, **html_kwargs):- """Returns HTML5 code embedding the clip+ """Returns HTML5 code embedding the clip.- clip+ Parameters+ ----------++ clip : moviepy.Clip.ClipEither a file name, or a clip to preview.Either an image, a sound or a video. Clips will actually bewritten to a file and embedded as if a filename was provided.-- filetype+ filetype : str, optionalOne of 'video','image','audio'. If None is given, it is determinedbased on the extension of ``filename``, but this can bug.- rd_kwargs- Keyword arguments for the rendering, like ``{'fps':15, 'bitrate':'50k'}``+ maxduration : float, optional+ An error will be raised if the clip's duration is more than the indicated+ value (in seconds), to avoid spoiling the browser's cache and the RAM.++ rd_kwargs : dict, optional+ Keyword arguments for the rendering, like ``dict(fps=15, bitrate="50k")``.+ Allow you to give some options to the render process. You can, for+ example, disable the logger bar passing ``dict(logger=None)``.+ center : bool, optional+ If true (default), the content will be wrapped in a+ ``<div align=middle>`` HTML container, so the content will be displayed+ at the center.html_kwargsAllow you to give some options, like ``width=260``, ``autoplay=True``,@@ -72,9 +89,19 @@ def html_embed(Examples--------- TODO Create example based on ipython_display examples++ >>> from moviepy.editor import *+ >>> # later ...+ >>> html_embed(clip, width=360)+ >>> html_embed(clip.audio)++ >>> clip.write_gif("test.gif")+ >>> html_embed('test.gif')++ >>> clip.save_frame("first_frame.jpeg")+ >>> html_embed("first_frame.jpeg")"""- if rd_kwargs is None:+ if rd_kwargs is None: # pragma: no coverrd_kwargs = {}if "Clip" in str(clip.__class__):@@ -82,7 +109,10 @@ def html_embed(if isinstance(clip, ImageClip):filename = TEMP_PREFIX + ".png"kwargs = {"filename": filename, "with_mask": True}- kwargs.update(rd_kwargs)+ argnames = inspect.getfullargspec(clip.save_frame).args+ kwargs.update(+ {key: value for key, value in rd_kwargs.items() if key in argnames}+ )clip.save_frame(**kwargs)elif isinstance(clip, VideoClip):filename = TEMP_PREFIX + ".mp4"@@ -174,33 +204,45 @@ def ipython_display():"""Displays clip content in an IPython Notebook.- clip- Either the name of a file, or a clip to preview. The clip will- actually be written to a file and embedded as if a filename was- provided.+ Remarks: If your browser doesn't support HTML5, this should warn you.+ If nothing is displayed, maybe your file or filename is wrong.+ Important: The media will be physically embedded in the notebook.- filetype:- One of 'video','image','audio'. If None is given, it is determined- based on the extension of ``filename``, but this can bug.+ Parameters+ ----------++ clip : moviepy.Clip.Clip+ Either the name of a file, or a clip to preview. The clip will actually+ be written to a file and embedded as if a filename was provided.- maxduration+ filetype : str, optional+ One of ``"video"``, ``"image"`` or ``"audio"``. If None is given, it is+ determined based on the extension of ``filename``, but this can bug.++ maxduration : float, optionalAn error will be raised if the clip's duration is more than the indicated- value (in seconds), to avoid spoiling the browser's cache and the RAM.+ value (in seconds), to avoid spoiling the browser's cache and the RAM.- t+ t : float, optionalIf not None, only the frame at time t will be displayed in the notebook,- instead of a video of the clip+ instead of a video of the clip.- fps+ fps : int, optionalEnables to specify an fps, as required for clips whose fps is unknown.- kwargs- Allow you to give some options, like width=260, etc. When editing- looping gifs, a good choice is loop=1, autoplay=1.+ rd_kwargs : dict, optional+ Keyword arguments for the rendering, like ``dict(fps=15, bitrate="50k")``.+ Allow you to give some options to the render process. You can, for+ example, disable the logger bar passing ``dict(logger=None)``.- Remarks: If your browser doesn't support HTML5, this should warn you.- If nothing is displayed, maybe your file or filename is wrong.- Important: The media will be physically embedded in the notebook.+ center : bool, optional+ If true (default), the content will be wrapped in a+ ``<div align=middle>`` HTML container, so the content will be displayed+ at the center.++ kwargs+ Allow you to give some options, like ``width=260``, etc. When editing+ looping gifs, a good choice is ``loop=1, autoplay=1``.Examples--------diff --git a/tests/test_videotools.py b/tests/test_videotools.pyindex 2b583dfc..d223fdf0 100644--- a/tests/test_videotools.py+++ b/tests/test_videotools.py@@ -1,10 +1,13 @@"""Video file clip tests meant to be run with pytest."""+import importlibimport mathimport os+import sysimport pytest+from moviepy.audio.AudioClip import AudioClipfrom moviepy.video.compositing.concatenate import concatenate_videoclipsfrom moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.tools.credits import CreditsClip@@ -14,9 +17,18 @@ from moviepy.video.tools.cuts import (detect_scenes,find_video_period,)-from moviepy.video.VideoClip import BitmapClip, ColorClip+from moviepy.video.VideoClip import BitmapClip, ColorClip, ImageClip, VideoClip-from tests.test_helper import FONT, TMP_DIR+from tests.test_helper import FONT, TMP_DIR, get_stereo_wave+++try:+ importlib.import_module("ipython.display")+except ImportError:+ ipython_available = False+else:+ ipython_available = True+ del sys.modules["ipython.display"]def test_credits():@@ -216,5 +228,215 @@ def test_FramesMatches_save_load():assert frames_match == input_matching_frames[i]+ ("clip", "filetype", "fps", "maxduration", "t", "expected_error"),+ (+ pytest.param(+ AudioClip(get_stereo_wave(), duration=0.2, fps=44100),+ None,+ None,+ None,+ None,+ None,+ id="AudioClip",+ ),+ pytest.param(+ VideoFileClip("media/bitmap.mp4"),+ None,+ None,+ None,+ None,+ None,+ id="VideoFileClip",+ ),+ pytest.param(+ BitmapClip([["RR", "RR"], ["GG", "GG"]], duration=0.25),+ None,+ 4,+ None,+ None,+ None,+ id="BitmapClip",+ ),+ pytest.param(+ ImageClip("media/python_logo.png"),+ None,+ None,+ None,+ None,+ None,+ id="ImageClip(.png)",+ ),+ pytest.param(+ ImageClip("media/pigs_in_a_polka.gif"),+ None,+ None,+ None,+ None,+ None,+ id="ImageClip(.gif)",+ ),+ pytest.param(+ os.path.join("media", "pigs_in_a_polka.gif"),+ None,+ None,+ None,+ None,+ None,+ id="filename(.gif)",+ ),+ pytest.param(+ os.path.join("media", "vacation_2017.jpg"),+ None,+ None,+ None,+ None,+ None,+ id="filename(.jpg)",+ ),+ pytest.param(+ os.path.join(TMP_DIR, "moviepy_ipython_display.foo"),+ None, # unknown filetype+ None,+ None,+ None,+ (ValueError, "No file type is known for the provided file."),+ id="filename(.foo)",+ ),+ pytest.param(+ os.path.join(TMP_DIR, "moviepy_ipython_display.foo"),+ "video", # unsupported filetype for '.foo' extension+ None,+ None,+ None,+ (+ ValueError,+ "This video extension cannot be displayed in the IPython Notebook.",+ ),+ id="filename(.foo)[filetype=video]",+ ),+ pytest.param(+ VideoFileClip("media/bitmap.mp4"),+ "video",+ None,+ 0,+ None,+ (+ ValueError,+ "You can increase 'maxduration', by passing 'maxduration'",+ ),+ id="VideoFileClip(.mp4)[filetype=video, maxduration > clip.duration]",+ ),+ pytest.param(+ type("FakeClip", (), {})(),+ None,+ None,+ None,+ None,+ (ValueError, "Unknown class for the clip. Cannot embed and preview"),+ id="FakeClip",+ ),+ pytest.param(+ VideoFileClip("media/chaplin.mp4").subclip(0, 1),+ None,+ None,+ None,+ 0.5,+ None,+ id="VideoFileClip(.mp4)[filetype=video, t=0.5]",+ ),+ pytest.param(+ ImageClip("media/pigs_in_a_polka.gif"),+ None,+ None,+ None,+ 0.2,+ None,+ id="ImageClip(.gif)[t=0.2]",+ ),+ ),+)+def test_ipython_display(+ clip, filetype, fps, maxduration, t, expected_error, monkeypatch+):+ # patch module to use it without ipython installed+ video_io_html_tools_module = importlib.import_module("moviepy.video.io.html_tools")+ monkeypatch.setattr(video_io_html_tools_module, "ipython_available", True)++ # build `ipython_display` kwargs+ kwargs = {}+ if fps is not None:+ kwargs["fps"] = fps+ if maxduration is not None:+ kwargs["maxduration"] = maxduration+ if t is not None:+ kwargs["t"] = t++ if expected_error is None:+ html_content = video_io_html_tools_module.ipython_display(+ clip,+ rd_kwargs=dict(logger=None),+ filetype=filetype,+ **kwargs,+ )+ else:+ with pytest.raises(expected_error[0]) as exc:+ video_io_html_tools_module.ipython_display(+ clip,+ rd_kwargs=None if not kwargs else dict(logger=None),+ filetype=filetype,+ **kwargs,+ )+ assert expected_error[1] in str(exc.value)+ return++ # assert built content according to each file type+ HTML5_support_message = (+ "Sorry, seems like your browser doesn't support HTML5 audio/video"+ )++ def image_contents():+ return ("<div align=middle><img src=", "></div>")++ if isinstance(clip, AudioClip):+ content_start = "<div align=middle><audio controls><source src="+ content_end = f">{HTML5_support_message}</audio></div>"+ elif isinstance(clip, ImageClip) or t is not None: # t -> ImageClip+ content_start, content_end = image_contents()+ elif isinstance(clip, VideoClip):+ content_start = "<div align=middle><video src="+ content_end = f" controls>{HTML5_support_message}</video></div>"+ else:+ ext = os.path.splitext(clip)[1]+ if ext in [".jpg", ".gif"]:+ content_start, content_end = image_contents()+ else:+ raise NotImplementedError(+ f"'test_ipython_display' must handle '{ext}' extension types!"+ )++ assert html_content.startswith(content_start)+ assert html_content.endswith(content_end)++ # clean `ipython` and `moviepy.video.io.html_tools` module from cache+ del sys.modules["moviepy.video.io.html_tools"]+ if "ipython" in sys.modules:+ del sys.modules["ipython"]+++ ipython_available,+ reason="ipython must not be installed in order to run this test",+)+def test_ipython_display_not_available():+ video_io_html_tools_module = importlib.import_module("moviepy.video.io.html_tools")++ with pytest.raises(ImportError) as exc:+ video_io_html_tools_module.ipython_display("foo")+ assert str(exc.value) == "Only works inside an IPython Notebook"++ del sys.modules["moviepy.video.io.html_tools"]++if __name__ == "__main__":- test_credits()+ pytest.main()