def get_song_from_title(self, full_title): youtube = Youtube() song = youtube.get_youtube_video(full_title) if not (song): logger.info('No Match in Youtube. Searching Soundcloud') soundcloud = Soundcloud() song = soundcloud.get_soundcloud_song(full_title) return song
def delete_playlist_mark_read(self, playlist_url,key,limit=None): if 'youtube' in playlist_url: youtube=Youtube() playlist_name, playlist_desc, playlist_id = youtube.get_playlist_id_name_description(playlist_url, limit) elif 'spotify' in playlist_url: spotify = Spotify() playlist_name, playlist_desc, tracks = spotify.get_playlist_name_desc_tracks(playlist_url) gmusic = GoogleMusic() gmusic.delete_playlist_if_exists(playlist_name) self.p.archive(key) self.p.commit()
def get_song_list(self, tracks, gmusic=None, strict=False, collect_skipped=False): song_list = [] for tracks in tracks['items']: track = tracks['track'] artist = self.html_parser.unescape(track['artists'][0]['name']) title = self.html_parser.unescape(track['name']) popularity = track['popularity'] song = Song(artist=artist, title=title, spotify_popularity=popularity) if gmusic: first_result = None try: first_result = gmusic.search_song(song, strict) if first_result is None: raise ValueError('No result from Google Music') except Exception as e: logger.debug('Exception: {}'.format(e)) logger.info( u'Skipped {}. Added to to Watch Playlist'.format( song.full_title)) if collect_skipped: youtube = Youtube(secure=False) if song.youtube_id is None: youtube_video = youtube.get_youtube_video( full_title=song.full_title) if youtube_video: song.youtube_id = youtube_video.youtube_id song.video_link = "http://www.youtube.com/watch?v={}".format( youtube_video.youtube_id) if song.youtube_id: if youtube.to_watch_playlist is None: youtube.to_watch_playlist = youtube.get_playlist( 'https://www.youtube.com/playlist?list={}'. format(Config.YOUTUBE_TO_WATCH_PLAYLIST)) existing_ids = youtube.to_watch_playlist.song_df.youtube_id.values if song.youtube_id not in existing_ids: ToDoist.ToDoist().add_item( item=song.video_link, project_name=Config. TODOIST_YOUTUBE_COLLECT_PROJECT) song.google_music_store_id = gmusic.get_store_id(first_result) song.google_music_rating = gmusic.get_google_rating( first_result) song_list.append(song) return song_list
def iTunesLibSearch(songPaths, iTunesPaths={}, searchParameters=''): """ Performs a search on users iTunes library by album, artist and genre params: paths to all iTunes songs, iTunes dictionary object, search term Returns: iTunesPaths dict with songs matching the search added """ for songPath in songPaths: songNameSplit = songPath.split(os.sep) formattedName = songNameSplit[len(songNameSplit) - 1].lower( ) + " " + songNameSplit[len(songNameSplit) - 2].lower( ) + " " + songNameSplit[len(songNameSplit) - 3].lower() formattedName = Youtube.removeIllegalCharacters(formattedName) searchParameters = Youtube.removeIllegalCharacters(searchParameters) # songNameSplit is list of itunes file path.. artist is -3 from length, song is -1 if searchParameters.lower() in formattedName.lower(): iTunesPaths['searchedSongResult'].append(songPath) iTunesPaths['searchedSongResult'] = sorted( iTunesPaths['searchedSongResult']) # sort tracks alphabetically return iTunesPaths
def get_song(self,item): #Checking Youtube Links youtube=Youtube() link = youtube.extract_youtube_link_from_text(item) if link: full_title = youtube.get_title_from_youtube_code(get_youtube_code_from_link(link)) song = Song(full_title= full_title, video_link = link, ) else: soundcloud = Soundcloud() link = soundcloud.extract_soundcloud_link_from_text(item) if link: song= Song(full_title=soundcloud.get_title_soundcloud(link), video_link = link) else: #Items without a link songs = youtube.youtube_search(item,1) if len(songs) >0 : song = songs[0] else: return None return song
def main(): json_file = json.loads(open("config.json", "r").read()) try: spotify_obj = Spotify(json_file) spotify_obj.get_recommended_songs() youtube_obj = Youtube(json_file) youtube_obj.get_liked_videos(spotify_obj) spotify_obj.populate_playlist() send_email( json_file, "Music transfer succeeded", "No errors were found. " "{} new song(s) were added to your playlist.".format( spotify_obj.number_of_songs_added())) except Exception as error: error_message = "Error: {}\n\n" \ "Stacktrace: {}".format(error, traceback.format_exc()) send_email(json_file, "Playlist generator failed", error_message)
async def yt (ctx, num, *args): global players global _queue try: search_num = int (num) except: await ctx.send('**❗ Invalid number of search, canceled request**') return search = " ".join(args[:]) voice_state = ctx.author.voice if voice_state is None: await ctx.send('**❗ Join a channel**') return voice_channel = ctx.author.voice.channel channel_name = str(voice_channel) if ctx.voice_client is None: await voice_channel.connect() await ctx.send(f'**✅ Joined in {channel_name}**') voice = discord.utils.get(client.voice_clients, guild=ctx.guild) await ctx.send(f'**🔎 Searching {search_num} videos in Youtube: {search}**') videos = Youtube.get_videos(search, search_num) if len(videos) > 0: await ctx.send(f'**🆗 Found {len(videos)} results**') else: await ctx.send('**❗ Unfortunately the request limit has expired**') return await show_search(videos, ctx) msg = await client.wait_for("message", check=lambda message: message.author == ctx.author) try: option = int(msg.content) except: await ctx.send('**❗ Request canceled, invalid option**') return if option == -1: await ctx.send('**❗ Request canceled**') return elif option > len(videos): await ctx.send('**❗ Request canceled, invalid option**') return _queue.append(Element(msg.author, videos[option - 1])) try: player = await YTDLSource.from_url(url=videos[option - 1].link, stream = True) players.append(player) except: del _queue[len(_queue) - 1] await ctx.send('**❗ Error with this video, canceled request**') return if voice.is_playing(): await show_new_element(ctx) return voice.play(player, after=lambda e: repeat(ctx.guild, voice, players)) del players[0] await ctx.send(f'**🎶 Now playing: {videos[option - 1].link}**')
def get(self): app = Youtube(storage_file="../oauth2.json", client_secrets_file="../desktop_app.json") self.finish(app.get_subscriptions())
def get(self): category = self.get_argument("category", None) app = Youtube(storage_file="../oauth2.json", client_secrets_file="../desktop_app.json") new_uploads = app.get_uploads_from_category(category=category) self.finish({"new_uploads": new_uploads})
from YoutubeDownloader import YoutubeDownloader from Youtube import Youtube from pytube import YouTube as ABC API = 'AIzaSyD298lx0cwZkpw8syTGoxC4Fs9ed08zbCw' downloader = Youtube(API) # video = downloader.download_video_caption('CeOadxT7kPA','en') # print(video) # downloader.download_channel('UCAuUUnT6oDeKwE6v1NGQxug',10,'/home/bachnguyen/Pictures/test',4) # downloader.download('neCmEbI2VWg','/home/bachnguyen/Documents','test') abc = ABC('https://www.youtube.com/watch?v=iBa9EoEbb38') caption = abc.captions.get_by_language_code('en').generate_srt_captions() f = open("test.srt", "a") f.write(caption) f.close()
def run_download(microPhone, recognizer, iTunesInstalled=True, searchFor='', autoDownload=False, pathToDirectory='', iTunesPaths={}, speechRecogOn=False, debugMode=False, trackProperties={}): localDumpFolder = os.path.join(pathToDirectory, "dump") pathToSettings = os.path.join(pathToDirectory, 'settings.json') response = Youtube.getYoutubeInfoFromDataBase( searchQuery={'search_query': ''}, songName=searchFor) youtubeResponseObject = Youtube.youtubeSongDownload( youtubePageResponse=response, autoDownload=autoDownload, pathToDumpFolder=localDumpFolder, pathToSettings=pathToSettings, debugMode=debugMode) # youtubeSongDownload returns none if there is no songPath or if user wants a more specific search while youtubeResponseObject['error'] == '404': searchFor = input('Please enter your more specific song: ') newYoutubeResponseAsResultOfSearch = Youtube.getYoutubeInfoFromDataBase( searchQuery={'search_query': ''}, songName=searchFor) youtubeResponseObject = Youtube.youtubeSongDownload( youtubePageResponse=newYoutubeResponseAsResultOfSearch, autoDownload=autoDownload, pathToDumpFolder=localDumpFolder, pathToSettings=pathToSettings, debugMode=debugMode) if youtubeResponseObject[ 'error'] == '405': # return out if user wants to cancel. return # No none type is good news.. continue as normal if youtubeResponseObject['songPath'] != None and youtubeResponseObject[ 'error'] == None: if speechRecogOn == True: computer.speak( sys.platform, 'Playing song.', os.path.join(pathToDirectory, 'speechPrompts', 'playingSong.m4a')) p = vlc.MediaPlayer(youtubeResponseObject['songPath']) time.sleep(1.5) #startup time p.play() # this checks to see if the user is happy with the song, only if in select edition if autoDownload == False and speechRecogOn == False: continueToSaveOrNot = input( "Hit enter if this sounds right. To try another song -- enter (no): " ) if continueToSaveOrNot == 'no': print('Returning to beginning.') p.stop() return run_download(microPhone=microPhone, recognizer=recognizer, iTunesInstalled=iTunesInstalled, searchFor=searchFor, autoDownload=autoDownload, pathToDirectory=pathToDirectory, iTunesPaths=iTunesPaths, speechRecogOn=speechRecogOn, debugMode=debugMode, trackProperties=trackProperties) # parseItunesSearchApi() throws None return type if the user selects no properties if trackProperties != None: properSongName = iTunesSearch.mp3ID3Tagger( mp3Path=youtubeResponseObject['songPath'], dictionaryOfTags=trackProperties) else: print('Skipping tagging process (No itunes properties selected)') if iTunesInstalled == True: # autoDownload check if autoDownload == False: userInput = input( "Type 's' to save to itunes, anything else to save locally to 'dump' folder. " ) p.stop() elif speechRecogOn == True and autoDownload == True: # speech recog check for save action = '' print(GlobalVariables.PLAYING_STRING_COMMANDS_DEFAULT ) # provide commands while action != 'next': # used this block again below. Should be its own function.. but am too right now. action = jukebox.wait_until_end( player=p, prompt='', file_index=0, index_diff=1, mic=microPhone, r=recognizer, speechRecogOn=speechRecogOn, command_string=GlobalVariables. PLAYING_STRING_COMMANDS_DEFAULT) if action == GlobalVariables.player_stop: break p.play() p.stop() save_or_not = SpeechAnalysis.main( microPhone, recognizer, talking=True, OS=sys.platform, string_to_say="Should I save to iTunes?", file_to_play=os.path.join(pathToDirectory, 'speechPrompts', 'shouldSaveToItunes.m4a'), pathToDirectory=pathToDirectory, expected=['yes', 'no'], phrase_time_limit=4) if 'yes' in save_or_not: userInput = 's' computer.speak( sys.platform, 'Saving to Itunes.', os.path.join(pathToDirectory, 'speechPrompts', 'savingiTunes.m4a')) else: userInput = '' computer.speak( sys.platform, 'Saving Locally', os.path.join(pathToDirectory, 'speechPrompts', 'savingLocal.m4a')) else: print("Saving to iTunes.. whether you like it or not.") userInput = 's' p.stop() if userInput == 's': formattedSongName = formatFileName( pathToFile=youtubeResponseObject['songPath'], sliceKey=".mp3", stringToAdd="_complt") shutil.move(formattedSongName, iTunesPaths['autoAdd']) print("Moved your file to iTunes.") else: print("Saved your file locally.") p.stop() formattedSongName = formatFileName( pathToFile=youtubeResponseObject['songPath'], sliceKey=".mp3", stringToAdd="_complt") return else: # autoDownload check if autoDownload == False: input("Type anything to stop playing.") elif speechRecogOn == True and autoDownload == True: print(GlobalVariables.PLAYING_STRING_COMMANDS_DEFAULT ) # provide commands action = '' while action != 'next': # wait until user ends song. 'next is returned from wait_until_end upon completion.' action = jukebox.wait_until_end( player=p, prompt='', file_index=0, index_diff=1, mic=microPhone, r=recognizer, speechRecogOn=speechRecogOn, command_string=GlobalVariables. PLAYING_STRING_COMMANDS_DEFAULT) if action == GlobalVariables.player_stop: break p.play() computer.speak( sys.platform, 'Saving Locally', os.path.join(pathToDirectory, 'speechPrompts', 'savingLocal.m4a')) else: print("Saving locally. Whether you like it or not.") p.stop() formattedSongName = formatFileName( pathToFile=youtubeResponseObject['songPath'], sliceKey=".mp3", stringToAdd="_complt") return if youtubeResponseObject['error'] == 'youMP3fail': print("YoutubeMp3 failed too many times. quitting to last menu.") return
def __init__(self, api_key): self.youtube = Youtube(api_key) return
class YoutubeDownloader: def __init__(self, api_key): self.youtube = Youtube(api_key) return def download(self, video_id, save_path, filename): video_url = self.youtube.get_video_url(video_id) downloader = Downloader(video_url) downloader.register_on_complete_callback(self.download_complete_action) downloader.register_on_progress_callback( self.download_on_progress_action) stream = downloader.streams.filter(progressive=True, file_extension='mp4') \ .order_by('resolution').desc().first() stream.download(output_path=save_path, filename=filename) return stream def download_queue(self, queue): while not queue.empty(): download_info = queue.get() try: self.download(download_info['video_id'], download_info['save_path'], download_info['filename']) except: queue.put(download_info) time.sleep(10) queue.task_done() def download_channel(self, channel_id, number_video, save_path, num_threads=2): videos = self.youtube.get_chanel_video(channel_id, number_video) queue = Queue(number_video) for video in videos: download_info = { "video_id": video['id']['videoId'], "save_path": save_path, "filename": video['snippet']['title'] } queue.put(download_info) for i in range(num_threads): worker = Thread(name='', target=self.download_queue, args=(queue, )) worker.setDaemon(True) worker.start() queue.join() def download_playlist(self, playlist_id, save_path, number_video, num_threads=3): videos = self.youtube.get_playlist_video(playlist_id, number_video) queue = Queue(number_video) for video in videos: download_info = { "video_id": video['id']['videoId'], "save_path": save_path, "filename": video['snippet']['title'] } queue.put(download_info) for i in range(num_threads): worker = Thread(name='', target=self.download_queue, args=(queue, )) worker.setDaemon(True) worker.start() queue.join() def download_complete_action(self, stream, file_handle): print(' download completd') def download_on_progress_action(self, stream, chunk, file_handle, bytes_remaining): print('.')
def get(self): app = Youtube(storage_file = "../oauth2.json", client_secrets_file = "../desktop_app.json") self.finish(app.get_subscriptions())
def get(self): category = self.get_argument("category", None) app = Youtube(storage_file = "../oauth2.json", client_secrets_file = "../desktop_app.json") new_uploads = app.get_uploads_from_category(category = category) self.finish({"new_uploads": new_uploads})
from Youtube import Youtube if __name__ == '__main__': tubeyou = Youtube.from_token('token.pickle')