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.

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