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.

385 lines
14 KiB

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