def download_playlist(tag, video_id, max_downloads=None, audio_dir=AUDIO_DIR): """ Download's the audio of a YT mix playlist based on a seed video id Optional parameter to select max download number. Returns the list of converted audio files that were downloaded. """ print "Downloading playlist for \ [Tag:'{0}', Seed:'{1}]'...\n".format(tag.upper(), video_id) #use seed_video to generate mix playlist id seed_video = pafy.new(video_id) playlist_id = seed_video.mix.plid playlist = pafy.get_playlist(playlist_id)['items'] #decide number of files to download if not max_downloads: max_downloads = len(playlist) download_count = min(len(playlist), max_downloads) wav_files = [] #iterate over list of video urls to download their audio for x in xrange(-1, download_count): if x == -1: video = pafy.new(video_id) #process seed video else: video = playlist[x]['pafy'] #process playlist videos video_id = video.videoid wav_file = get_wav_from_vid(video_id) wav_files.append(wav_file) print "Playlist download completed\n" return wav_files
def downloadPlaylist(self, directory, audio=False): # create an object containing all the playlist items playlist = pafy.get_playlist(self.url) playlist_length = len(playlist['items']) video_downloaded = 0 if audio: for vid in playlist['items']: video_name = vid['pafy'].title filepath = directory + '/' + video_name.replace('/', '') try: vid['pafy'].getbestaudio().download(filepath=filepath + '.mp3') video_downloaded += 1 ratio = (video_downloaded / playlist_length) self.updateProgressBar(0, 0, ratio, 0, 0) except Exception as e: print(e) messagebox.showerror('Error', 'an Error happened while Downloading: \n' + video_name) else: for vid in playlist['items']: video_name = vid['pafy'].title filepath = directory + '/' + video_name.replace('/', '') try: vid['pafy'].getbestvideo().download(filepath=filepath + '.mp4') video_downloaded += 1 ratio = (video_downloaded / playlist_length) self.updateProgressBar(0, 0, ratio, 0, 0) except Exception as e: print(e) messagebox.showerror('Error', 'an Error happened while Downloading: \n' + video_name)
def Playlist_Download(self): playlist_url = self.tab2urlentry_2.text() save_location = self.tab2locatioentry_2.text() if playlist_url == '' or save_location == '': QMessageBox.warning( self, "Date Error", 'Provide a valid Playlist URL or save location') else: playlist = pafy.get_playlist(playlist_url) playlist_video = playlist['items'] self.lcdNumber_2.display(len(playlist_video)) os.chdir(save_location) if os.path.exists(str(playlist['title'])): os.chdir(str(playlist['title'])) else: os.mkdir(str(playlist['title'])) os.chdir(str(playlist['title'])) current_video_in_download = 1 quality = self.tab2comboBox_2.currentIndex() self.lcdNumber.display(current_video_in_download) for video in playlist_video: current_video = video['pafy'] current_video_stream = current_video.videostreams download = current_video_stream[quality].download( callback=self.Playlist_Progress) QApplication.processEvents() current_video_in_download += 1 self.lcdNumber.display(current_video_in_download)
def getYoutubePlaylist(self, plurl): '''get data from playlist url''' all_videos = [] playlist = pafy.get_playlist(plurl) for video in playlist['items']: all_videos.append(video['pafy']) return all_videos
def async_download(url, user_name): client = MongoClient() db = client.concert print("New Song to Add") print(url) if "soundcloud.com" in url: print("Source is SoundCloud") try: resource = sndcld.get("/resolve", url=url).fields() print(resource["kind"]) if resource["kind"] == "playlist": for t in resource["tracks"]: add_song_to_queue(*soundcloud_processing(t), user_name, db) elif resource["kind"] == "track": add_song_to_queue(*soundcloud_processing(resource), user_name, db) except Exception as e: pass elif "youtube.com" in url: print("Source is Youtube") try: playlist = pafy.get_playlist(url) videos = playlist["items"] for video in videos: try: add_song_to_queue(*youtube_processing(video["pafy"]), user_name, db) except Exception as e: pass # Skip invalid youtube videos except Exception as e: video = pafy.new(url) add_song_to_queue(*youtube_processing(video), user_name, db)
def startDownload(self): if not os.path.exists("downloads"): os.mkdir("downloads") self.urlBtn.config(text="Loading...") self.ipGui.update() self.url = self.urlBox.get() if "watch" in self.url and "list" in self.url: parts = self.url.split("&") for part in parts: if "list=" in part: self.url = "https://www.youtube.com/playlist?" + part break self.ipFrame.pack_forget() if "playlist" in self.url: self.selectVidsFrame.pack(fill=BOTH, padx=3, pady=3) self.vidsListBox.focus() self.pafy = pafy.get_playlist(self.url) self.ipGui.wm_title(self.pafy['title']) self.vidsObjs = [] i = 0 for vid in self.pafy['items']: self.vidsObjs.append(vid) i += 1 self.vidsListBox.insert(END, str(i) + ". " + vid['playlist_meta']['title'] + " [" + str( round(int(vid['playlist_meta']['length_seconds']) / 60, 2)) + "min]")
def playlist_downloader(request): form = PlayListForm(request.POST or None) if (form.is_valid()): playlist_url = form.cleaned_data.get('PlayLink') playlist = pafy.get_playlist(playlist_url) PlayListTitle = playlist['title'] ##playlist eke titile eka PlayListAuthor = playlist['author'] length_of_playlist = len( playlist['items']) # playlist eke tiyana videos gaaana # print(length_of_playlist) links = [] x = 0 data = [] while (x < length_of_playlist): data.append({ 'link': playlist['items'][x]['pafy'].getbest().url, 'thumb': playlist['items'][x]['pafy'].bigthumb, 'title': playlist['items'][x]['pafy'].title }) x += 1 return render( request, 'playlist.html', { 'form': form, 'data': data, 'title': PlayListTitle, 'author': PlayListAuthor }) return render(request, 'playlist.html', {'form': form})
def getPlaylists(pUrl): playlist = pafy.get_playlist(pUrl) print("Titulo de la Playlist: ", playlist["title"]) print("Playlist con ", len(playlist["items"]), " videos") print("1. Ver la lista de videos") print("2, Descargar todos los videos") askAction = input("Que opción que desea? ") contador = 1 if askAction == "1": for i in playlist["items"]: # bestVideo = i["pafy"].getbest() print("Video ", contador, ": \n", i["pafy"].title) # print("Resolución: ", bestVideo.resolution, " Extension: ", bestVideo.extension) contador += 1 time.sleep(5) elif askAction == "2": for i in playlist["items"]: bestVideo = i["pafy"].getbest() print("Titulo del Video # ", contador, ": ", i["pafy"].title) print("Resolución: ", bestVideo.resolution, " Extension: ", bestVideo.extension) print("Tamaño del archivo: ", bestVideo.get_filesize()) print("") bestVideo.download() contador += 1
def backup_stream(playlist_address: str): playlist = pafy.get_playlist(playlist_address) for song in playlist['items']: try: stream_to_SRT(song['pafy'].getbestaudio().url) except OSError: pass
def runOnce(self): """ Create pafy objects for tests. """ if hasattr(Test, "hasrun"): return Test.quick = os.environ.get("quick") Test.videos = VIDEOS if not Test.quick else [] Test.playlists = PLAYLISTS if not Test.quick else [] for video in Test.videos: time.sleep(0 if Test.quick else self.delay) video['pafy'] = pafy.new(video['identifier']) video['streams'] = video['pafy'].streams video['best'] = video['pafy'].getbest() video['bestaudio'] = video['pafy'].getbestaudio() video['bestvideo'] = video['pafy'].getbestvideo() # get urls for age restricted vids if video['pafy'].videoid == "07FYdnEawAQ": _ = video['pafy'].streams[0].url _ = video['pafy'].streams[1].url_https del _ for playlist in Test.playlists: playlist['fetched'] = pafy.get_playlist(playlist['identifier']) Test.hasrun = True
def getYoutubePlaylist(plurl): """get data from playlist url""" all_videos = [] playlist = pafy.get_playlist(plurl) for video in playlist["items"]: all_videos.append(video["pafy"]) return all_videos
def Downloadbtn3(self): self.pushButton_11.setEnabled(False) PlayListurl = self.lineEdit_10.text() saveLocation = self.lineEdit_9.text() try: playlist = pafy.get_playlist(PlayListurl) numberOfVideoes = len(playlist['items']) os.chdir(saveLocation) os.mkdir(str(playlist['title'])) os.chdir(str(playlist['title'])) start = self.spinBox.value() - 1 end = self.spinBox_2.value() for i in range(start, end): video = playlist['items'][i]['pafy'] mystreams = video.streams target = video.getbest() selectedQuality = self.comboBox_3.currentText().split(" ")[1] for mystream in mystreams: if str(mystream.quality) == selectedQuality: target = mystream break self.Filesizelbl3(target.get_filesize()) self.label_24.setText("Video Name : " + str(target.title)) self.label_22.setText("Current Video : " + str(i - start + 1) + "/" + str(end - start)) target.download(quiet=True, callback=self.progressbar3) except Exception: QMessageBox.warning(self, "Download Error", "The Download Faild") self.MyReset3() return QMessageBox.information(self, "Download Completed", "The Download Finished") self.MyReset3()
def downloadplaylist(url): print("Give a download location") root = Tk() root.withdraw() filename = filedialog.askdirectory() playlist = pafy.get_playlist(url) playlen = len(playlist['items']) i=0 while i < playlen: pafyobj = playlist['items'][i]['pafy'] aobj = pafyobj.getbest() print("---------------------------------------------------------") print("Now Downloading: "+pafyobj.title) print("Size is: %s" % aobj.get_filesize) print("Video Resolution is: "+aobj.resolution) fileloc = aobj.download(filepath=filename,quiet=False) print("Videos downloaded at: "+filename) print("Do you want to open the download location?\n1.Yes\n2.No") ch = int(input()) if ch == 1: os.startfile(filename) else: print("Thank you for using this script!") print("EAT................SLEEP..................CODE...................REPEAT")
def queue(self, yturl='',kind=''): @reconnect def appendPlaylist(self,t): self.playlist.append(track) self.client.add(track.file) if self.client.status()['playlistlength']=='1': self.client.play() if kind=="video": try: self.loading=True track=model.Track(yturl) appendPlaylist(self,track) except Exception as e: print(e) finally: self.loading=False if kind=="playlist": pl=pafy.get_playlist(yturl) for i in pl['items']: try: self.loading=True track=model.Track(1,i['pafy']) appendPlaylist(self,track) except Exception as e: print(e) finally: self.loading=False
def enqueue_audio_playlist(self, arg): """Add all audio streams in a YouTube playlist to the playback queue. :param arg: a YouTube playlist id """ logging.info('enqueue_audio_playlist : %s', arg) try: count = len(self.queue) playlist = pafy.get_playlist(arg) items = playlist.get('items') if len(items) > 0: for item in items: yt_video = item.get('pafy') if yt_video: yt_audio = yt_video.getbestaudio(preftype="webm") if yt_audio: self.add_to_playback_queue(audio=yt_audio, video=yt_video) if count == len(self.queue): raise ValueError self.__update_play_queue_order() except ValueError: raise ValueError(str("Playlist not found : %s" % arg))
def actualDownloader(): s = v.get() flag = 0 type = 1 #input("Hit 1 for video,2 for playlist") type = int(type) #input("Hit 1 for best clarity, 2 for worst, 3 for other") result = s quality = actualQual c = 0 if type == 1: url = result video = pafy.new(url) best = video.streams for b in best: print(str(c) + str(b)) c += 1 if flag == 1: index = raw_input("Enter index") index = int(index) if quality == 2: global index index = c - 1 elif quality == 1: global index index = 0 filename = video.streams[index] print(filename) x = filename.download(filepath=filename.title + "." + filename.extension, callback=callback) cwd = os.getcwd() global message message = filename.title + " was save to " + cwd finalAlert() else: url = result video = pafy.get_playlist(url) for i in xrange(1, 100): c = 0 best = video['items'][i]['pafy'].streams for b in best: print(str(c) + str(b)) c += 1 if flag == 1: index = raw_input("Enter index") index = int(index) elif quality == 2: index = c - 1 elif quality == 1: index = 0 filename = video['items'][i]['pafy'].streams[index] try: x = filename.download(filepath="C:/ProgramOut") except: x = filename.download(filepath="C:/")
def Playlist_Download(self): playlist_url = self.lineEdit_5.text() save_location = self.lineEdit_6.text() if playlist_url == "" or save_location == "": QMessageBox.warning(self, "Data Error", "Please Enter a valid url or save location") else: playlist = pafy.get_playlist(playlist_url) playlist_videos = playlist['items'] self.lcdNumber_2.display(len(playlist_videos)) os.chdir(save_location) if os.path.exists(str(playlist['title'])): os.chdir(str(playlist['title'])) else: os.mkdir(str(playlist['title'])) os.chdir(str(playlist['title'])) current_video_in_download = 1 quality = self.comboBox_2.currentIndex() for video in playlist_videos: current_video = video['pafy'] current_video_stream = current_video.videostreams self.lcdNumber.display(current_video_in_download) download = current_video_stream[quality].download( callback=self.Playlist_Progress) current_video_in_download += 1
def getSongs(): prompts = [["Song: ", "Artist: "], ["URL: "]] option = safeInput("(1) Song and Artist, (2) URL: ", [1, 2]) - 1 #note: test url by doing a get_playlist and then catching valueErrors values = {prompts[option][i].replace(": ", ""): input(prompts[option][i]) for i in range(len(prompts[option]))} if(option==0): print("Getting page...") html = requests.get("http://www.youtube.com/results?search_query={0}+{1}+audio".format(values["Artist"], values["Song"])).text print("Parsing...") parser = Parser() parser.initLinks() parser.feed(html) parser.cleanLinks() links = parser.links for link in links: vid = pafy.new(link) if safeInput("Downloading '{0}'. Continue? (y/n): ".format(vid.title), str) in "yY": return [vid] #if we get here we've go no more videos print("No more videos in the list... Exiting.") sys.exit() elif(option==1): try: playlist = pafy.get_playlist(values["URL"]) return [item['pafy'] for item in playlist['items']] except ValueError: return [pafy.new(values["URL"])]
def download_playlist(tag, video_id, max_downloads=None, audio_dir=AUDIO_DIR): """ Download's the audio of a YT mix playlist based on a seed video id Optional parameter to select max download number. Returns the list of converted audio files that were downloaded. """ print "Downloading playlist for \ [Tag:'{0}', Seed:'{1}]'...\n".format(tag.upper(),video_id) #use seed_video to generate mix playlist id seed_video = pafy.new(video_id) playlist_id = seed_video.mix.plid playlist = pafy.get_playlist(playlist_id)['items'] #decide number of files to download if not max_downloads: max_downloads = len(playlist) download_count = min(len(playlist),max_downloads) wav_files = [] #iterate over list of video urls to download their audio for x in xrange(-1,download_count): if x == -1: video = pafy.new(video_id) #process seed video else: video = playlist[x]['pafy'] #process playlist videos video_id = video.videoid wav_file = get_wav_from_vid(video_id) wav_files.append(wav_file) print "Playlist download completed\n" return wav_files
def download(): url = "" urls = "" url = request.forms.get("url") urls = request.forms.get("urls") print "url:::::::"+url print "urls::::::"+urls if urls: print "enter urls" playlist = pafy.get_playlist(urls) videos = playlist['items'] directory = "./" + playlist['title'] best =[] for video in videos: p = video["pafy"] title = p.title best.append([p.getbestaudio().url,title]) if best: return template("downloadlist",urllist=best) else: return "URLが正しくありません。適切なモードを選択して下さい。" elif url: print "enter url" a = pafy.new(url) return "<a href="+a.getbestaudio().url+">"+ a.title+"</a>"
def downloadPlaylist(self): playlistUrl = self.lnEdtPlaylistTb2.text() saveLocation = self.lnEdtSvPlaylistTb2.text() if playlistUrl == '' or saveLocation == '': QMessageBox(self, 'Data Error', 'Please provide valid url or save location') else: playlist = pafy.get_playlist(playlistUrl) print(playlist) playlistVideos = playlist['items'] self.playlistLcdNumber.display(len(playlistVideos)) os.chdir(saveLocation) if os.path.exists(str(playlist['title'])): os.chdir(str(playlist['title'])) else: os.mkdir(str(playlist['title'])) os.chdir(str(playlist['title'])) quality = self.comboBoxPlaylist.currentIndex() currentVideoInDownload = 1 QApplication.processEvents() for video in playlistVideos: # if video['playlist_meta']['privacy'] == 'public': self.currentLcdNumber.display(currentVideoInDownload) currentVideo = video['pafy'] print(currentVideo) currentVideoStreams = currentVideo.videostreams download = currentVideoStreams[quality].download( callback=self.playlistProgress) QApplication.processEvents() currentVideoInDownload += 1
def getYoutubePlayList(url, more=False, audio=False): res = {} res["type"] = "LIST" res["yurl"] = url try: import pafy playlist = pafy.get_playlist(url) res["title"] = playlist["title"] res["author"] = playlist["author"] res["description"] = playlist["description"] res["count"] = len(playlist["items"]) res["list"] = [] for p in playlist["items"]: now = {} x = p["pafy"] now["title"] = x.title now["thumb"] = x.thumb now["length"] = x.length now["duration"] = x.duration if more: now["extension"] = x.getbest().extension now["filesize"] = "{0:.2f}".format(x.getbest().get_filesize() / (1024 * 1024.0)) + "MB" now["url"] = x.getbest().url res["list"].append(now) return {"status": "success", "res": res, "msg": "data returned"} except Exception, e: return {"status": "error", "res": None, "msg": "Unknown Error # " + str(e)}
def download_and_preprocess_data(urls_source_file, out_path): if not os.path.exists(urls_source_file): raise ValueError("URLs source file does not exist.") if not os.path.isdir(out_path): os.makedirs(out_path) audio_out_path = os.path.join(out_path, "audio/") if not os.path.isdir(audio_out_path): os.makedirs(audio_out_path) subs_out_path = os.path.join(out_path, "subs/") if not os.path.isdir(subs_out_path): os.makedirs(subs_out_path) with open(urls_source_file, "r") as f: for url in f: playlist = pafy.get_playlist(url) for item in playlist['items']: try: try: #downloading subs filename = os.path.join(subs_out_path, "%(id)s.%(ext)s") p = subprocess.Popen([ "youtube-dl", "-o", filename, "-v", "--skip-download", "--write-auto-sub", "--sub-format", "vtt", "--sub-lang", "ru", item['pafy'].videoid ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode != 0: raise Exception("Failed to download subs: %s" % str(err)) print("%s: \nsubs were downloaded" % item['pafy'].videoid) if not os.path.isfile( os.path.join( subs_out_path, item['pafy'].videoid + ".ru.vtt")): continue # downloading audio audio = item['pafy'].getbestaudio("m4a") filename = os.path.join( audio_out_path, item['pafy'].videoid + "." + audio.extension) result = audio.download(filename) print("audeo was downloaded") except: pass #raise except: pass
def is_url_real(self): try: playlist = pafy.get_playlist(self.playlist_url) return True except ValueError: return False except OSError: return False
def nc_playlist_info(playlist_id): print ' > process playlist(%s)' % (playlist_id) pl = pafy.get_playlist(playlist_id) data = {} data['key'] = playlist_id data['description'] = pl['description'] data['items'] = map(lambda x: x['pafy'].videoid, pl['items']) return data
def download_playlist(self): """Downloads media items within a playlist""" playlist = pafy.get_playlist(self.url) media_count = len(playlist['items']) print("Downloading {} items from {}".format(media_count, playlist['title'])) for i, media in enumerate(playlist['items']): print("Downloading {} / {}.".format(i + 1, media_count)) self.download_by_format(media['pafy'])
def parseUrl(self): try: # try to declare the url as a playlist self.playlist = pafy.get_playlist(self.url) # assuming the declaration did not fail with ValueError proceed to parse further print(self.playlist["title"]) self.title(self.playlist["title"]) try: # check to see if the url of the playlist ALSO contains a video self.video = pafy.new(self.url) # assuming the declaration did not fail with some error proceed to ask user what course of action should be taken valid = False while not valid: # Make user decide the best course of action print("Download the whole playlist or just this video?") print(" 1.) The whole playlist from the begining.") print(" 2.) Select where to start and where to end.") print(" 3.) Download this video only.") print("=================================================================") opt = input("Enter 1, 2, or 3: ") if opt == "1": # Classify url as a playlist and set the limits to beggining and end self.ytype = "PLIST" self.conf.data["limit"][0] == 1 self.conf.data["limit"][1] == -1 valid = True elif opt == "2": # Classify url as a playlist and make the user choose the limits manually self.conf.set_pl_bound() self.ytype = "PLIST" valid = True elif opt == "3": # Classify the url as a video self.ytype = "VIDEO" valid = True else: # Make the user pick again and explain that they didnt choose from the available options print("I didn't understand that :C") valid = False except Exception as e: self.ytype = "PLIST" except ValueError: try: # Assuming the url is not a playlist, declare the url as a video, and classify it as such self.video = pafy.new(self.url) # print(self.video.title) self.title(self.video.title) self.ytype = "VIDEO" except ValueError: # Assuming the URL is not a video or a playlist, it falls outside of the scope of this program # inform user, and classify the URL as "NONE" print("This is not a youtube or other compatable url.") self.ytype = "NONE" except OSError: # self.parseUrl() was passed something that it could not parse print("I didn't understand that :C") self.ytype = "NONE"
def playListuRL(self): plaListuRl = pafy.get_playlist(self.uRl) playListUzunluk = len(plaListuRl['items']) data = [] print(f'''{plaListuRl['title']} Listesinde Bulanan Videolar''') for i in range(playListUzunluk): data.append(plaListuRl['items'][i]['pafy'].watchv_url) print(f'''{i + 1} {plaListuRl['items'][i]['pafy'].title}''') return data
def _procura_video(self, video, tipo): """.""" try: if tipo: return pafy.new(video) else: return pafy.get_playlist(video) except: return self._procura_video(video, tipo)
def getYoutubePlaylist(self, plurl): all_videos = [] try: playlist = pafy.get_playlist(plurl) for video in playlist['items']: all_videos.append(video['pafy']) except: pass return all_videos
def generate_urls_list(self, youtube_url, playlist = True): playlist = pafy.get_playlist(youtube_url) for i_video in range(len(playlist['items'])): v = playlist['items'][i_video]['pafy'] print i_video try: self.stream.append(v) except: pass
def load(self, playlist): p = pafy.get_playlist(playlist, basic=False) playlist = Playlist(p['title']) for item in p['items']: playlist.add(PafySong(item['pafy'])) return playlist
class MediaPlayer: # Create new VLC Instance instance = vlc.Instance() mood = "chill" oldMood = "" # Create a MediaPlayer with the default instance player = instance.media_player_new() chill = "https://www.youtube.com/playlist?list=PLJ2DFXwybJACJtqhHhIz7xI1w8cfQ2Kiw" energy = "https://www.youtube.com/playlist?list=PLkMRAPworbEelkUPJrQEF5pBTVgzNLxWG" playlist_chill = pafy.get_playlist(chill) playlist_energy = pafy.get_playlist(energy) def getURL(self): try: # Youtube Playlist link if self.mood == "energy": video = self.playlist_energy['items'][randint( 0, len(self.playlist_energy['items']))]['pafy'] elif self.mood == "chill": video = self.playlist_chill['items'][randint( 0, len(self.playlist_chill['items']))]['pafy'] # Best url for video at best settings best = video.getbest(preftype="webm") # Load the media file media = self.instance.media_new(best.url) # Add the media to the player self.player.set_media(media) except: self.getURL() def play_video(self): while True: if self.oldMood != self.mood: self.getURL() self.player.play() self.oldMood = self.mood sleep(100)
async def youtubePlaylistTreatment(context, url): ytbPlaylist = pafy.get_playlist(url) for index in range(len(ytbPlaylist['items'])): video = f"www.youtube.com/watch?v={ytbPlaylist['items'][index]['pafy'].videoid}" #await play(context, video) Server[context.guild.id].queue.append(video) Server[context.guild.id].copyQueue.append(video) Server[context.guild.id].requestBy.append(context.author.mention) return
def playlist_download(self): playList_url = self.lineEdit_11.text() v = pafy.get_playlist(playList_url) location = self.lineEdit_12.text() st = v.allstreams quality = self.comboBox.currentIndex() down = st[quality].download(filepath=location) QMessageBox.information(self, "Download Completed", "Your Download Finished")
def url_getter(url): # get url and make needed changes on it global details, playlist details = pafy.get_playlist(url) playlist = pafy.get_playlist2(url) print(details['title']) print('length of the playlist: {}'.format(len(playlist))) music_getter(details, playlist)
def __init__(self, url, playlist=True, seekable=True): super(YoutubeFS, self).__init__() self.playlist = playlist self.seekable = seekable self.url = url self._cache = {} if playlist: self._title = pafy.get_playlist(self.url)['title'] else: self._title = pafy.new(self.url).title
def get_video_by_url(url, is_playlist=False, index=0): if is_playlist: playlist = pafy.get_playlist(url)['items'] if not (len(playlist) > index and index >= 0): index = 0 video = playlist[index]['pafy'] else: video = pafy.new(url) return video
def load_saved_playlist(self, list_name): if list_name not in self.saved_lists: return False #Load list pickle object filename = PL_DIR + "/" + list_name with open(filename, 'rb') as handler: url = pickle.load(handler)['url'] self.playlist = pafy.get_playlist(url) self.queue_len = len(self.playlist['items']) return True
def get_ytplaylist_pafys(playlist_url): """ Returns a dict with :class:`pafy.Pafy` objects that each represent an item in the playlist. :param playlist_url: URL of the playlist :type playlist_url: str :return: A dict of :class:`pafy.Pafy` objects. :rtype: dict """ playlist = pafy.get_playlist(playlist_url) return playlist["items"]
def main(): parser = argparse.ArgumentParser(description=description) parser.add_argument('-p','--pl', help='playlist url') parser.add_argument('-v', '--video', nargs='?', help='video url') args = parser.parse_args() if args.video: for video in args.video: download(getyt(video)) if args.pl: playlist = pafy.get_playlist(args.pl) for i in playlist['items']: download(i['pafy'])
def download_playlist(url_link): """ Download all videos from playlist """ pl_link = pafy.get_playlist(url_link) chose = raw_input("Chose format (A)audio or (V)video download\n=>") if chose == 'A': for element in range(len(pl_link['items'])): link_video = pl_link['items'][element]['pafy'].getbestaudio() link_video.download(filepath='./music') elif chose == 'V': for element in range(len(pl_link['items'])): link_video = pl_link['items'][element]['pafy'].getbest() link_video.download(filepath='video') print "Download finished"
def get_pafy(url): """Generate a pafy object to pull thumbnail images. :param str url: The URL to the youtube video. """ is_playlist = "/videoseries" in url if is_playlist: videos = pafy.get_playlist(url) if len(videos['items']): return videos['items'][0]['pafy'] return pafy.new(url)
def get_videos_from(result: UrlResult) -> Iterable[Video]: if result.type == "single_video": yield Video(result.url) elif result.type == "playlist": try: for video in pafy.get_playlist(result.url)['items']: try: yield Video(video['pafy']) except: continue except ValueError: print("Playlist is missing/private.")
def downloadPlaylist(self, playlistID, audio=False, path=""): playlist = pafy.get_playlist(playlistID) for item in playlist['items']: meta = item['playlist_meta'] # get some info about the current track self._currentTrackTitle = meta["title"] self._currentTrackDuration = meta["duration"] self._currentTrackID = meta["encrypted_id"] self._download(item['pafy'], audio=audio, path=path)
def updatePlaylist(playlist): p = pafy.get_playlist(playlist) d = info['directory'] + '/' + p['title'] print 'Updating ' + p['title'] + ' playlist...' lastTrack = info['playlists'][p['playlist_id']] items = p['items'] for item in items[::-1]: if item['pafy'].videoid==lastTrack: break item['pafy'].getbestaudio().download(d) print '\nDone!' lastTrack = items[-1]['pafy'].videoid info['playlists'][p['playlist_id']] = lastTrack convertFiles(d) saveInfo()
def create_playlist_object(self): try: playlist = pafy.get_playlist(self.playlist_url) self.playlist_title = playlist['title'] self.playlist_author = playlist['author'] self.playlist_size = len(playlist['items']) if not self.is_there_playlist_obj: self.dir_to_dl = self.dir_to_dl +'@'+self.playlist_author+' #' \ + self.playlist_title+'\\' self.is_there_playlist_obj = True if not os.path.exists(self.dir_to_dl): os.makedirs(self.dir_to_dl) return playlist except FileNotFoundError: return False
def load(self, playlist): logger.info('parsing playlist: %s', playlist) p = pafy.get_playlist(playlist, basic=False) for i, item in enumerate(p['items'], start=1): logger.info('processing item %s/%s - %s', i, len(p['items']), item['playlist_meta']['title']) try: song = YoutubeSong(item) except Exception as e: logger.info('skipping because of "%s"', e) else: logger.debug('got song: %s', song) if song is not None: yield song
def fetchPlaylistAndDownload(playlistID): playlist = pafy.get_playlist(playlistID) for item in playlist['items']: meta = item['playlist_meta'] title = meta['title'] added = meta['added'] #print meta #print item['pafy'].videoid print title #print "\n\n" download(item['pafy'], audio=False) #print(title + ' was published on ' + added) print("")
def download_playlist(self): song_count = 0 if not self.is_url_real(): return 1 playlist = pafy.get_playlist(self.playlist_url) self.playlist_title = playlist['title'] self.playlist_author = playlist['author'] self.playlist_size = len(playlist['items']) self.dir_to_dl = self.dir_to_dl +'@'+self.playlist_author+' #' \ + self.playlist_title+'/' if not self.path_check(): return 2 print ('Syncing YouTube playlist [' + \ self.filter_string_sequence(playlist['title']) +'] '+'('+ \ str(self.playlist_size)+' songs) '+'with ' + \ self.filter_string_sequence(self.dir_to_dl)) for videos in playlist['items']: try: song_count += 1 stream = videos['pafy'].getbestaudio() if stream is not None: stream._title = stream.generate_filename() if self.is_song_downloaded(stream._title): continue stream._title = stream._title[:-4] print ('Downloading' + ' -> ' \ + self.filter_string_sequence(stream.filename).ljust(90) + str(song_count) + '/' + str(self.playlist_size)) stream.download(filepath=self.dir_to_dl, meta=True) except OSError: pass except IOError: pass except ZeroDivisionError: pass except KeyError: pass except IndexError: pass except AttributeError: pass print ('Done'.ljust(90)) print ('-----------------') return 0
def downloadPlaylist(self, url, start=None, end=None, ptype='mp4', silent=False, audio=False): plist = pafy.get_playlist(url) videos = [item['pafy'] for item in plist['items']] if start is None: start = 0 else: start = start - 1 if end is None: end = len(videos) for video in videos[start:end]: try: if audio: best = video.getbestaudio() else: best = video.getbest(preftype=ptype) best.download(quiet=silent, filepath="../../files") except: print "Error:skipping"
def downloadPlaylist(playlist): if info['directory'] == '': print '\033[91m ERROR: Please set a directory to store the playlist\033[0m' return p = pafy.get_playlist(playlist) if info['playlists'].has_key(p['playlist_id']): updatePlaylist(playlist) else: d = info['directory'] + '/' + p['title'] if not os.path.exists(d): os.makedirs(d) items = p['items'] print 'Downloading ' + p['title'] + ' playlist...' for item in items: item['pafy'].getbestaudio().download(d) print '\nDone!' lastTrack = items[-1]['pafy'].videoid info['playlists'][p['playlist_id']] = lastTrack convertFiles(d) saveInfo()
def extract(self, url, outDir, maxDownload): if "&index=" in url: playlist = pafy.get_playlist(url) # length of playlist item = len(playlist["items"]) if maxDownload == 0: downloadNum = item else: downloadNum = min(item, maxDownload) print("downloading %d songs from the playlist" % downloadNum) for num in range(0, downloadNum): bestaudio = playlist["items"][num]["pafy"].getbestaudio() filename = bestaudio.download(filepath=outDir) else: video = pafy.new(url) bestaudio = video.getbestaudio() filename = bestaudio.download(filepath=outDir)
def generateJSON(_file,_outputfile): """Generates the JSON String with all metadata Args: _file: filepath to JSON file Returns: nothing for the moment """ artistlist = open(_file) artistlist = json.load(artistlist) outputfile = open(_outputfile) outputfile = json.load(outputfile) for key, videoplayer in artistlist.items(): for works, value in sorted(videoplayer.items()): # check for dictionary "Works" if type(value) == dict: # sort them by numeric key indices 0, 1, 2 ... n instead of 0, 1, 10, 11 ... n for k,v in sorted(value.items(), key=lambda (k,v): (int(k),v)): if v['Playlisturl'] != "": _w[k]['Artistname'] = v['Artistname'] _w[k]['Concept'] = v['Concept'] _w[k]['Title'] = v['Title'] _w[k]['Playlisturl'] = v['Playlisturl'] _w[k]['PlaylistID'] = '' _w[k]['ID'] = k if v['DownloadMetaFlag'] == 1: print "... Getting playlist for: " + _w[k]['Artistname'] plpafy = pafy.get_playlist(v['Playlisturl']) getMetaDataForPlaylist(k,plpafy) getAllVideos(k,plpafy,v['DownloadVideosFlag']) elif v['DownloadMetaFlag'] == 0: print "... Replacing existing Metadata for %s with keyid: %s" %(_w[k]['Artistname'],k) _w[k] = outputfile['Videoplayer']['Works'][k] else: print "... Couldn't get playlist for keyid: %s" %(k) # check if dict value is string "Title" if type(value) == unicode: works_output['Videoplayer']['Title'] = value works_output['Videoplayer']['AssetsPath'] = '../assets/'
def download_from_youtube_playlist(playlist_url, output_stream_queue=None): playlist = pafy.get_playlist(playlist_url) files = [] if playlist and playlist.get('items'): cwd = os.getcwd() folder_name = os.path.join(cwd, ftransc.utils.get_safe_filename(playlist['title'])) os.mkdir(folder_name) os.chdir(folder_name) for item in playlist['items']: try: stream = item['pafy'].getbestaudio() except KeyError: continue filename = ftransc.utils.get_safe_filename(stream.title) output_filename = os.path.join(folder_name, stream.download(filepath=filename, quiet=True)) if output_stream_queue is not None: output_stream_queue.put(output_filename) else: files.append(output_filename) os.chdir(cwd) return files
def playlist(url, start, end, ptype='mp4', silent=False, audio=False): plist = pafy.get_playlist(url) videos = [item['pafy'] for item in plist['items']] if start is None: start = 0 else: start -= 1 if end is None: end = len(videos) for video in videos[start:end]: try: if audio: best = video.getbestaudio() else: best = video.getbest(preftype=ptype) print "\nDownloading : " + video.title best.download(quiet=silent, filepath="playlists/") msg = "Completed : " + video.title + "\n" print msg except: msg = "Error, skipping : " + video.title print msg