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.

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