from pytube import Playlist import ffmpeg import os def make_alpha_numeric(string: str) -> str: return "".join(char for char in string if char.isalnum()) class YouLoadPlayList: """A class for download and handling youtube playlists""" DOWNLOAD_TYPES = ["default", "highest", "lowest", "mp3", "720p", "480p", "360p", "240p", "144p"] DEFAULT_DOWNLOAD_TYPE = "default" def __init__(self, link: str): self.yt_playlist = Playlist(link) self.video_count = len(self.yt_playlist.videos) self.folder_name = make_alpha_numeric(self.yt_playlist.title) self.download_type = self.DEFAULT_DOWNLOAD_TYPE def generate_video_info(self, video_num: int) -> str: """Returns information on video in playlist at 'video_num'""" video = self.yt_playlist.videos[video_num] video_size = video.streams.get_highest_resolution().filesize // 1048576 return f"Title: {video.title}, Size: {video_size} MB" def set_download_directory(self, directory: str) -> None: """Sets where the playlist folder will be downloaded""" self.folder_name = os.path.join(directory, make_alpha_numeric(self.yt_playlist.title)) def prepare_for_download(self) -> None: """Gets the playlist ready for download. Creates the output folder and that stuff.""" os.mkdir(self.folder_name) def download_video(self, video_num: int, use_prefix: bool) -> str: """Download video at 'video_num'""" video = self.yt_playlist.videos[video_num] # Create prefix. filename_prefix = "" if use_prefix: filename_prefix = str(video_num + 1) + " " # Download this fucker. if self.download_type == "default": # video.streams.first().download(output_path=self.folder_name, filename_prefix=filename_prefix) elif self.download_type == "highest": video.streams.get_highest_resolution().download(output_path=self.folder_name, filename_prefix=filename_prefix) elif self.download_type == "lowest": video.streams.get_lowest_resolution().download(output_path=self.folder_name, filename_prefix=filename_prefix) elif self.download_type == "mp3": file_path = video.streams.first().download(output_path=self.folder_name, filename_prefix=filename_prefix) # To mp3. file_path_mp3 = file_path[:-4] + ".mp3" ffmpeg.input(file_path).output(file_path_mp3).run() # Remove mp4 file. os.remove(file_path) else: video.streams.get_by_resolution(self.download_type).download(output_path=self.folder_name, filename_prefix=filename_prefix) return f"Title: {video.title}"