import os
import tempfile
import requests
from typing import List, Optional, Callable, Dict, Any
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.fx.accel_decel import AccelDecel
from moviepy.video.fx.black_and_white import blackwhite
from moviepy.video.fx.blink import blink
from moviepy.video.fx.crop import crop
from moviepy.video.fx.crossfadein import crossfadein
from moviepy.video.fx.crossfadeout import crossfadeout
from moviepy.video.fx.even_size import even_size
from moviepy.video.fx.fadein import fadein
from moviepy.video.fx.fadeout import fadeout
from moviepy.video.fx.freeze import freeze
from moviepy.video.fx.freeze_region import Freezeregion
from moviepy.video.fx.gamma_correction import gammacorrection
from moviepy.video.fx.headblur import headblur
from moviepy.video.fx.invert_colors import invert_colors
from moviepy.video.fx.loop import loop
from moviepy.video.fx.lum_contrast import lum_contrast
from moviepy.video.fx.make_loopable import makeloopable
from moviepy.video.fx.margin import margin
from moviepy.video.fx.mask_color import mask_color
from moviepy.video.fx.masks_and import masks_and
from moviepy.video.fx.masks_or import masks_or
from moviepy.video.fx.mirrorx import mirrorx
from moviepy.video.fx.mirrory import mirrory
from moviepy.video.fx.multiply_color import multiply_color
from moviepy.video.fx.multiply_speed import multipliespeed
from moviepy.video.fx.painting import painting
from moviepy.video.fx.resize import resize
from moviepy.video.fx.rotate import rotate
from moviepy.video.fx.scroll import scroll
from moviepy.video.fx.slide_in import slidein
from moviepy.video.fx.slide_out import slideout
from moviepy.video.fx.supersample import supersample
from moviepy.video.fx.time_mirror import timemirror
from moviepy.video.fx.time_symmetrize import timesymmetrize
from moviepy.editor import vfx
class VideoProcessingError(Exception):
"""Custom exception for video processing errors."""
pass
class VideoProcessor:
"""
A class to process videos from URLs with various controls and effects.
Attributes:
video_url (str): URL of the video to process.
fps (Optional[int]): Frames per second for the output video.
duration (Optional[float]): Desired duration of the output video in seconds.
max_length_frames (Optional[int]): Maximum number of frames in the output video.
quality (Optional[str]): Quality setting for the output video.
effects (List[str]): List of effects to apply.
"""
# Mapping of effect names to MoviePy effect functions
EFFECT_FUNCTIONS: Dict[str, Callable[..., VideoFileClip]] = {
'AccelDecel': AccelDecel,
'BlackAndWhite': blackwhite,
'Blink': blink,
'Crop': crop,
'CrossFadeIn': crossfadein,
'CrossFadeOut': crossfadeout,
'EvenSize': even_size,
'FadeIn': fadein,
'FadeOut': fadeout,
'Freeze': freeze,
'FreezeRegion': Freezeregion,
'GammaCorrection': gammacorrection,
'HeadBlur': headblur,
'InvertColors': invert_colors,
'Loop': loop,
'LumContrast': lum_contrast,
'MakeLoopable': makeloopable,
'Margin': margin,
'MaskColor': mask_color,
'MasksAnd': masks_and,
'MasksOr': masks_or,
'MirrorX': mirrorx,
'MirrorY': mirrory,
'MultiplyColor': multiply_color,
'MultiplySpeed': multipliespeed,
'Painting': painting,
'Resize': resize,
'Rotate': rotate,
'Scroll': scroll,
'SlideIn': slidein,
'SlideOut': slideout,
'SuperSample': supersample,
'TimeMirror': timemirror,
'TimeSymmetrize': timesymmetrize,
}
def __init__(
self,
video_url: str,
fps: Optional[int] = None,
duration: Optional[float] = None,
max_length_frames: Optional[int] = None,
quality: Optional[str] = None,
effects: Optional[List[str]] = None
) -> None:
"""
Initializes the VideoProcessor with user-defined parameters.
Args:
video_url (str): URL of the video to process.
fps (Optional[int]): Frames per second for the output video.
duration (Optional[float]): Desired duration of the output video in seconds.
max_length_frames (Optional[int]): Maximum number of frames in the output video.
quality (Optional[str]): Quality setting for the output video.
effects (Optional[List[str]]): List of effects to apply.
"""
self.video_url: str = video_url
self.fps: Optional[int] = fps
self.duration: Optional[float] = duration
self.max_length_frames: Optional[int] = max_length_frames
self.quality: Optional[str] = quality
self.effects: List[str] = effects if effects else []
self.temp_video_path: Optional[str] = None
def download_video(self) -> str:
"""
Downloads the video from the provided URL to a temporary file.
Returns:
str: Path to the downloaded temporary video file.
Raises:
VideoProcessingError: If the video cannot be downloaded.
"""
try:
response = requests.get(self.video_url, stream=True, timeout=30)
response.raise_for_status()
except requests.RequestException as e:
raise VideoProcessingError(f"Failed to download video: {e}")
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=self._get_file_extension(), mode='wb') as tmp_file:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
tmp_file.write(chunk)
self.temp_video_path = tmp_file.name
return self.temp_video_path
except Exception as e:
raise VideoProcessingError(f"Error saving video to temporary file: {e}")
def _get_file_extension(self) -> str:
"""
Extracts the file extension from the video URL.
Returns:
str: File extension (e.g., '.mp4').
Raises:
VideoProcessingError: If the file extension cannot be determined.
"""
_, ext = os.path.splitext(self.video_url)
if not ext:
raise VideoProcessingError("Unable to determine the video file extension from the URL.")
return ext
def apply_controls(self, clip: VideoFileClip) -> VideoFileClip:
"""
Applies user-defined controls to the video clip.
Args:
clip (VideoFileClip): The original video clip.
Returns:
VideoFileClip: The processed video clip with controls applied.
"""
if self.fps is not None:
try:
clip = clip.set_fps(self.fps)
except Exception as e:
raise VideoProcessingError(f"Failed to set FPS: {e}")
if self.duration is not None:
try:
clip = clip.subclip(0, min(self.duration, clip.duration))
except Exception as e:
raise VideoProcessingError(f"Failed to set duration: {e}")
if self.max_length_frames is not None:
try:
max_duration = self.max_length_frames / clip.fps
clip = clip.subclip(0, min(max_duration, clip.duration))
except Exception as e:
raise VideoProcessingError(f"Failed to set max length frames: {e}")
if self.quality is not None:
# Quality handling might involve setting bitrate or other codec parameters during write
# This will be handled during video writing
pass # Placeholder for quality-related adjustments
return clip
def apply_effects(self, clip: VideoFileClip) -> VideoFileClip:
"""
Applies the specified MoviePy effects to the video clip.
Args:
clip (VideoFileClip): The video clip to apply effects to.
Returns:
VideoFileClip: The video clip with effects applied.
"""
for effect in self.effects:
effect_func = self.EFFECT_FUNCTIONS.get(effect)
if not effect_func:
raise VideoProcessingError(f"Effect '{effect}' is not supported.")
try:
# For simplicity, effects are applied with default parameters.
# This can be extended to accept parameters for each effect.
clip = effect_func(clip)
except Exception as e:
raise VideoProcessingError(f"Failed to apply effect '{effect}': {e}")
return clip
def process_video(self, output_path: str) -> None:
"""
Downloads, processes, and saves the video to the specified output path.
Args:
output_path (str): Path where the processed video will be saved.
Raises:
VideoProcessingError: If any step in the processing pipeline fails.
"""
try:
temp_path = self.download_video()
with VideoFileClip(temp_path) as clip:
clip = self.apply_controls(clip)
clip = self.apply_effects(clip)
# Define codec and bitrate based on quality
codec = 'libx264' # Default codec
bitrate = '5000k' # Default bitrate
if self.quality:
if self.quality.lower() == 'high':
bitrate = '8000k'
elif self.quality.lower() == 'low':
bitrate = '2500k'
# Extend with more quality settings as needed
clip.write_videofile(
output_path,
codec=codec,
bitrate=bitrate,
fps=self.fps if self.fps else clip.fps,
threads=4,
logger=None # Suppress MoviePy logger or set to 'bar' to show progress
)
except VideoProcessingError:
raise
except Exception as e:
raise VideoProcessingError(f"An unexpected error occurred during video processing: {e}")
finally:
self.cleanup()
def cleanup(self) -> None:
"""
Removes the temporary video file if it exists.
"""
if self.temp_video_path and os.path.exists(self.temp_video_path):
try:
os.remove(self.temp_video_path)
except OSError:
pass # Silently ignore cleanup errors