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.

360 lines
13 KiB

  1. # imports {{{ #
  2. import requests
  3. import math
  4. import pprint
  5. from .models import Artist, User, Track, AudioFeatures
  6. # }}} imports #
  7. # parse_library {{{ #
  8. def parse_library(headers, tracks, library_stats, user):
  9. """Scans user's library for certain number of tracks to update library_stats with.
  10. :headers: For API call.
  11. :tracks: Number of tracks to get from user's library.
  12. :library_stats: Dictionary containing the data mined from user's library
  13. :user: a User object representing the user whose library we are parsing
  14. :returns: None
  15. """
  16. # TODO: implement importing entire library with 0 as tracks param
  17. # number of tracks to get with each call
  18. limit = 5
  19. # keeps track of point to get songs from
  20. offset = 0
  21. payload = {'limit': str(limit)}
  22. # use two separate variables to track, because the average popularity also requires num_samples
  23. num_samples = 0 # number of actual track samples
  24. feature_data_points = 0 # number of feature data analyses (some tracks do not have analyses available)
  25. # iterate until hit requested num of tracks
  26. for _ in range(0, tracks, limit):
  27. payload['offset'] = str(offset)
  28. # get current set of tracks
  29. saved_tracks_response = requests.get('https://api.spotify.com/v1/me/tracks', headers=headers, params=payload).json()
  30. # TODO: refactor the for loop body into helper function
  31. # iterate through each track
  32. for track_dict in saved_tracks_response['items']:
  33. num_samples += 1
  34. # update artist info before track so that Track object can reference
  35. # Artist object
  36. track_artists = []
  37. for artist_dict in track_dict['track']['artists']:
  38. increase_artist_count(headers, artist_dict['name'],
  39. artist_dict['id'], library_stats)
  40. track_artists.append(Artist.objects.get_or_create(
  41. artist_id=artist_dict['id'],
  42. name=artist_dict['name'],
  43. )[0])
  44. save_track_obj(track_dict['track'], track_artists, user)
  45. get_track_info(track_dict['track'], library_stats, num_samples)
  46. audio_features_dict = get_audio_features(headers, track_dict['track']['id'])
  47. if len(audio_features_dict) != 0:
  48. # Track the number of audio analyses for calculating
  49. # audio feature averages and standard deviations on the fly
  50. feature_data_points += 1
  51. for feature, feature_data in audio_features_dict.items():
  52. update_audio_feature_stats(feature, feature_data,
  53. feature_data_points, library_stats)
  54. # calculates num_songs with offset + songs retrieved
  55. library_stats['num_songs'] = offset + len(saved_tracks_response['items'])
  56. offset += limit
  57. calculate_genres_from_artists(headers, library_stats)
  58. # pprint.pprint(library_stats)
  59. # }}} parse_library #
  60. def save_track_obj(track_dict, artists, user):
  61. """Make an entry in the database for this track if it doesn't exist already.
  62. :track_dict: TODO
  63. :artists: artists of the song, passed in as a list of Artist objects.
  64. :user: TODO
  65. :returns: None
  66. """
  67. if len(Track.objects.filter(track_id__exact=track_dict['id'])) == 0:
  68. new_track = Track.objects.create(
  69. track_id=track_dict['id'],
  70. year=track_dict['album']['release_date'].split('-')[0],
  71. popularity=int(track_dict['popularity']),
  72. runtime=int(float(track_dict['duration_ms']) / 1000),
  73. name=track_dict['name'],
  74. )
  75. # print("pop/run: ", new_track.popularity, new_track.runtime)
  76. # have to add artists and user after saving object since track needs to
  77. # have ID before filling in m2m field
  78. for artist in artists:
  79. new_track.artists.add(artist)
  80. new_track.users.add(user)
  81. new_track.save()
  82. # get_audio_features {{{ #
  83. def get_audio_features(headers, track_id):
  84. """Returns the audio features of a soundtrack
  85. Args:
  86. headers: headers containing the API token
  87. track_id: the id of the soundtrack, needed to query the Spotify API
  88. Returns:
  89. A dictionary with the features as its keys, if audio feature data is missing for the track,
  90. an empty dictionary is returned.
  91. """
  92. response = requests.get("https://api.spotify.com/v1/audio-features/{}".format(track_id), headers = headers).json()
  93. if 'error' in response:
  94. return {}
  95. features_dict = {}
  96. # Data that we don't need
  97. useless_keys = [
  98. "key", "mode", "type", "liveness", "id", "uri", "track_href", "analysis_url", "time_signature",
  99. ]
  100. for key, val in response.items():
  101. if key not in useless_keys:
  102. features_dict[key] = val
  103. return features_dict
  104. # }}} get_audio_features #
  105. # update_std_dev {{{ #
  106. def update_std_dev(cur_mean, cur_std_dev, new_data_point, sample_size):
  107. """Calculates the standard deviation for a sample without storing all data points
  108. Args:
  109. cur_mean: the current mean for N = (sample_size - 1)
  110. cur_std_dev: the current standard deviation for N = (sample_size - 1)
  111. new_data_point: a new data point
  112. sample_size: sample size including the new data point
  113. Returns:
  114. (new_mean, new_std_dev)
  115. """
  116. # This is an implementation of Welford's method
  117. # http://jonisalonen.com/2013/deriving-welfords-method-for-computing-variance/
  118. new_mean = ((sample_size - 1) * cur_mean + new_data_point) / sample_size
  119. delta_variance = (new_data_point - new_mean) * (new_data_point - cur_mean)
  120. new_std_dev = math.sqrt(
  121. (math.pow(cur_std_dev, 2) * (sample_size - 2) + delta_variance) / (
  122. sample_size - 1
  123. ))
  124. return new_mean, new_std_dev
  125. # }}} update_std_dev #
  126. # update_audio_feature_stats {{{ #
  127. def update_audio_feature_stats(feature, new_data_point, sample_size, library_stats):
  128. """Updates the audio feature statistics in library_stats
  129. Args:
  130. feature: the audio feature to be updated (string)
  131. new_data_point: new data to update the stats with
  132. sample_size: sample size including the new data point
  133. library_stats Dictionary containing the data mined from user's Spotify library
  134. Returns:
  135. None
  136. """
  137. # first time the feature is considered
  138. if sample_size < 2:
  139. library_stats['audio_features'][feature] = {
  140. "average": new_data_point,
  141. "std_dev": 0,
  142. }
  143. else:
  144. cur_mean = library_stats['audio_features'][feature]['average']
  145. cur_std_dev = library_stats['audio_features'][feature]['std_dev']
  146. new_mean, new_std_dev = update_std_dev(cur_mean, cur_std_dev, new_data_point, sample_size)
  147. library_stats['audio_features'][feature] = {
  148. "average": new_mean,
  149. "std_dev": new_std_dev
  150. }
  151. # }}} update_audio_feature_stats #
  152. # increase_nested_key {{{ #
  153. def increase_nested_key(top_key, nested_key, library_stats, amount=1):
  154. """Increases count for the value of library_stats[top_key][nested_key]. Checks if nested_key exists already and takes
  155. appropriate action.
  156. :top_key: First key of library_stats.
  157. :nested_key: Key in top_key's dict for which we want to increase value of.
  158. :library_stats: Dictionary containing the data mined from user's Spotify library
  159. :returns: None
  160. """
  161. if nested_key not in library_stats[top_key]:
  162. library_stats[top_key][nested_key] = amount
  163. else:
  164. library_stats[top_key][nested_key] += amount
  165. # }}} increase_nested_key #
  166. # increase_artist_count {{{ #
  167. def increase_artist_count(headers, artist_name, artist_id, library_stats):
  168. """Increases count for artist in library_stats and stores the artist_id.
  169. :headers: For making the API call.
  170. :artist_name: Artist to increase count for.
  171. :artist_id: The Spotify ID for the artist.
  172. :library_stats: Dictionary containing the data mined from user's Spotify library
  173. :returns: None
  174. """
  175. if artist_name not in library_stats['artists']:
  176. library_stats['artists'][artist_name] = {}
  177. library_stats['artists'][artist_name]['count'] = 1
  178. library_stats['artists'][artist_name]['id'] = artist_id
  179. else:
  180. library_stats['artists'][artist_name]['count'] += 1
  181. # }}} increase_artist_count #
  182. # update_popularity_stats {{{ #
  183. def update_popularity_stats(new_data_point, library_stats, sample_size):
  184. """Updates the popularity statistics in library_stats
  185. Args:
  186. new_data_point: new data to update the popularity stats with
  187. library_stats: Dictionary containing data mined from user's Spotify library
  188. sample_size: The sample size including the new data
  189. Returns:
  190. None
  191. """
  192. if sample_size < 2:
  193. library_stats['popularity'] = {
  194. "average": new_data_point,
  195. "std_dev": 0,
  196. }
  197. else :
  198. cur_mean_popularity = library_stats['popularity']['average']
  199. cur_popularity_stdev = library_stats['popularity']['std_dev']
  200. new_mean, new_std_dev = update_std_dev(
  201. cur_mean_popularity, cur_popularity_stdev, new_data_point, sample_size)
  202. library_stats['popularity'] = {
  203. "average": new_mean,
  204. "std_dev": new_std_dev,
  205. }
  206. # }}} update_popularity_stats #
  207. # get_track_info {{{ #
  208. def get_track_info(track_dict, library_stats, sample_size):
  209. """Get all the info from the track_dict directly returned by the API call in parse_library.
  210. :track_dict: Dict returned from the API call containing the track info.
  211. :library_stats: Dictionary containing the data mined from user's Spotify library
  212. :sample_size: The sample size so far including this track
  213. :returns: None
  214. """
  215. # popularity
  216. update_popularity_stats(track_dict['popularity'], library_stats, sample_size)
  217. # year
  218. year_released = track_dict['album']['release_date'].split('-')[0]
  219. increase_nested_key('year_released', year_released, library_stats)
  220. # runtime
  221. library_stats['total_runtime'] += float(track_dict['duration_ms']) / (1000 * 60)
  222. # }}} get_track_info #
  223. # calculate_genres_from_artists {{{ #
  224. def calculate_genres_from_artists(headers, library_stats):
  225. """Tallies up genre counts based on artists in library_stats.
  226. :headers: For making the API call.
  227. :library_stats: Dictionary containing the data mined from user's Spotify library
  228. :returns: None
  229. """
  230. for artist_entry in library_stats['artists'].values():
  231. artist_response = requests.get('https://api.spotify.com/v1/artists/' + artist_entry['id'], headers=headers).json()
  232. # increase each genre count by artist count
  233. for genre in artist_response['genres']:
  234. increase_nested_key('genres', genre, library_stats, artist_entry['count'])
  235. # update genre for artist in database with top genre
  236. Artist.objects.filter(artist_id=artist_entry['id']).update(genre=artist_response['genres'][0])
  237. # }}} calculate_genres_from_artists #
  238. # process_library_stats {{{ #
  239. def process_library_stats(library_stats):
  240. """Processes library_stats into format more suitable for D3 consumption
  241. Args:
  242. library_stats: Dictionary containing the data mined from user's Spotify library
  243. Returns:
  244. A new dictionary that contains the data in library_stats, in a format more suitable for D3 consumption
  245. """
  246. processed_library_stats = {}
  247. for key in library_stats:
  248. if key == 'artists' or key == 'genres' or key == 'year_released':
  249. for inner_key in library_stats[key]:
  250. if key not in processed_library_stats:
  251. processed_library_stats[key] = []
  252. processed_item_key = '' # identifier key for each dict in the list
  253. count = 0
  254. if 'artist' in key:
  255. processed_item_key = 'name'
  256. count = library_stats[key][inner_key]['count']
  257. elif 'genre' in key:
  258. processed_item_key = 'genre'
  259. count = library_stats[key][inner_key]
  260. else:
  261. processed_item_key = 'year'
  262. count = library_stats[key][inner_key]
  263. processed_library_stats[key].append({
  264. processed_item_key: inner_key,
  265. "count": count
  266. })
  267. elif key == 'audio_features':
  268. for audio_feature in library_stats[key]:
  269. if 'audio_features' not in processed_library_stats:
  270. processed_library_stats['audio_features'] = []
  271. processed_library_stats['audio_features'].append({
  272. 'feature': audio_feature,
  273. 'average': library_stats[key][audio_feature]['average'],
  274. 'std_dev': library_stats[key][audio_feature]['std_dev']
  275. })
  276. # TODO: Not sure about final form for 'popularity'
  277. # elif key == 'popularity':
  278. # processed_library_stats[key] = []
  279. # processed_library_stats[key].append({
  280. # })
  281. elif key == 'num_songs' or key == 'total_runtime' or key == 'popularity':
  282. processed_library_stats[key] = library_stats[key]
  283. return processed_library_stats
  284. # }}} process_library_stats #