示例#1
0
def playlist_download():
    res_setting = 0
    res_flag = 1
    dumbpeople = ["Quit playin around\n", "I aint got all day\n"]
    print("\nPaste playlist URL:")
    URL = input()
    print("Please wait...\n")
    try:
        playlist = Playlist(URL)
    except:
        exceptions.check1(URL, True)
    URL_list = playlist.video_urls
    while (res_flag == 1):
        print("Which resolution setting would you prefer?:")
        print("1.Download in highest available resolution")
        print("2.Download in lowest available resolution")
        res_setting = int(input())
        if (res_setting != 1 and res_setting != 2):
            print(dumbpeople[random.choice([0, 1])])
        else:
            if (res_setting == 1):
                title = playlist.title() + "[High res]"
            else:
                title = playlist.title() + "[Low res]"
            res_flag = 0
    path1, title = path.mkdirectory(title, True)
    for video in URL_list:
        mainscript.single_download(True, video, path1, res_setting)
    print("Finished")
示例#2
0
def main():
    """Command line application to download youtube videos."""
    # noinspection PyTypeChecker
    parser = argparse.ArgumentParser(description=main.__doc__)
    args = _parse_args(parser)
    if args.verbosity:
        log_level = min(args.verbosity, 4) * 10
        setup_logger(logging.FATAL - log_level)

    if not args.url or "youtu" not in args.url:
        parser.print_help()
        sys.exit(1)

    if "/playlist" in args.url:
        print("Loading playlist...")
        playlist = Playlist(args.url)
        if not args.target:
            args.target = safe_filename(playlist.title())
        for youtube_video in playlist.videos:
            try:
                _perform_args_on_youtube(youtube_video, args)
            except PytubeError as e:
                print(f"There was an error with video: {youtube_video}")
                print(e)
    else:
        print("Loading video...")
        youtube = YouTube(args.url)
        _perform_args_on_youtube(youtube, args)
示例#3
0
def test_title(request_get):
    request_get.return_value = ("<title>(149) Python Tutorial for Beginners "
                                "(For Absolute Beginners) - YouTube</title>")
    url = "https://www.fakeurl.com/playlist?list=PLsyeobzWxl7poL9JTVyndKe62ieoN"
    pl = Playlist(url)
    pl_title = pl.title()
    assert pl_title == "(149) Python Tutorial for Beginners (For Absolute Beginners)"
 def download(self, playlist_url: str, start: int = 0, limit: int = 5, folder: Optional[str] = None) -> None:
     # invoke youtube and donwload up to limit
     # https://github.com/nficano/pytube docs and examples
     # based on this!
     
     playlist = Playlist(playlist_url)
     
     i = 0
     print(dir(playlist))
     print(playlist.title())
     print(playlist.video_urls)
     for video in playlist:
         print(i, start, start + limit)
         if i < start:
             i += 1
             continue
         if i >= start + limit:
             break
         # TODO parallel?
         print('downloading video: ', video)
         yt = YouTube(video)
         # print(type(yt.streams))
         stream = yt.streams.get_highest_resolution()
         stream.download(output_path=folder)
         yt.register_on_progress_callback(lambda *args: self.on_progress(*args))
         print('  completed ', yt.title)
         self.videos.append(Video(yt.title, stream.get_file_path(), stream))
         i += 1
示例#5
0
def enter():
    if (videotype.get() == 1):
        yt1 = YouTube(urlInput.get())
        urlInput_label = tk.Label(frame,
                                  text=yt1.title,
                                  bg="#041824",
                                  fg="#ffffff",
                                  font=("Courier", 10),
                                  wraplength=400)
        urlInput_label.place(y=240, relwidth=1, relheight=0.2)
        urlInput_label = tk.Label(frame,
                                  text=yt1.length + " seconds long",
                                  bg="#041824",
                                  fg="#ffffff",
                                  font=("Courier", 10),
                                  wraplength=400)
        urlInput_label.place(y=330, relwidth=1, relheight=0.05)

    elif (videotype.get() == 2):
        pl = Playlist(urlInput.get())
        pl.populate_video_urls()
        urlInput_label = tk.Label(frame,
                                  text='Playlist Name: ' + pl.title() + '\n' +
                                  'Number of videos in playlist: ' +
                                  str(len(pl.video_urls)),
                                  bg="#041824",
                                  fg="#ffffff",
                                  font=("Courier", 10),
                                  wraplength=400)
        urlInput_label.place(y=260, relwidth=1, relheight=0.2)
def download_playlist(url, dest='bucket/', skip=0):
    filenames = get_filenames(path=dest)
    print('Total {} files in {}.'.format(len(filenames), dest))
    print()

    pl = Playlist(url)
    print('Playlist name: {}'.format(pl.title()))
    print()

    yts = []
    vid_names = []
    t0 = time.time()
    for idx, yt in enumerate(pl.videos):
        if idx < skip:
            continue
        yts.append(yt)
        vid_name = yt.title
        vid_names.append(vid_name)
        print('{}. {}'.format(idx + 1, vid_name))

        if vid_name in filenames:
            print('Already in {}.'.format(dest))
        else:
            download_video(yt=yt)
        t1 = time.time()
        print("  Time elapsed: {:0.5f}s".format(t1 - t0))
        print()

        t0 = t1
示例#7
0
 def loadStreams(self, url):
     try:
         if url.__contains__('playlist?list'):
             playlist = Playlist(url)
             print("Progress Status: " + playlist.title())
             for video_url in playlist.video_urls:
                 yt = YouTube(video_url)
                 self.videos[yt.video_id] = yt
                 print("Loaded " + yt.title)
         else:
             yt = YouTube(url)
             self.videos[yt.video_id] = yt
             print("Progress Status: " + yt.title)
             print("Loaded: " + yt.title)
     except:
         print("Url doesn't have any video.")
         return False
     print("All Videos are loaded.\n")
     print("Select videos to download.\n\n")
     for videoID, yt in self.videos.items():
         print("\t" + yt.title)
         for stream in yt.streams:
             print(f'ITag: {stream.itag}\n')
             print(f'Res: {stream.resolution}, FPS: {stream.fps}')
             print(f'Video Codec: {stream.video_codec}')
             print(f'Audio Codec: {stream.audio_codec}, ABR: {stream.abr}')
             print(
                 f'File Type: {stream.mime_type.split("/")[1]}, Size: {stream.filesize // 1024} KB\n'
             )
         self.downloadItems[videoID] = input(
             "Enter the ITags of video streams, you wan to download:"
         ).replace(' ', '').split(',')
     return True
def main():
    # check is user is conncted to internet
    if not connect():
        print('No Internet Connection!\nExiting....')
        exit() #exit if not
    else:
        while True:
        	# url='https://www.youtube.com/watch?v=Edpy1szoG80&list=PL153hDY-y1E00uQtCVCVC8xJ25TYX8yPU'
        	url=input('Enter the Playlist link to Download: ')
        	if urlChecker(url):
        		break
        	else:print('Invalid Url!')
        while True:
            temp=pathExistsElseCreate(input('\nEnter Destination Path("." for this dir):'))
            if temp is not None:
                SAVE_PATH=temp
                break
            else:print('Invalid Path!')

        
        print("\nGetting Details of Playlist")
        pl = Playlist(url)
        os.system('cls')
        print("\nDetails for Playlist","\n")
        print("Title:   ",pl.title()) #may not work for some playlist
        print("\nDownloading...")
        pl.download_all(SAVE_PATH)
        print("\nDownload completed!!")
	def getPlaylistObjectForPlaylistUrl(self, playlistUrl):
		"""
		Returns the pytube.Playlist object corresponding to the passed playlistObject the
		playlistObject title and None if no problem happened.
		
		:param playlistUrl:
		:return: playlistObject - Playlist object
				 playlistTitle
				 accessError in case of problem, None otherwise
		"""
		playlistObject = None
		playlistTitle = None
		accessError = None
		
		try:
			playlistObject = Playlist(playlistUrl)
			playlistObject._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
			playlistTitle = playlistObject.title()
		except http.client.InvalidURL as e:
			accessError = AccessError(AccessError.ERROR_TYPE_PLAYLIST_URL_INVALID, str(e))
		except AttributeError as e:
			accessError = AccessError(AccessError.ERROR_TYPE_PLAYLIST_URL_INVALID, str(e))
		except URLError:
			accessError = AccessError(AccessError.ERROR_TYPE_NO_INTERNET, 'No internet access. Fix the problem and retry !')

		if accessError is None and (playlistTitle is None or 'Oops' in playlistTitle):
			accessError = AccessError(AccessError.ERROR_TYPE_NOT_PLAYLIST_URL, playlistUrl)

		return playlistObject, playlistTitle, accessError
示例#10
0
def test_title(request_get):
    request_get.return_value = ("<title>(149) Python Tutorial for Beginners "
                                "(For Absolute Beginners) - YouTube</title>")
    url = "https://www.fakeurl.com/playlist?list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n"
    pl = Playlist(url)
    pl_title = pl.title()
    assert pl_title == "(149) Python Tutorial for Beginners (For Absolute Beginners)"
示例#11
0
    def download_playlist(self, playlist_url=None):
        """Downloads all songs from a playlist"""
        pl = Playlist(playlist_url)

        self.videos_dir += "/"+pl.title()

        # set values for progress bar
        self.progress["value"] = 0
        self.max_songs = len(pl)
        self.progress["maximum"] = len(pl)

        # print(f'[+]Saving playlist at: {self.videos_dir}')
        # print(f'[+]Downloading playlist, total: {len(pl)} songs')

        self.text.insert(
            tk.INSERT, f'[+]Saving playlist at: {self.videos_dir}\n')
        self.text.insert(
            tk.INSERT, f'[+]Downloading playlist;"{pl.title()}" , total: {len(pl)} songs\n')

        with concurrent.futures.ThreadPoolExecutor() as executor:
            executor.map(self.download_song, pl, chunksize=5)

        # print('[+]Download completed!')
        self.text.insert(tk.INSERT, '[+]Download completed!\n')

        tk.messagebox.showinfo("YTDownloader", "Download completed!")
示例#12
0
def processURL(target, audioOnly):
    if 'playlist?' in target:
        playlist = Playlist(target)
        playlistName = sanitize(playlist.title())
        print(f'Playlist: {playlistName}')
        if not os.path.isdir(playlistName):
            os.mkdir(playlistName)
            print(f'Created folder for playlist: {playlistName}')
        playlist_length = len(playlist.video_urls)
        print("Videos in playlist:", playlist_length)
        count = 0
        failure_count = 0
        while True:
            try:
                if count in range(playlist_length):
                    videoURL = playlist.video_urls[count]
                    result = dlVideo(videoURL, audioOnly, playlistName)
                    print(
                        f'Successfully downloaded {result}, {make_ordinal(count+1)} video from {playlistName}'
                    )
                    count += 1
                else:
                    break
            except:
                try:
                    print(
                        f'Failed to download {make_ordinal(count+1)} video from {playlistName}, retrying...'
                    )
                    result = dlVideo(videoURL, audioOnly, playlistName)
                    print(
                        f'Successfully downloaded {result}, {make_ordinal(count+1)} video from {playlistName}'
                    )
                    count += 1
                except:
                    print(
                        f'Failed to download {make_ordinal(count+1)} video from {playlistName}'
                    )
                    count += 1
                    failure_count += 1
                    pass
        print("Successful:", count - failure_count)
        print("Failed:", failure_count)
    else:
        try:
            result = dlVideo(target, audioOnly)
            print(f'Successfully downloaded {result}')
        except:
            try:
                print(f'Failed to download video\nretrying...')
                result = dlVideo(target, audioOnly)
                print(f'Successfully downloaded {result}')
                count += 1
            except:
                print(f'Failed to download video')
                count += 1
                failure_count += 1
                pass
def get_videos_from_playlist(url):
    videos = list()
    playlist = Playlist(url)
    title = playlist.title()
    for video in playlist:
        # video.streams.get_highest_resolution().download()
        videos.append(f"{video}")

    return videos, title
 def loadStreams(self):
     url = self.window.urlLE.text()
     try:
         if url.__contains__('playlist?list'):
             playlist = Playlist(url)
             self.signalStatus.emit("Progress Status: " + playlist.title())
             index, total = 0, len(playlist.video_urls) * 2
             for video_url in playlist.video_urls:
                 yt = YouTube(video_url)
                 self.videos[yt.video_id] = yt
                 self.signalMessage.emit("Loaded " + yt.title)
                 self.signalProgress.emit(int((index + 1) / total * 100))
                 index += 1
         else:
             yt = YouTube(url)
             self.videos[yt.video_id] = yt
             self.signalStatus.emit("Progress Status: " + yt.title)
             self.signalMessage.emit("Loaded: " + yt.title)
     except:
         self.signalError.emit("Url doesn't have any video.")
         return None
     self.signalProgress.emit(50)
     for videoID, yt in self.videos.items():
         streamHead = StreamTreeItem([yt.title],
                                     videoID,
                                     parent=self.window.streamsTW)
         audioHead = StreamTreeItem(['Audio Only'], videoID)
         index, total = 0, len(list(self.videos.keys())) * len(yt.streams)
         for stream in yt.streams:
             if stream.video_codec is None:
                 title = [
                     f'Codec: {stream.audio_codec}, '
                     f'ABR: {stream.abr}, '
                     f'File Type: {stream.mime_type.split("/")[1]}, '
                     f'Size: {stream.filesize // 1024} KB'
                 ]
                 audioHead.addChild(
                     StreamTreeItem(title, videoID, stream.itag))
             else:
                 title = [
                     f'Res: {stream.resolution}, FPS: {stream.fps}, '
                     f' Video Codec: {stream.video_codec}, Audio Codec: {stream.audio_codec}, '
                     f'File Type: {stream.mime_type.split("/")[1]}, '
                     f'Size: {stream.filesize // 1024} KB'
                 ]
                 streamHead.addChild(
                     StreamTreeItem(title, videoID, stream.itag))
             index += 1
             self.signalProgress.emit(int(50 + index / total * 100))
         streamHead.addChild(audioHead)
     self.signalProgress.emit(100)
     self.signalWorkDone.emit(True)
def download_youtube_playlist(link, folder=None):
	p = Playlist(link)
	title = p.title()
	if folder:
		folder = os.path.join(folder, title)
	else:
		folder = title
	print(f"Folder to the playlist - {link}: {folder}")
	try:
		os.makedirs(folder)
	except:
		pass
	p.download_all(download_path=folder)
class Series_vid_download:
    def __init__(self,
                 baseurl,
                 downloadfolder="Downloads",
                 on_progress_callback=None,
                 on_complete_callback=None,
                 isaudio=False):
        self.baseurl = baseurl
        self.playlist = Playlist(self.baseurl,
                                 on_progress_callback=on_progress_callback,
                                 on_complete_callback=on_complete_callback,
                                 isaudio=isaudio)
        if self.playlist.title():
            self.title = format_filename(self.playlist.title())
        else:
            self.title = format_filename(self.baseurl)
        self.downloadfolder = downloadfolder

    def download(self):
        folder = os.path.join(self.downloadfolder, self.title)
        if not os.path.exists(folder):
            os.mkdir(folder)

        self.playlist.download_all(folder)
示例#17
0
def from_playlist_url(url):
    pli = Playlist(url)
    pli.parse_links()
    pli.populate_video_urls()

    output = dict()
    output['type'] = 'playlist'
    output['title'] = pli.title()
    url = pli.construct_playlist_url()
    output['url'] = url
    output['playlist_id'] = _get_playlist_id(url)
    video_urls = pli.parse_links()
    output['video_urls'] = video_urls
    output['video_ids'] = [v.split('=')[1] for v in video_urls]
    return output
示例#18
0
def playlist_processor():
    #
    # Get each video from a playlist and process the video
    #
    try:
        playlist = Playlist(cfg.link)
        playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
        video_index = 0
        for video_url in playlist:
            print(f"\nProcessing video {video_index+1} of {len(playlist)}:")
            video_processor(video_url, video_index)
            video_index += 1
        return playlist.title()
    except Exception as e:
        print("ERROR SETTING UP PLAYLIST")
        print(e)
        print("CHECK THE PLAYLIST URL AND TRY AGAIN...")
示例#19
0
def playlist(self, url, path, res):
    count = 1
    error = 1
    playlist = Playlist(url)
    for video_url in playlist.video_urls:
        while (True):
            try:
                ytd = YouTube(video_url)
                stream = ytd.streams.filter(progressive=True)
                file = stream.get_by_resolution(res)
                file.download(path + '\\' + playlist.title())
                self.label3.setText(str(count) + "File downloaded")
                count += 1
                break
            except:
                self.label3.setText(str(error) + "File Not downloaded")
                error += 1
                break
    def download(self):
        print(self.get_quality())
        playlist_url = self.link.text
        if playlist_url:
            pl = Playlist(playlist_url)
            folder_name = self.safe_filename(pl.title())
            video_list = pl.parse_links()
            self.playlistLen = len(video_list)
            self.folder_path = 'D:/download/' + folder_name

            self.create_new_folder(self.folder_path)
            counter = 1
            for x in video_list:
                self.total_size = 1
                try:
                    yt = YouTube("https://www.youtube.com/" + x)
                    y_title = self.safe_filename(yt.title)
                    yt.register_on_progress_callback(self.show_progress_bar)
                    video_name = self.get_cnt(counter) + y_title
                    video_path = video_name+"_v"
                    audio_path = video_name+"_a"
                    yt.streams.filter(adaptive=True, only_audio=True).first().download(self.folder_path, filename=audio_path)
                    yt.streams.filter(adaptive=True).first().download(self.folder_path, filename=video_path)
                    sss = [stream.subtype for stream in yt.streams.filter(adaptive=True).all()]
                    file_extension_video = sss[0]
                    sss = [stream.subtype for stream in yt.streams.filter(adaptive=True, only_audio=True).all()]
                    file_extension_audio = sss[0]
                    MergeVA.merge_va(isinstance, f"{self.folder_path}/{video_path}.{file_extension_video}",
                                     f"{self.folder_path}/{audio_path}.{file_extension_audio}",
                                     f"{self.folder_path}/{video_name}.mkv")
                    os.remove(f"{self.folder_path}/{video_path}.{file_extension_video}")
                    os.remove(f"{self.folder_path}/{audio_path}.{file_extension_audio}")
                    caption = yt.captions.get_by_language_code('en')
                    if caption:
                        my_file = open(self.folder_path + '/' + self.get_cnt(counter) + y_title + ".srt", "w+", encoding='UTF8')
                        my_file.writelines(caption.generate_srt_captions())
                        my_file.close()
                    else:
                        print("No Sub Found")
                except Exception as e:
                    print("Can't Download: " + str(e))

                counter += 1
示例#21
0
 def playlist(self,url,path,res,info):
     count = 1
     error = 1
     try:
         playlist = Playlist(url)
         for video_url in playlist.video_urls:
             while(True):
                 try:
                     ytd = YouTube(video_url)
                     stream = ytd.streams.filter(progressive=True)
                     file = stream.get_by_resolution(res)
                     file.download(path + '\\' + playlist.title())
                     info.text = str(count) + "File Downloaded"
                     count+=1
                     break
                 except:
                     info.text = str(error) + "File Not Downloaded"
                     error+=1
                     break
     except:
         info.text = "File Not Downloaded"
示例#22
0
 def run(self):
     show_info('Download', 'Your download is in progress')
     global file_size
     if file_path.get():
         folder_path = file_path.get()
     else:
         entry2.delete(0, END)
         entry2.insert(0, DEFAULT_PATH)
         folder_path = DEFAULT_PATH
         show_warning(
             'Destination Path',
             'No destination folder specified! Using default Downloads folder...'
         )
     if download_type.get() == 1:
         try:
             video = YouTube(yt_link.get(),
                             on_progress_callback=progress_check,
                             on_complete_callback=entry_reset)
             video_stream = video.streams.first()
             file_size = video_stream.filesize
             video_stream.download(folder_path)
         except:
             show_error('Error',
                        "I ran into some issues! Let's try that again...")
     elif download_type.get() == 2:
         try:
             my_playlist = Playlist(yt_link.get())
             playlist_name = my_playlist.title()
             new_folder_path = make_folder(folder_path, playlist_name)
             for video in my_playlist.videos:
                 try:
                     video.register_on_progress_callback(progress_check)
                     video_stream = video.streams.first()
                     file_size = video_stream.filesize
                     video_stream.download(new_folder_path)
                 except VideoUnavailable:
                     continue
             entry_reset(stream=None, file_handle=None)
         except Exception as e:
             show_error('Error', f"{e}")
示例#23
0
def download_playlist():
    youtube_playlist = input("Enter Youtube Playlist URL : ")
    pl = Playlist(youtube_playlist)
    pl.populate_video_urls()
    print('Title of the playlist: %s' % pl.title())
    print('Number of videos in playlist: %s' % len(pl.video_urls))
    pl_video_list = pl.video_urls
    print("Downloading Playlist Videos \n")

    # printing the list using loop
    for x in range(len(pl_video_list)):
        print(str(x) + " >> " + pl_video_list[x])
        individual_video_stream = YouTube(
            pl_video_list[x]).streams.filter(mime_type="video/mp4").first()
        individual_video_stream.download(download_destination,
                                         "PhysicsSession" + str(x),
                                         "unAcademy-ClassXI-JEE")

    # print(*pl_video_list, sep="\n")
    # pl.download_all(download_destination)

    return
示例#24
0
    def doDownload(self):
        playlistUrl = self.getPlaylistUrlFromClipboard()

        if playlistUrl == None:
            self.displayError('Playlist URL not in clipboard. Program closed.')

            return

        playlist = None

        try:
            playlist = Playlist(playlistUrl)
            playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
        except KeyError as e:
            self.displayError('Playlist URL not in clipboard. Program closed.')
            return
        except http.client.InvalidURL as e:
            self.displayError(str(e))
            return

        playlistTitle = playlist.title()

        if 'Oops' in playlistTitle:
            self.displayError(
                'The URL obtained from clipboard is not pointing to a playlist. Program closed.'
            )
            return

        playlistName, timeInfo = self.splitPlayListTitle(playlistTitle)
        targetAudioDir = AUDIO_DIR + DIR_SEP + playlistName

        if not os.path.isdir(targetAudioDir):
            targetAudioDirList = targetAudioDir.split(DIR_SEP)
            targetAudioDirShort = DIR_SEP.join(targetAudioDirList[-2:])

            if self.getConfirmation(
                    "Directory\n{}\nwill be created.\n\nContinue with download ?"
                    .format(targetAudioDirShort)) != 'yes':
                return

            os.makedirs(targetAudioDir)

        for video in playlist.videos:
            audioStream = video.streams.get_by_itag(YOUTUBE_STREAM_AUDIO)
            videoTitle = video.title
            self.msgText = self.msgText + 'downloading ' + videoTitle + '\n'
            self.msg.configure(text=self.msgText)
            self.root.update()
            audioStream.download(output_path=targetAudioDir)

        for file in [
                n for n in os.listdir(targetAudioDir) if re.search('mp4', n)
        ]:
            mp4FilePathName = os.path.join(targetAudioDir, file)
            mp3FilePathName = os.path.join(targetAudioDir,
                                           os.path.splitext(file)[0] + '.mp3')

            if timeInfo:
                timeStartSec, timeEndSec = self.splitTimeInfo(timeInfo)
                import moviepy.editor as mp  # not working on Android
                clip = mp.AudioFileClip(mp4FilePathName).subclip(
                    timeStartSec,
                    timeEndSec)  # disable if do not want any clipping
                clip.write_audiofile(mp3FilePathName)
                clip.close()
                os.remove(mp4FilePathName)
            else:
                if os.path.isfile(mp3FilePathName):
                    os.remove(mp3FilePathName)

                os.rename(mp4FilePathName, mp3FilePathName)
示例#25
0
    def playlist_download(self, play_list_link, folder_path, quality_max,
                          quality_min):
        self.folder_path = folder_path
        playlist_url = play_list_link
        if playlist_url:
            pl = Playlist(playlist_url)
            folder_name = self.filename(pl.title())
            video_list = pl.parse_links()
            self.playlistLen = len(video_list)
            self.folder_path += folder_name
            self.create_new_folder(self.folder_path)
            counter = 1
            for x in video_list:
                print(self.kill_download)
                if self.kill_download:
                    return
                self.total_size = 1
                try:
                    yt = YouTube("https://www.youtube.com/" + x)
                    y_title = self.filename(yt.title)
                    yt.register_on_progress_callback(self.show_progress_bar)
                    video_name = self.get_cnt(counter) + y_title
                    video_path = video_name + "_v"
                    audio_path = video_name + "_a"

                    if quality_max.text == 'Max Quality':
                        quality_max.text = '2160p'
                    if quality_min.text == 'Min Quality':
                        quality_min.text = '144p'

                    mx_idx = self.max_qualities.index(quality_max.text)
                    mn_idx = self.max_qualities.index(quality_min.text)

                    # ---- Adding Label of Video Title --------
                    test = f' {y_title}   '
                    print(test)
                    #reshaped_text = arabic_reshaper.reshape(test)
                    #display_text = bidi.algorithm.get_display(reshaped_text)
                    self.video_label = Label(text=f"{counter}. {test}",
                                             color=(1, 0.9, 1, 1),
                                             size_hint_y=None,
                                             height=60,
                                             halign="left",
                                             valign="middle",
                                             size_hint_x=0.6,
                                             font_name='Arial')
                    self.video_label.bind(
                        size=self.video_label.setter('text_size'))
                    self.viewerVideo.height += self.video_label.height * 2
                    self.viewerVideo.add_widget(self.video_label)

                    self.video_folder = Label(text=self.def_directory +
                                              folder_name,
                                              color=(1, 0.9, 1, 1),
                                              size_hint_y=None,
                                              height=40,
                                              halign="left",
                                              valign="middle",
                                              size_hint_x=0.2)
                    self.video_folder.bind(
                        size=self.video_folder.setter('text_size'))
                    self.viewerVideo.add_widget(self.video_folder)

                    self.video_label2 = Label(text="",
                                              color=(1, 0.9, 1, 1),
                                              size_hint_y=None,
                                              height=40,
                                              halign="left",
                                              valign="middle",
                                              size_hint_x=0.1)
                    self.video_label2.bind(
                        size=self.video_label2.setter('text_size'))
                    self.viewerVideo.add_widget(self.video_label2)

                    test2 = f"0 %"
                    self.video_label3 = Label(text=test2,
                                              color=(1, 0.9, 1, 1),
                                              size_hint_y=None,
                                              height=40,
                                              halign="right",
                                              valign="middle",
                                              size_hint_x=0.1)
                    self.video_label3.bind(
                        size=self.video_label3.setter('text_size'))
                    self.viewerVideo.add_widget(self.video_label3)

                    # ---------------------------------------------------

                    file_extension_video = ""
                    video_done = False
                    audio_done = False
                    merge_done = False

                    if self.kill_download:
                        return
                    print(mx_idx, mn_idx)
                    if mx_idx > mn_idx:
                        mx_idx = mn_idx
                    for i in range(mx_idx, mn_idx + 1):
                        try:
                            self.video_label2.text = self.max_qualities[i]
                            yt.streams.filter(adaptive=True, res=self.max_qualities[i]).first(). \
                                download(self.folder_path, filename=video_path)
                            sss = [
                                stream.subtype for stream in yt.streams.filter(
                                    adaptive=True,
                                    res=self.max_qualities[i]).all()
                            ]
                            file_extension_video = sss[0]
                            video_done = True
                            break
                        except Exception as e:
                            print(
                                f"Quality does not exist'|  {e}  |Quality:{self.max_qualities[i]}"
                            )

                    if video_done:
                        try:
                            yt.streams.filter(
                                adaptive=True,
                                only_audio=True).first().download(
                                    self.folder_path, filename=audio_path)
                            sss2 = [
                                stream.subtype for stream in yt.streams.filter(
                                    adaptive=True, only_audio=True).all()
                            ]
                            print(sss2)
                            file_extension_audio = sss2[0]
                            audio_done = True
                        except Exception as e:
                            print(f"audio does not exist' {e}")

                    if audio_done and video_done:
                        if MergeVA.merge_va(
                                isinstance,
                                f"{self.folder_path}/{video_path}.{file_extension_video}",
                                f"{self.folder_path}/{audio_path}.{file_extension_audio}",
                                f"{self.folder_path}/{video_name}.mkv"):
                            merge_done = True
                        else:
                            merge_done = False

                    # ---- Changing Label Color if Video is downloaded --------
                    if merge_done:
                        self.video_label.color = (0.13, 0.83, 0.25, 1)
                    else:
                        self.video_label.color = (1, 0, 0, 1)
                    # ---------------------------------------------------------

                    caption = yt.captions.get_by_language_code('en')
                    if caption:
                        my_file = open(self.folder_path + '/' +
                                       self.get_cnt(counter) + y_title +
                                       ".srt",
                                       "w+",
                                       encoding='UTF8')
                        my_file.writelines(caption.generate_srt_captions())
                        my_file.close()
                    else:
                        print("No Sub Found")

                except Exception as e:
                    print("Can't Download: " + str(e))
                    # ---- Changing Label Color if Video is not downloaded ----
                    #self.video_label.color = (1, 0, 0, 1)
                finally:
                    try:
                        os.remove(
                            f"{self.folder_path}/{video_path}.{file_extension_video}"
                        )
                        os.remove(
                            f"{self.folder_path}/{audio_path}.{file_extension_audio}"
                        )
                    except Exception as e:
                        print(f"can't Remove |  {e} ")
                # ---------------------------------------------------------
                counter += 1
示例#26
0
def download_playlist(URL):
    playlist = Playlist(URL)
    print("Downloading '%s' playlist...\n" % playlist.title())
    playlist.download_all()
    print("Done! Exiting...")
示例#27
0
 a = input("Choice --> ")
 if a == "1":
     url = input("Url --> ")
     if "&list=" not in url:
         p1 = Process(target=mp4)
         p1.start()
         p2 = Process(target=vbar(0.0000001))
         p2.start()
         p1.join()
         p2.join()
     if "&list=" in url:
         name1 = Playlist(url)
         name1._video_regex = re.compile(
             r"\"url\":\"(/watch\?v=[\w-]*)")
         try:
             print((name1.title()))
         except:
             pass
         print("Total videos " + str(len(name1.video_urls)) + "\n")
         print("Start Progressing...")
         for url in name1.video_urls:
             name2 = YouTube(url)
             print(name2.title)
             p1 = Process(target=mp4)
             p1.start()
             p2 = Process(target=vbar(1))
             p2.start()
             p1.join()
             p2.join()
 if a == "2":
     url = input("Url --> ")
示例#28
0
    def playlist_download(self, play_list_link, folder_path, quality_max,
                          quality_min):
        self.folder_path = folder_path
        playlist_url = play_list_link
        if playlist_url:
            pl = Playlist(playlist_url)
            folder_name = self.filename(pl.title())
            video_list = pl.parse_links()
            self.playlistLen = len(video_list)
            self.folder_path += folder_name
            self.create_new_folder(self.folder_path)
            counter = 1
            for x in video_list:
                print(self.kill_download)
                if self.kill_download:
                    return
                self.total_size = 1
                try:
                    #with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    link = "https://www.youtube.com/" + x
                    link_info = ydl.extract_info(link, download=False)

                    print("h5a")
                    y_title = self.filename(link_info['title'])
                    #yt.register_on_progress_callback(self.show_progress_bar)
                    video_name = self.get_cnt(counter) + y_title
                    video_path = video_name + "_v"
                    audio_path = video_name + "_a"

                    if quality_max.text == 'Max Quality':
                        quality_max.text = '2160p'
                    if quality_min.text == 'Min Quality':
                        quality_min.text = '144p'

                    mx_idx = self.max_qualities.index(quality_max.text)
                    mn_idx = self.max_qualities.index(quality_min.text)

                    # ---- Adding Label of Video Title --------
                    test = f' {y_title}   '
                    print(test)
                    #reshaped_text = arabic_reshaper.reshape(test)
                    #display_text = bidi.algorithm.get_display(reshaped_text)
                    self.video_label = Label(text=f"{counter}. {test}",
                                             color=(1, 0.9, 1, 1),
                                             size_hint_y=None,
                                             height=60,
                                             halign="left",
                                             valign="middle",
                                             size_hint_x=0.6,
                                             font_name='Arial')
                    self.video_label.bind(
                        size=self.video_label.setter('text_size'))
                    self.viewerVideo.height += self.video_label.height * 2
                    self.viewerVideo.add_widget(self.video_label)

                    self.video_folder = Label(text=self.def_directory +
                                              folder_name,
                                              color=(1, 0.9, 1, 1),
                                              size_hint_y=None,
                                              height=40,
                                              halign="left",
                                              valign="middle",
                                              size_hint_x=0.2)
                    self.video_folder.bind(
                        size=self.video_folder.setter('text_size'))
                    self.viewerVideo.add_widget(self.video_folder)

                    self.video_label2 = Label(text="",
                                              color=(1, 0.9, 1, 1),
                                              size_hint_y=None,
                                              height=40,
                                              halign="left",
                                              valign="middle",
                                              size_hint_x=0.1)
                    self.video_label2.bind(
                        size=self.video_label2.setter('text_size'))
                    self.viewerVideo.add_widget(self.video_label2)

                    test2 = f"0 %"
                    self.video_label3 = Label(text=test2,
                                              color=(1, 0.9, 1, 1),
                                              size_hint_y=None,
                                              height=40,
                                              halign="right",
                                              valign="middle",
                                              size_hint_x=0.1)
                    self.video_label3.bind(
                        size=self.video_label3.setter('text_size'))
                    self.viewerVideo.add_widget(self.video_label3)

                    # ---------------------------------------------------

                    file_extension_video = ""
                    file_extension_audio = ""
                    video_done = False
                    audio_done = False
                    merge_done = False

                    if self.kill_download:
                        return

                    maxx = quality_max.text.strip('p')
                    minn = quality_min.text.strip('p')
                    ids_quality = ""
                    for k, v in quality_ids.items():
                        if int(minn) <= int(k) <= int(maxx):
                            for vs in v:
                                ids_quality += f"{vs}/"
                    ydl_opts['format'] = ids_quality
                    print(ids_quality)
                    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                        meta = ydl.extract_info(
                            'https://www.youtube.com/watch?v=Vi_xyV3Tj5Q',
                            download=True)
                        #self.video_label2.text =
                        #file_extension_video
                        video_done = True

                    if video_done:
                        try:
                            ydl_opts['format'] = 'bestaudio'
                            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                                meta2 = ydl.extract_info(
                                    'https://www.youtube.com/watch?v=Vi_xyV3Tj5Q',
                                    download=True)
                                #file_extension_audio = sss2[0]
                            audio_done = True
                        except Exception as e:
                            print(f"audio does not exist' {e}")

                    if audio_done and video_done:
                        if MergeVA.merge_va(
                                isinstance,
                                f"{self.folder_path}/{video_path}.{file_extension_video}",
                                f"{self.folder_path}/{audio_path}.{file_extension_audio}",
                                f"{self.folder_path}/{video_name}.mkv"):
                            merge_done = True
                        else:
                            merge_done = False

                    # ---- Changing Label Color if Video is downloaded --------
                    if merge_done:
                        self.video_label.color = (0.13, 0.83, 0.25, 1)
                    else:
                        self.video_label.color = (1, 0, 0, 1)
                    # ---------------------------------------------------------

                    #caption = yt.captions.get_by_language_code('en')
                    #if caption:
                    #    my_file = open(self.folder_path + '/' + self.get_cnt(counter) + y_title + ".srt", "w+",
                    #                   encoding='UTF8')
                    #    my_file.writelines(caption.generate_srt_captions())
                    #    my_file.close()
                    #else:
                    #    print("No Sub Found")

                except Exception as e:
                    print("Can't Download: " + str(e))
                    # ---- Changing Label Color if Video is not downloaded ----
                    #self.video_label.color = (1, 0, 0, 1)
                finally:
                    try:
                        os.remove(
                            f"{self.folder_path}/{video_path}.{file_extension_video}"
                        )
                        os.remove(
                            f"{self.folder_path}/{audio_path}.{file_extension_audio}"
                        )
                    except Exception as e:
                        print(f"can't Remove |  {e} ")
                # ---------------------------------------------------------
                counter += 1
def test_title():
    list_key = 'PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3'
    url = 'https://www.youtube.com/playlist?list=' + list_key
    pl = Playlist(url)
    pl_title = pl.title()
    assert pl_title == 'Python Tutorial for Beginners'
示例#30
0
            else:
                try:
                    playlist_url = Playlist(payload)
                    playlist_url.populate_video_urls()
                except:
                    print(
                        "Invalid url or couldn't connect to server, check connection and try again. If this message persist, check input.\n"
                    )
                    continue

                print("Is the playlist an album?")
                check = input("\n [y]/[Enter]    [n] ==> ")

                if check == "y" or check == "yes" or check == "":
                    album = True
                    metadata = parse_title(playlist_url.title(), True)
                else:
                    metadata = None

                try:
                    track_number = 1
                    for url in playlist_url.video_urls:
                        url_yt = YouTube(url)
                        song_metadata = {}

                        if album:
                            for k in metadata:
                                song_metadata[k] = metadata[k]
                            song_metadata["tracknumber"] = str(track_number)
                            track_number += 1