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.

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