From bbc713e72953ea290bfbf8547d8389d6aedd6005 Mon Sep 17 00:00:00 2001 From: Chris Shyi Date: Sun, 20 May 2018 15:55:59 -0400 Subject: [PATCH] Implement audio feature helper functions Implemented helper functions for updating audio feature statistics. --- spotifyvis/views.py | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/spotifyvis/views.py b/spotifyvis/views.py index 8dd57e9..895e040 100644 --- a/spotifyvis/views.py +++ b/spotifyvis/views.py @@ -120,20 +120,17 @@ def user_data(request): -def get_features(track_id, token): - """Returns the features of a soundtrack +def get_audio_features(track_id, headers): + """Returns the audio features of a soundtrack Args: track_id: the id of the soundtrack, needed to query the Spotify API - token: an access token for the Spotify API + headers: headers containing the API token Returns: A dictionary with the features as its keys """ - - headers = { - 'Authorization': token, - } + response = requests.get("https://api.spotify.com/v1/audio-features/{}".format(track_id), headers = headers).json() features_dict = {} @@ -163,4 +160,31 @@ def update_std_dev(cur_mean, new_data_point, sample_size): # http://jonisalonen.com/2013/deriving-welfords-method-for-computing-variance/ new_mean = ((sample_size - 1) * cur_mean + new_data_point) / sample_size std_dev = (new_data_point - new_mean) * (new_data_point - cur_mean) - return new_mean, std_dev \ No newline at end of file + return new_mean, std_dev + + +def update_audio_feature_stats(feature, new_data_point, sample_size): + """Updates the audio feature statistics in library_stats + + Args: + feature: the audio feature to be updated (string) + new_data_point: new data to update the stats with + sample_size: sample size including the new data point + + Returns: + None + """ + # first time the feature is considered + if sample_size < 2: + library_stats['audio_features'][feature] = { + "average": new_data_point, + "std_dev": 0, + } + + else: + current_mean = library_stats['audio_features'][feature]['average'] + updated_mean, std_dev = update_std_dev(current_mean, new_data_point, sample_size) + + library_stats['audio_features'][feature]['average'] = updated_mean + library_stats['audio_features'][feature]['std_dev'] = std_dev +