Skip to content

Instantly share code, notes, and snippets.

@JupyterJones
Created August 4, 2023 23:56
Show Gist options
  • Save JupyterJones/7ae1a25124d43d2e77aaff619eb1bfa5 to your computer and use it in GitHub Desktop.
Save JupyterJones/7ae1a25124d43d2e77aaff619eb1bfa5 to your computer and use it in GitHub Desktop.
This script selects 30 random videos from the path entered in this case "~/Desktop/StoryMaker/VIDEOS" and merges a random .5 seconds from each video into one video.
import os
import random
import shutil
import uuid
from moviepy.editor import VideoFileClip, concatenate_videoclips
def get_random_video_clips(dir_path, num_clips=30, clip_duration=1, target_size=(512, 768), default_fps=30):
video_files = []
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.endswith(('.mp4', '.avi', '.mkv')):
video_files.append(os.path.join(root, file))
num_videos = len(video_files)
if num_videos < num_clips:
print(f"Not enough videos ({num_videos}) in the directory.")
return None
random_clips = []
for _ in range(num_clips):
random_video = random.choice(video_files)
try:
video_clip = VideoFileClip(random_video)
duration = video_clip.duration
start_time = random.uniform(0, duration - clip_duration)
end_time = start_time + clip_duration
random_clip = video_clip.subclip(start_time, end_time)
random_clip_resized = random_clip.resize(target_size)
random_clips.append(random_clip_resized)
except Exception as e:
print(f"Error processing {random_video}: {e}")
continue # Continue to the next iteration if there is an error
# Set the default frame rate for all clips
for clip in random_clips:
clip.fps = default_fps
return random_clips
def copy_verified_clips(random_clips, target_folder):
os.makedirs(target_folder, exist_ok=True)
copied_clips = []
for idx, clip in enumerate(random_clips):
unique_filename = str(uuid.uuid4()) + ".mp4"
clip_filename = os.path.join(target_folder, unique_filename)
clip.write_videofile(clip_filename, codec='libx264', fps=30)
copied_clips.append(clip_filename)
return copied_clips
def main():
desktop_path = os.path.expanduser("~/Desktop/StoryMaker/VIDEOS")
random_clips = get_random_video_clips(desktop_path)
if random_clips:
clips_folder = os.path.join(desktop_path, "random_clips")
copied_clips = copy_verified_clips(random_clips, clips_folder)
# Manually review the clips in the 'random_clips' folder, remove unwanted ones if needed
# After verifying the clips, you can use the 'copied_clips' list to create the final video
final_clip = concatenate_videoclips([VideoFileClip(clip) for clip in copied_clips])
final_clip = final_clip.subclip(0, 30) # Limit the final video to 58 seconds
output_path = os.path.join(desktop_path, "random_video_58s.mp4")
final_clip.write_videofile(output_path, codec='libx264', fps=30)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment