Skip to content

Instantly share code, notes, and snippets.

@daitomanabe
Last active June 1, 2023 12:17
Show Gist options
  • Save daitomanabe/9aae431db13d5c6f6a9748c4bb73372d to your computer and use it in GitHub Desktop.
Save daitomanabe/9aae431db13d5c6f6a9748c4bb73372d to your computer and use it in GitHub Desktop.
random_clip_extractor
import argparse
import random
from moviepy.video.io.VideoFileClip import VideoFileClip
import os
import concurrent.futures
def write_clip(clip, start_time, end_time, output_file_path):
output_clip = clip.subclip(start_time, end_time)
output_clip.write_videofile(output_file_path, codec='libx264', bitrate='5000k')
print(f'Created: {output_file_path}')
def random_clips(file_path, output_dir, base_filename, num_clips=3, clip_length=1.0):
clip = VideoFileClip(file_path)
duration = clip.duration
os.makedirs(output_dir, exist_ok=True) # Creates the output directory if it doesn't exist
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
for i in range(num_clips):
start_time = random.uniform(0, duration - clip_length) # Random start time
end_time = start_time + clip_length
output_file_name = f'{base_filename}_{str(i).zfill(2)}.mov'
output_file_path = os.path.join(output_dir, output_file_name)
futures.append(executor.submit(write_clip, clip, start_time, end_time, output_file_path))
for future in concurrent.futures.as_completed(futures):
future.result() # just to raise exception if any
def main():
parser = argparse.ArgumentParser(description='Create random clips from a video.')
parser.add_argument('filepath', help='The path to the video file.')
parser.add_argument('output_dir', help='The directory to output the clips to.')
parser.add_argument('base_filename', help='The base name for output files.')
args = parser.parse_args()
random_clips(args.filepath, args.output_dir, args.base_filename)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment