Graphs and tables for your Spotify account.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

289 lines
11 KiB

  1. import requests
  2. import math
  3. import pprint
  4. # parse_library {{{ #
  5. def parse_library(headers, tracks, library_stats):
  6. """Scans user's library for certain number of tracks to update library_stats with.
  7. :headers: For API call.
  8. :tracks: Number of tracks to get from user's library.
  9. :library_stats: Dictionary containing the data mined from user's library
  10. :returns: None
  11. """
  12. # TODO: implement importing entire library with 0 as tracks param
  13. # number of tracks to get with each call
  14. limit = 5
  15. # keeps track of point to get songs from
  16. offset = 0
  17. payload = {'limit': str(limit)}
  18. for _ in range(0, tracks, limit):
  19. payload['offset'] = str(offset)
  20. saved_tracks_response = requests.get('https://api.spotify.com/v1/me/tracks', headers=headers, params=payload).json()
  21. num_samples = offset
  22. for track_dict in saved_tracks_response['items']:
  23. # Track the number of samples for calculating
  24. # audio feature averages and standard deviations on the fly
  25. num_samples += 1
  26. get_track_info(track_dict['track'], library_stats, num_samples)
  27. # get_genre(headers, track_dict['track']['album']['id'])
  28. audio_features_dict = get_audio_features(headers, track_dict['track']['id'])
  29. for feature, feature_data in audio_features_dict.items():
  30. update_audio_feature_stats(feature, feature_data, num_samples, library_stats)
  31. for artist_dict in track_dict['track']['artists']:
  32. increase_artist_count(headers, artist_dict['name'], artist_dict['id'], library_stats)
  33. # calculates num_songs with offset + songs retrieved
  34. library_stats['num_songs'] = offset + len(saved_tracks_response['items'])
  35. offset += limit
  36. calculate_genres_from_artists(headers, library_stats)
  37. pprint.pprint(library_stats)
  38. # }}} parse_library #
  39. def get_audio_features(headers, track_id):
  40. """Returns the audio features of a soundtrack
  41. Args:
  42. headers: headers containing the API token
  43. track_id: the id of the soundtrack, needed to query the Spotify API
  44. Returns:
  45. A dictionary with the features as its keys
  46. """
  47. response = requests.get("https://api.spotify.com/v1/audio-features/{}".format(track_id), headers = headers).json()
  48. features_dict = {}
  49. # Data that we don't need
  50. useless_keys = [
  51. "key", "mode", "type", "liveness", "id", "uri", "track_href", "analysis_url", "time_signature",
  52. ]
  53. for key, val in response.items():
  54. if key not in useless_keys:
  55. features_dict[key] = val
  56. return features_dict
  57. def update_std_dev(cur_mean, cur_std_dev, new_data_point, sample_size):
  58. """Calculates the standard deviation for a sample without storing all data points
  59. Args:
  60. cur_mean: the current mean for N = (sample_size - 1)
  61. cur_std_dev: the current standard deviation for N = (sample_size - 1)
  62. new_data_point: a new data point
  63. sample_size: sample size including the new data point
  64. Returns:
  65. (new_mean, new_std_dev)
  66. """
  67. # This is an implementation of Welford's method
  68. # http://jonisalonen.com/2013/deriving-welfords-method-for-computing-variance/
  69. new_mean = ((sample_size - 1) * cur_mean + new_data_point) / sample_size
  70. delta_variance = (new_data_point - new_mean) * (new_data_point - cur_mean)
  71. new_std_dev = math.sqrt(
  72. (math.pow(cur_std_dev, 2) * (sample_size - 2) + delta_variance) / (
  73. sample_size - 1
  74. ))
  75. return new_mean, new_std_dev
  76. def update_audio_feature_stats(feature, new_data_point, sample_size, library_stats):
  77. """Updates the audio feature statistics in library_stats
  78. Args:
  79. feature: the audio feature to be updated (string)
  80. new_data_point: new data to update the stats with
  81. sample_size: sample size including the new data point
  82. library_stats Dictionary containing the data mined from user's Spotify library
  83. Returns:
  84. None
  85. """
  86. # first time the feature is considered
  87. if sample_size < 2:
  88. library_stats['audio_features'][feature] = {
  89. "average": new_data_point,
  90. "std_dev": 0,
  91. }
  92. else:
  93. cur_mean = library_stats['audio_features'][feature]['average']
  94. cur_std_dev = library_stats['audio_features'][feature]['std_dev']
  95. new_mean, new_std_dev = update_std_dev(cur_mean, cur_std_dev, new_data_point, sample_size)
  96. library_stats['audio_features'][feature] = {
  97. "average": new_mean,
  98. "std_dev": new_std_dev
  99. }
  100. # increase_nested_key {{{ #
  101. def increase_nested_key(top_key, nested_key, library_stats, amount=1):
  102. """Increases count for the value of library_stats[top_key][nested_key]. Checks if nested_key exists already and takes
  103. appropriate action.
  104. :top_key: First key of library_stats.
  105. :nested_key: Key in top_key's dict for which we want to increase value of.
  106. :library_stats: Dictionary containing the data mined from user's Spotify library
  107. :returns: None
  108. """
  109. if nested_key not in library_stats[top_key]:
  110. library_stats[top_key][nested_key] = amount
  111. else:
  112. library_stats[top_key][nested_key] += amount
  113. # }}} increase_nested_key #
  114. # increase_artist_count {{{ #
  115. def increase_artist_count(headers, artist_name, artist_id, library_stats):
  116. """Increases count for artist in library_stats and stores the artist_id.
  117. :headers: For making the API call.
  118. :artist_name: Artist to increase count for.
  119. :artist_id: The Spotify ID for the artist.
  120. :library_stats: Dictionary containing the data mined from user's Spotify library
  121. :returns: None
  122. """
  123. if artist_name not in library_stats['artists']:
  124. library_stats['artists'][artist_name] = {}
  125. library_stats['artists'][artist_name]['count'] = 1
  126. library_stats['artists'][artist_name]['id'] = artist_id
  127. else:
  128. library_stats['artists'][artist_name]['count'] += 1
  129. # }}} increase_artist_count #
  130. def update_popularity_stats(new_data_point, library_stats, sample_size):
  131. """Updates the popularity statistics in library_stats
  132. Args:
  133. new_data_point: new data to update the popularity stats with
  134. library_stats: Dictionary containing data mined from user's Spotify library
  135. sample_size: The sample size including the new data
  136. Returns:
  137. None
  138. """
  139. if sample_size < 2:
  140. library_stats['popularity'] = {
  141. "average": new_data_point,
  142. "std_dev": 0,
  143. }
  144. else :
  145. cur_mean_popularity = library_stats['popularity']['average']
  146. cur_popularity_stdev = library_stats['popularity']['std_dev']
  147. new_mean, new_std_dev = update_std_dev(
  148. cur_mean_popularity, cur_popularity_stdev, new_data_point, sample_size)
  149. library_stats['popularity'] = {
  150. "average": new_mean,
  151. "std_dev": new_std_dev,
  152. }
  153. # get_track_info {{{ #
  154. def get_track_info(track_dict, library_stats, sample_size):
  155. """Get all the info from the track_dict directly returned by the API call in parse_library.
  156. :track_dict: Dict returned from the API call containing the track info.
  157. :library_stats: Dictionary containing the data mined from user's Spotify library
  158. :sample_size: The sample size so far including this track
  159. :returns: None
  160. """
  161. # popularity
  162. update_popularity_stats(track_dict['popularity'], library_stats, sample_size)
  163. # year
  164. year_released = track_dict['album']['release_date'].split('-')[0]
  165. increase_nested_key('year_released', year_released, library_stats)
  166. # artist
  167. # artist_names = [artist['name'] for artist in track_dict['artists']]
  168. # for artist_name in artist_names:
  169. # increase_nested_key('artists', artist_name)
  170. # runtime
  171. library_stats['total_runtime'] += float(track_dict['duration_ms']) / (1000 * 60)
  172. # }}} get_track_info #
  173. # calculate_genres_from_artists {{{ #
  174. def calculate_genres_from_artists(headers, library_stats):
  175. """Tallies up genre counts based on artists in library_stats.
  176. :headers: For making the API call.
  177. :library_stats: Dictionary containing the data mined from user's Spotify library
  178. :returns: None
  179. """
  180. for artist_entry in library_stats['artists'].values():
  181. artist_response = requests.get('https://api.spotify.com/v1/artists/' + artist_entry['id'], headers=headers).json()
  182. # increase each genre count by artist count
  183. for genre in artist_response['genres']:
  184. increase_nested_key('genres', genre, library_stats, artist_entry['count'])
  185. # }}} calculate_genres_from_artists #
  186. def process_library_stats(library_stats):
  187. """Processes library_stats into format more suitable for D3 consumption
  188. Args:
  189. library_stats: Dictionary containing the data mined from user's Spotify library
  190. Returns:
  191. A new dictionary that contains the data in library_stats, in a format more suitable for D3 consumption
  192. """
  193. processed_library_stats = {}
  194. for key in library_stats:
  195. if key == 'artists' or key == 'genres' or key == 'year_released':
  196. for inner_key in library_stats[key]:
  197. if key not in processed_library_stats:
  198. processed_library_stats[key] = []
  199. processed_item_key = '' # identifier key for each dict in the list
  200. count = 0
  201. if 'artist' in key:
  202. processed_item_key = 'name'
  203. count = library_stats[key][inner_key]['count']
  204. elif 'genre' in key:
  205. processed_item_key = 'genre'
  206. count = library_stats[key][inner_key]
  207. else:
  208. processed_item_key = 'year'
  209. count = library_stats[key][inner_key]
  210. processed_library_stats[key].append({
  211. processed_item_key: inner_key,
  212. "count": count
  213. })
  214. elif key == 'audio_features':
  215. for audio_feature in library_stats[key]:
  216. if 'audio_features' not in processed_library_stats:
  217. processed_library_stats['audio_features'] = []
  218. processed_library_stats['audio_features'].append({
  219. 'feature': audio_feature,
  220. 'average': library_stats[key][audio_feature]['average'],
  221. 'std_dev': library_stats[key][audio_feature]['std_dev']
  222. })
  223. # TODO: Not sure about final form for 'popularity'
  224. # elif key == 'popularity':
  225. # processed_library_stats[key] = []
  226. # processed_library_stats[key].append({
  227. # })
  228. elif key == 'num_songs' or key == 'total_runtime' or key == 'popularity':
  229. processed_library_stats[key] = library_stats[key]
  230. return processed_library_stats