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.

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