Esempio n. 1
0
def get_audio_features(sp: spotipy.client.Spotify, track_uri: str):
    track_uri = sp._get_id("track", track_uri)

    os.makedirs("audio_features", exist_ok=True)
    filename = f"audio_features/{track_uri}"
    try:
        with open(filename, "r") as f:
            contents = f.read()
            data = json.loads(contents)
    except FileNotFoundError:
        features = sp.audio_features([track_uri])
        data = features[0]
        with open(filename, "w") as f:
            contents = json.dumps(data, indent=4)
            f.write(contents)
    return data
Esempio n. 2
0
def get_audio_features(spotify: spotipy.client.Spotify, track_ids: list) -> list:
    """
    This function gets the following features of a spotify song, hundred songs at a time:
    ["acousticness", "danceability", "durationms", "energy", "instrumentalness", "key", "liveness", "loudness", "mode", "speechiness"\
        , "tempo", "timesignature", "valence"]
    Getting more than 100 songs will result in a bad request error
    Parameters Required: Authenticated Spotify Client, and list of song IDs
    Return Data: List of dictionary containing song features
    """
    # Getting features
    featurelst = []
    count = 0
    while count <= len(track_ids):
        # Get 100 songs' features at a time. Getting any more will result in bad result error
        featurelst.extend(spotify.audio_features(track_ids[count : count + 100]))
        count = count + 100
    return featurelst
Esempio n. 3
0
def get_features_for_playlist(sp: spotipy.client.Spotify,
                              uri: str) -> pd.DataFrame:
    """
    Extract features from each track in a playlist

    :param sp: spotify client object
    :param uri: playlist uri
    :return: playlist with audio features of each song
    """
    # Get all track metadata from given playlist
    playlist_name, names, artists, uris = get_playlist_info(sp, uri)

    # Set column names and empty dataframe
    column_names = [
        'name', 'artist', 'track_URI', 'acousticness', 'danceability',
        'energy', 'instrumentalness', 'liveness', 'loudness', 'speechiness',
        'tempo', 'valence', 'playlist'
    ]
    df = pd.DataFrame(columns=column_names)

    # Iterate through each track to get audio features and save data into dataframe
    for name, artist, track_uri in zip(names, artists, uris):

        # Access audio features for given track URI via spotipy
        audio_features = sp.audio_features(track_uri)

        # Get relevant audio features
        feature_subset = [
            audio_features[0][col] for col in column_names
            if col not in ["name", "artist", "track_URI", "playlist"]
        ]

        # Compose a row of the dataframe by flattening the list of audio features
        row = [name, artist, track_uri, *feature_subset, playlist_name]
        df.loc[len(df.index)] = row

    return df