Esempio n. 1
0
def getSong(emotion):
    access_token = ""

    token_info = sp_oauth.get_cached_token()

    if token_info:
        print("Found cached token!")
        access_token = token_info['access_token']
    else:
        print("no available token, errors abound")

    spotifyObj = spotipy.Spotify(token_info['access_token'])
    spClient = SpotifyClient(token_info['access_token'], SPOTIPY_CLIENT_ID)

    nbrOfTracks = 3

    lastPlayedTracks = spClient.get_last_played_tracks(nbrOfTracks)

    print(f"the {nbrOfTracks} last tracks you listened to were: ")
    for index, track in enumerate(lastPlayedTracks):
        print(f"{index+1}- {track}")

    seed = emotionCompiler(emotion)

    seedSongs = lastPlayedTracks

    recommendedTracks = spClient.get_recommended_tracks(seed, seedSongs)
    print("here are the recomended tracks")

    for index, track in enumerate(recommendedTracks):
        print(f"{index+1}- {track}")

    start_playback(track, spotifyObj)
Esempio n. 2
0
def main():
    my_client = SpotifyClient(client_id=SPOTIFY_CLIENT_ID,
                              client_secret=SPOTIFY_CLIENT_SECRET,
                              redirect_uri="https://www.google.com/",
                              scope="user-library-read")

    sample = my_client.get_saved_tracks().json()
    # print(json.dumps(sample, indent=4, sort_keys=True))

    songs_list = sample["items"]

    for song_details in songs_list:
        # print(song_details.keys())
        # print(json.dumps(song_details, indent=4, sort_keys=True))
        print("-", song_details["track"]["name"], "by:",
              song_details["track"]["artists"][0]["name"])
Esempio n. 3
0
def connect_spotify(credentials):
    spotify = SpotifyClient(client_id=credentials.get('spotify', 'client_id'),
                            client_secret=credentials.get('spotify', 'client_secret'),
                            username=credentials.get('spotify', 'username'),
                            password=credentials.get('spotify', 'password'),
                            callback=credentials.get('spotify', 'callback_url'),
                            scope=credentials.get('spotify', 'scope'))
    return spotify
def main():
    spotify_client = SpotifyClient(os.getenv("SPOTIFY_AUTHORIZATION_TOKEN"),
                                   os.getenv("SPOTIFY_USER_ID"))

    # get last played tracks
    num_tracks_to_visualize = int(input("How many tracks would you like to visualize? "))
    last_played_tracks = spotify_client.get_last_played_tracks(num_tracks_to_visualize)

    print(f"\nHere are the last {num_tracks_to_visualize} tracks you listened to on Spotify:")
    for index, track in enumerate(last_played_tracks):
        print(f"{index+1}- {track}")

    # choose which tracks to use as a seed to generate a playlist
    indexes = input("\nEnter a list of up to 5 tracks you'd like to use as seeds. Use indexes separated by a space: ")
    indexes = indexes.split()
    seed_tracks = [last_played_tracks[int(index)-1] for index in indexes]

    # get recommended tracks based off seed tracks
    recommended_tracks = spotify_client.get_track_recommendations(seed_tracks)
    print("\nHere are the recommended tracks which will be included in your new playlist:")
    for index, track in enumerate(recommended_tracks):
        print(f"{index+1}- {track}")

    # get playlist name from user and create playlist
    playlist_name = input("\nWhat's the playlist name? ")
    playlist = spotify_client.create_playlist(playlist_name)
    print(f"\nPlaylist '{playlist.name}' was created successfully.")

    # populate playlist with recommended tracks
    spotify_client.populate_playlist(playlist, recommended_tracks)
    print(f"\nRecommended tracks successfully uploaded to playlist '{playlist.name}'.")
Esempio n. 5
0
 def __init__(self):
     self.source_client = None
     self.destination_client = None
     self.services = [{
         "name": "Google Play Music",
         "client": GoogleClient()
     }, {
         "name": "Spotify",
         "client": SpotifyClient()
     }]
Esempio n. 6
0
    def test_spotify_client(self):

        # Initialize client
        from spotifyclient import SpotifyClient
        spotify_client = SpotifyClient()
        assert (spotify_client)

        # Authenticate
        assert (spotify_client.authenticate())

        # Search for test tracks (one that exists and one that doesn't)
        track_list = [{
            "artist": "Broods",
            "track": "Bridges",
            "album": "Evergreen"
        }, {
            "artist": "Matthew Haldeman",
            "track": "PCP",
            "album": "The Matthew Haldeman Experience"
        }]
        result = spotify_client.search_for_tracklist(track_list)
        assert (len(result['found']) == len(result['not_found']) == 1)

        # Create a test playlist
        playlist_name = "Test Playlist"
        playlist_id = spotify_client.create_playlist(
            playlist_name=playlist_name)

        # Add test tracks
        track_list = ["2Ud3deeqLAG988pfW0Kwcl", "1285n66OGGUB3Bnh6c18nS"]
        spotify_client.add_tracks_to_playlist(playlist_id=playlist_id,
                                              track_list=track_list)
        # Check to make sure the tracks were added
        results = spotify_client.get_playlist_tracks(
            playlist_id=playlist_id, user_id=spotify_client.user_id)
        assert (results['name']) == playlist_name
        assert (len(results['tracks']) == len(track_list))

        # Unfollow playlist (so I don't clutter up my spotify with bullshit "Test Playlists")
        result = spotify_client._delete_playlist(playlist_id=playlist_id)
        assert (result)
Esempio n. 7
0
def main(emotion):
    getSettings = settings.getSettings()
    SPOTIFY_USER_ID = getSettings[1].replace('\n', '')
    SPOTIFY_AUTHORIZATION_TOKEN = getSettings[2].replace('\n', '')

    happy_playlist_id = "1h90L3LP8kAJ7KGjCV2Xfd"
    sad_playlist_id = "37i9dQZF1DX7qK8ma5wgG1"
    neutral_playlist_id = "4PFwZ4h1LMAOwdwXqvSYHd"
    angry_playlist_id = "3uaOn723EyF8eF7GhtJkyD"
    x = 0

    spotify_client = SpotifyClient(SPOTIFY_AUTHORIZATION_TOKEN,
                                   SPOTIFY_USER_ID)

    if emotion == 'Happy':
        playlist_list = spotify_client.get_playlist()
        playlist_id = happy_playlist_id
    elif emotion == 'Sad':
        playlist_list = spotify_client.get_playlist()
        playlist_id = sad_playlist_id
    elif emotion == 'Neutral':
        playlist_list = spotify_client.get_playlist()
        playlist_id = neutral_playlist_id
    elif emotion == 'Angry':
        playlist_list = spotify_client.get_playlist()
        playlist_id = angry_playlist_id
    else:
        print("Invalid emotion entered")
        quit()

    # spotify_client = SpotifyClient(os.getenv("SPOTIFY_AUTHORIZATION_TOKEN"),
    #                                os.getenv("SPOTIFY_USER_ID"))

    playlist_musics = spotify_client.get_playlist_songs(playlist_id)
    # for index, track in enumerate(playlist_musics):
    # print(f"{index+1} - {track}")

    if emotion == 'Happy':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 100))
            x += 1
    elif emotion == 'Sad':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 60))
            x += 1
    elif emotion == 'Neutral':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 85))
            x += 1
    elif emotion == 'Angry':
        indexes = []
        while x < 5:
            indexes.insert(x, random.randint(0, 100))
            x += 1

    seed_tracks = [playlist_musics[int(index) - 1] for index in indexes]

    recommended_tracks = spotify_client.get_track_recommendations(seed_tracks)

    if emotion == 'Happy':
        playlist_name = "Happy Playlist"
    elif emotion == 'Sad':
        playlist_name = "Sad Playlist"
    elif emotion == 'Neutral':
        playlist_name = "Neutral Playlist"
    elif emotion == 'Angry':
        playlist_name = "Angry Playlist"

    playlist = spotify_client.create_playlist(playlist_name)
    print(f"Playlist '{playlist.name}' was created successfully.")

    spotify_client.populate_playlist(playlist, recommended_tracks)
    print(
        f"Recommended tracks successfully uploaded to playlist '{playlist.name}'"
    )
Esempio n. 8
0
def main():
    #token = secretCredentials.GetAccessToken()

    #spotify_client = SpotifyClient(secretCredentials.GetAccessToken(),
    #                               os.getenv("SPOTIFY_USER_ID"))

    spotify_client = SpotifyClient(os.getenv("SPOTIFY_AUTHORIZATION_TOKEN"),
                                   os.getenv("SPOTIFY_USER_ID"))

    # get tracks to choose seeds
    option2 = 0
    while option2 != 1 and option2 != 2 and option2 != 3 and option2 != 4:
        option2 = int(input('Choose option to get list of tracks:\n1. Recently Played\n2. Top Tracks (Recent)\n'\
                            '3. Top Tracks (Medium Term)\n4. Top Tracks (All Time)\n\nSelect: '))

    if option2 == 1:
        # get last played tracks
        num_tracks_to_visualise = int(input("How many tracks would you like to visualise? "))
        last_played_tracks = spotify_client.get_last_played_tracks(num_tracks_to_visualise)

        print(f"\nHere are the last {num_tracks_to_visualise} tracks you listened to on Spotify:")
        for index, track in enumerate(last_played_tracks):
            print(f"{index+1}- {track}")

        # choose which tracks to use as a seed to generate a playlist
        indexes = input("\nEnter a list of up to 5 tracks you'd like to use as seeds."
                        "Use indexes separated by a space: ")
        indexes = indexes.split()
        seed_tracks = [last_played_tracks[int(index)-1] for index in indexes]

    else:
        num_tracks_to_visualise = int(input("How many tracks would you like to visualise? "))
        if option2 == 2:
            top_played_tracks = spotify_client.get_top_tracks_short(num_tracks_to_visualise)
        elif option2 == 3:
            top_played_tracks = spotify_client.get_top_tracks_medium(num_tracks_to_visualise)
        else:
            top_played_tracks = spotify_client.get_top_tracks_long(num_tracks_to_visualise)

        print(f"\nHere are the top {num_tracks_to_visualise} tracks you listened to on Spotify:")
        for index, track in enumerate(top_played_tracks):
            print(f"{index + 1}- {track}")

        # choose which tracks to use as a seed to generate a playlist
        indexes = input("\nEnter a list of up to 5 tracks you'd like to use as seeds."
                        "Use indexes separated by a space: ")
        indexes = indexes.split()
        seed_tracks = [top_played_tracks[int(index) - 1] for index in indexes]

    #customize!!
    yesno = ''
    while yesno != 'n' and yesno != 'y':
        yesno = str(input('\nWould you like to filter the recommendations? (Y/N): '))
        yesno = yesno.lower()
        #if yesno == 'y' or yesno == 'n': break

    if yesno == 'n':
        # get recommended tracks based off seed tracks
        recommended_tracks = spotify_client.get_track_recommendations(seed_tracks)
        print("\nHere are the recommended tracks which will be included in your new playlist:")
        for index, track in enumerate(recommended_tracks):
            print(f"{index+1}- {track}")

        # get playlist name from user and create playlist
        playlist_name = input("\nWhat's the playlist name? ")
        playlist = spotify_client.create_playlist(playlist_name)
        print(f"\nPlaylist '{playlist.name}' was created successfully.")

        # playlist cover
        #option3 = ''
        #while option3 != 'y' and option3 != 'n':
        #    option3 = str(input('\nWould you like a custom playlist cover? (Y/N): '))
        #    option3 = option3.lower()
        #if option3 == 'y':
        #    spotify_client.playlist_cover(playlist)

        # populate playlist with recommended tracks
        spotify_client.populate_playlist(playlist, recommended_tracks)
        print(f"\nRecommended tracks successfully uploaded to playlist '{playlist.name}'.")

    elif yesno == 'y':
        option1 = 0
        while option1 != 1 and option1 != 2:
            option1 = int(input('\n1. Presets\n2. Custom (Advanced)\n\nSelect number: '))
            #if option1 == 1 or option1 == 2: break

        if option1 == 1:
            presetselect = spotify_client.choose_presets()

            recommended_tracks2 = spotify_client.get_track_recommendations_presets(seed_tracks, preset=presetselect)
            print("\nHere are the recommended tracks which will be included in your new playlist:")
            for index, track in enumerate(recommended_tracks2):
                print(f"{index + 1}- {track}")

            # get playlist name from user and create playlist
            playlist_name = input("\nWhat's the playlist name? ")
            playlist = spotify_client.create_playlist(playlist_name)
            print(f"\nPlaylist '{playlist.name}' was created successfully.")

            # playlist cover
            # option3 = ''
            # while option3 != 'y' and option3 != 'n':
            #    option3 = str(input('\nWould you like a custom playlist cover? (Y/N): '))
            #    option3 = option3.lower()
            # if option3 == 'y':
            #    spotify_client.playlist_cover(playlist)

            # populate playlist with recommended tracks
            spotify_client.populate_playlist(playlist, recommended_tracks2)
            print(f"\nRecommended tracks successfully uploaded to playlist '{playlist.name}'.")

        elif option1 == 2:
            print('\nEnter Values:')
            bpmtarget = int(input('\nBpm Target: '))
            bpmmin = int(input('Bpm Minimum: '))
            bpmmax = int(input('Bpm Maximum: '))
            acmin = float(input('Acousticness Min. (0-1): '))
            acmax = float(input('Acousticness Max. (0-1): '))
            dancemin = float(input('Danceability Min. (0-1): '))
            dancemax = float(input('Danceability Max. (0-1): '))
            energymin = float(input('Energy Min. (0-1): '))
            energymax = float(input('Energy Max. (0-1): '))
            valenmin = float(input('Valence Min. (0-1): '))
            valenmax = float(input('Valence Max. (0-1): '))

            recommendedtracks3=spotify_client.get_track_recommendations_custom(seed_tracks, bpmtarget=bpmtarget,
                                                                               bpmmin=bpmmin, bpmmax=bpmmax,
                                                                               acmin=acmin, acmax=acmax,
                                                                               dancemin=dancemin, dancemax=dancemax,
                                                                               energymin=energymin, energymax=energymax,
                                                                               valenmin=valenmin, valenmax=valenmax)
            print("\nHere are the recommended tracks which will be included in your new playlist:")
            for index, track in enumerate(recommendedtracks3):
                print(f"{index + 1}- {track}")

            # get playlist name from user and create playlist
            playlist_name = input("\nWhat's the playlist name? ")
            playlist = spotify_client.create_playlist(playlist_name)
            print(f"\nPlaylist '{playlist.name}' was created successfully.")

            # playlist cover
            # option3 = ''
            # while option3 != 'y' and option3 != 'n':
            #    option3 = str(input('\nWould you like a custom playlist cover? (Y/N): '))
            #    option3 = option3.lower()
            # if option3 == 'y':
            #    spotify_client.playlist_cover(playlist)

            # populate playlist with recommended tracks
            spotify_client.populate_playlist(playlist, recommendedtracks3)
            print(f"\nRecommended tracks successfully uploaded to playlist '{playlist.name}'.")