import yaml import pytube import tempfile import imageio from pathlib import Path from functools import lru_cache import moviepy.editor as mpy FILE = 'data/input/samples/exercises.yaml' @lru_cache(5) def get_video(url): output_dir = tempfile.mktemp() video = pytube.YouTube(url) video.streams.filter(res="360p").first().download(filename=output_dir) return output_dir def create_gif_from_video_and_timestamps(video_path, start, end): video = mpy.VideoFileClip(video_path) clip: mpy.VideoFileClip = video.subclip(start, end) output_dir = tempfile.mktemp() + '.mp4' clip.set_fps(2) clip.without_audio().write_videofile(output_dir) return output_dir if __name__ == '__main__': file = open(FILE) exercises = yaml.safe_load(file) for ex in exercises['exercises']: name = ex['name'] video_url = ex['video'] start = ex['start'] end = ex['end'] video_path = get_video(video_url) gif = create_gif_from_video_and_timestamps(video_path, start, end) ex['gif_path'] = gif print(gif)