Skip to content

Instantly share code, notes, and snippets.

@saalaus
Created February 28, 2024 18:13
Show Gist options
  • Save saalaus/7ea6a4923078f495945655b5aa3ee1a7 to your computer and use it in GitHub Desktop.
Save saalaus/7ea6a4923078f495945655b5aa3ee1a7 to your computer and use it in GitHub Desktop.
Make video preview
# Creates previews for videos - random short snippets of 2 seconds each
# pip install moviepy==1.0.3
# use python video.py <input_video_path> <output_video_name> <duration_in_seconds>
from moviepy.video.compositing.concatenate import concatenate_videoclips
from moviepy.editor import VideoFileClip
import sys
import random
import argparse
def create_preview(input_video: str, output_video: str, duration: float) -> None:
"""
Create a preview video from the input video with the specified duration and save it to the output video file.
Args:
input_video (str): The path to the input video file.
output_video (str): The path to save the output preview video file.
duration (float): The duration of the preview video in seconds.
"""
video = VideoFileClip(input_video)
total_duration = video.duration
clips = []
current_duration = 0
while current_duration < duration:
start_time = random.uniform(0, total_duration - 2)
clip = video.subclip(start_time, start_time + 2)
if current_duration + clip.duration > duration:
clip = clip.subclip(0, duration - current_duration)
clips.append((start_time, clip))
current_duration += clip.duration
clips.sort(key=lambda clip: clip[0])
clips = [clip[1] for clip in clips]
preview = concatenate_videoclips(clips)
preview.write_videofile(output_video)
def parse_args(args: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog="preview", description="Makes short preview from video"
)
parser.add_argument("input_video_path", type=str)
parser.add_argument("output_video_name", type=str, nargs="?")
parser.add_argument("duration", type=float, nargs="?", default=20.0)
return parser.parse_args(args)
def main():
args = parse_args(sys.argv[1:])
if not args.output_video_name:
output_name = args.input_video_path.rsplit(".", 1)[0]
args.output_video_name = f"{output_name}_preview.mp4"
create_preview(args.input_video_path, args.output_video_name, args.duration)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment