Last active
June 1, 2023 12:17
-
-
Save daitomanabe/9aae431db13d5c6f6a9748c4bb73372d to your computer and use it in GitHub Desktop.
random_clip_extractor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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