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.

447 lines
16 KiB

  1. # imports {{{ #
  2. import requests
  3. import math
  4. import pprint
  5. from .models import *
  6. from django.db.models import Count, Q, F
  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 = 50
  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. if artist_created:
  42. tally_artist_genres(headers, artist_dict['id'])
  43. # update_artist_genre(headers, artist_obj)
  44. # get_or_create() returns a tuple (obj, created)
  45. track_artists.append(artist_obj)
  46. top_genre = get_top_genre(headers,
  47. track_dict['track']['artists'][0]['id'])
  48. track_obj, track_created = save_track_obj(track_dict['track'],
  49. track_artists, top_genre, user)
  50. # if a new track is not created, the associated audio feature does not need to be created again
  51. # if track_created:
  52. save_audio_features(headers, track_dict['track']['id'], track_obj)
  53. """
  54. TODO: Put this logic in another function
  55. # Audio analysis could be empty if not present in Spotify database
  56. if len(audio_features_dict) != 0:
  57. # Track the number of audio analyses for calculating
  58. # audio feature averages and standard deviations on the fly
  59. feature_data_points += 1
  60. for feature, feature_data in audio_features_dict.items():
  61. update_audio_feature_stats(feature, feature_data,
  62. feature_data_points, library_stats)
  63. """
  64. # calculates num_songs with offset + songs retrieved
  65. offset += limit
  66. # pprint.pprint(library_stats)
  67. # }}} parse_library #
  68. # save_track_obj {{{ #
  69. def save_track_obj(track_dict, artists, top_genre, user):
  70. """Make an entry in the database for this track if it doesn't exist already.
  71. :track_dict: dictionary from the API call containing track information.
  72. :artists: artists of the song, passed in as a list of Artist objects.
  73. :top_genre: top genre associated with this track (see get_top_genre).
  74. :user: User object for which this Track is to be associated with.
  75. :returns: (The created/retrieved Track object, created)
  76. """
  77. track_query = Track.objects.filter(track_id__exact=track_dict['id'])
  78. if len(track_query) != 0:
  79. return track_query[0], False
  80. else:
  81. new_track = Track.objects.create(
  82. track_id=track_dict['id'],
  83. year=track_dict['album']['release_date'].split('-')[0],
  84. popularity=int(track_dict['popularity']),
  85. runtime=int(float(track_dict['duration_ms']) / 1000),
  86. name=track_dict['name'],
  87. # genre=top_genre,
  88. )
  89. # have to add artists and user after saving object since track needs to
  90. # have ID before filling in m2m field
  91. for artist in artists:
  92. new_track.artists.add(artist)
  93. new_track.users.add(user)
  94. new_track.save()
  95. return new_track, True
  96. # }}} save_track_obj #
  97. # get_audio_features {{{ #
  98. def save_audio_features(headers, track_id, track):
  99. """Creates and saves a new AudioFeatures object
  100. Args:
  101. headers: headers containing the API token
  102. track_id: the id of the soundtrack, needed to query the Spotify API
  103. track: Track object to associate with the new AudioFeatures object
  104. """
  105. response = requests.get("https://api.spotify.com/v1/audio-features/{}".format(track_id), headers = headers).json()
  106. if track_id is '5S1IUPueD0xE0vj4zU3nSf':
  107. pprint.pprint(response)
  108. if 'error' in response:
  109. return
  110. # Data that we don't need
  111. useless_keys = [
  112. "key", "mode", "type", "liveness", "id", "uri", "track_href", "analysis_url", "time_signature",
  113. ]
  114. audio_features_entry = AudioFeatures()
  115. audio_features_entry.track = track
  116. for key, val in response.items():
  117. if key not in useless_keys:
  118. setattr(audio_features_entry, key, val)
  119. audio_features_entry.save()
  120. # }}} get_audio_features #
  121. # update_std_dev {{{ #
  122. def update_std_dev(cur_mean, cur_std_dev, new_data_point, sample_size):
  123. """Calculates the standard deviation for a sample without storing all data points
  124. Args:
  125. cur_mean: the current mean for N = (sample_size - 1)
  126. cur_std_dev: the current standard deviation for N = (sample_size - 1)
  127. new_data_point: a new data point
  128. sample_size: sample size including the new data point
  129. Returns:
  130. (new_mean, new_std_dev)
  131. """
  132. # This is an implementation of Welford's method
  133. # http://jonisalonen.com/2013/deriving-welfords-method-for-computing-variance/
  134. new_mean = ((sample_size - 1) * cur_mean + new_data_point) / sample_size
  135. delta_variance = (new_data_point - new_mean) * (new_data_point - cur_mean)
  136. new_std_dev = math.sqrt(
  137. (math.pow(cur_std_dev, 2) * (sample_size - 2) + delta_variance) / (
  138. sample_size - 1
  139. ))
  140. return new_mean, new_std_dev
  141. # }}} update_std_dev #
  142. # update_audio_feature_stats {{{ #
  143. def update_audio_feature_stats(feature, new_data_point, sample_size, library_stats):
  144. """Updates the audio feature statistics in library_stats
  145. Args:
  146. feature: the audio feature to be updated (string)
  147. new_data_point: new data to update the stats with
  148. sample_size: sample size including the new data point
  149. library_stats Dictionary containing the data mined from user's Spotify library
  150. Returns:
  151. None
  152. """
  153. # first time the feature is considered
  154. if sample_size < 2:
  155. library_stats['audio_features'][feature] = {
  156. "average": new_data_point,
  157. "std_dev": 0,
  158. }
  159. else:
  160. cur_mean = library_stats['audio_features'][feature]['average']
  161. cur_std_dev = library_stats['audio_features'][feature]['std_dev']
  162. new_mean, new_std_dev = update_std_dev(cur_mean, cur_std_dev, new_data_point, sample_size)
  163. library_stats['audio_features'][feature] = {
  164. "average": new_mean,
  165. "std_dev": new_std_dev
  166. }
  167. # }}} update_audio_feature_stats #
  168. # increase_nested_key {{{ #
  169. def increase_nested_key(top_key, nested_key, library_stats, amount=1):
  170. """Increases count for the value of library_stats[top_key][nested_key]. Checks if nested_key exists already and takes
  171. appropriate action.
  172. :top_key: First key of library_stats.
  173. :nested_key: Key in top_key's dict for which we want to increase value of.
  174. :library_stats: Dictionary containing the data mined from user's Spotify library
  175. :returns: None
  176. """
  177. if nested_key not in library_stats[top_key]:
  178. library_stats[top_key][nested_key] = amount
  179. else:
  180. library_stats[top_key][nested_key] += amount
  181. # }}} increase_nested_key #
  182. # increase_artist_count {{{ #
  183. def increase_artist_count(headers, artist_name, artist_id, library_stats):
  184. """Increases count for artist in library_stats and stores the artist_id.
  185. :headers: For making the API call.
  186. :artist_name: Artist to increase count for.
  187. :artist_id: The Spotify ID for the artist.
  188. :library_stats: Dictionary containing the data mined from user's Spotify library
  189. :returns: None
  190. """
  191. if artist_name not in library_stats['artists']:
  192. library_stats['artists'][artist_name] = {}
  193. library_stats['artists'][artist_name]['count'] = 1
  194. library_stats['artists'][artist_name]['id'] = artist_id
  195. else:
  196. library_stats['artists'][artist_name]['count'] += 1
  197. # }}} increase_artist_count #
  198. # update_popularity_stats {{{ #
  199. def update_popularity_stats(new_data_point, library_stats, sample_size):
  200. """Updates the popularity statistics in library_stats
  201. Args:
  202. new_data_point: new data to update the popularity stats with
  203. library_stats: Dictionary containing data mined from user's Spotify library
  204. sample_size: The sample size including the new data
  205. Returns:
  206. None
  207. """
  208. if sample_size < 2:
  209. library_stats['popularity'] = {
  210. "average": new_data_point,
  211. "std_dev": 0,
  212. }
  213. else :
  214. cur_mean_popularity = library_stats['popularity']['average']
  215. cur_popularity_stdev = library_stats['popularity']['std_dev']
  216. new_mean, new_std_dev = update_std_dev(
  217. cur_mean_popularity, cur_popularity_stdev, new_data_point, sample_size)
  218. library_stats['popularity'] = {
  219. "average": new_mean,
  220. "std_dev": new_std_dev,
  221. }
  222. # }}} update_popularity_stats #
  223. # get_track_info {{{ #
  224. def get_track_info(track_dict, library_stats, sample_size):
  225. """Get all the info from the track_dict directly returned by the API call in parse_library.
  226. :track_dict: Dict returned from the API call containing the track info.
  227. :library_stats: Dictionary containing the data mined from user's Spotify library
  228. :sample_size: The sample size so far including this track
  229. :returns: None
  230. """
  231. # popularity
  232. update_popularity_stats(track_dict['popularity'], library_stats, sample_size)
  233. # year
  234. year_released = track_dict['album']['release_date'].split('-')[0]
  235. increase_nested_key('year_released', year_released, library_stats)
  236. # runtime
  237. library_stats['total_runtime'] += float(track_dict['duration_ms']) / (1000 * 60)
  238. # }}} get_track_info #
  239. # update_artist_genre {{{ #
  240. def update_artist_genre(headers, artist_obj):
  241. """Updates the top genre for an artist by querying the Spotify API
  242. :headers: For making the API call.
  243. :artist_obj: the Artist object whose genre field will be updated
  244. :returns: None
  245. """
  246. artist_response = requests.get('https://api.spotify.com/v1/artists/' + artist_obj.artist_id, headers=headers).json()
  247. # update genre for artist in database with top genre
  248. if len(artist_response['genres']) > 0:
  249. artist_obj.genre = artist_response['genres'][0]
  250. artist_obj.save()
  251. # }}} #
  252. # get_top_genre {{{ #
  253. def get_top_genre(headers, top_artist_id):
  254. """Updates the top genre for a track by querying the Spotify API
  255. :headers: For making the API call.
  256. :top_artist: The first artist's (listed in the track) Spotify ID.
  257. :returns: The first genre listed for the top_artist.
  258. """
  259. artist_response = requests.get('https://api.spotify.com/v1/artists/' +
  260. top_artist_id, headers=headers).json()
  261. # pprint.pprint(artist_response)
  262. if len(artist_response['genres']) > 0:
  263. return artist_response['genres'][0]
  264. else:
  265. return "undefined"
  266. # }}} #
  267. def tally_artist_genres(headers, artist_id):
  268. """Tallies up genres for artist for the respective Genre models. Should be
  269. called when new Artist object is created.
  270. :headers: For making the API call.
  271. :artist_id: Artist ID for which to tally up genres for.
  272. :returns: None
  273. """
  274. artist_response = requests.get('https://api.spotify.com/v1/artists/' +
  275. artist_id, headers=headers).json()
  276. for genre in artist_response['genres']:
  277. genre_obj, created = Genre.objects.get_or_create(name=genre,
  278. defaults={'num_songs':1})
  279. if not created:
  280. genre_obj.num_songs = F('num_songs') +1
  281. genre_obj.save()
  282. # process_library_stats {{{ #
  283. def process_library_stats(library_stats):
  284. """Processes library_stats into format more suitable for D3 consumption
  285. Args:
  286. library_stats: Dictionary containing the data mined from user's Spotify library
  287. Returns:
  288. A new dictionary that contains the data in library_stats, in a format more suitable for D3 consumption
  289. """
  290. processed_library_stats = {}
  291. for key in library_stats:
  292. if key == 'artists' or key == 'genres' or key == 'year_released':
  293. for inner_key in library_stats[key]:
  294. if key not in processed_library_stats:
  295. processed_library_stats[key] = []
  296. processed_item_key = '' # identifier key for each dict in the list
  297. count = 0
  298. if 'artist' in key:
  299. processed_item_key = 'name'
  300. count = library_stats[key][inner_key]['count']
  301. elif 'genre' in key:
  302. processed_item_key = 'genre'
  303. count = library_stats[key][inner_key]
  304. else:
  305. processed_item_key = 'year'
  306. count = library_stats[key][inner_key]
  307. processed_library_stats[key].append({
  308. processed_item_key: inner_key,
  309. "count": count
  310. })
  311. elif key == 'audio_features':
  312. for audio_feature in library_stats[key]:
  313. if 'audio_features' not in processed_library_stats:
  314. processed_library_stats['audio_features'] = []
  315. processed_library_stats['audio_features'].append({
  316. 'feature': audio_feature,
  317. 'average': library_stats[key][audio_feature]['average'],
  318. 'std_dev': library_stats[key][audio_feature]['std_dev']
  319. })
  320. # TODO: Not sure about final form for 'popularity'
  321. # elif key == 'popularity':
  322. # processed_library_stats[key] = []
  323. # processed_library_stats[key].append({
  324. # })
  325. elif key == 'num_songs' or key == 'total_runtime' or key == 'popularity':
  326. processed_library_stats[key] = library_stats[key]
  327. return processed_library_stats
  328. # }}} process_library_stats #
  329. # get_artists_in_genre {{{ #
  330. def get_artists_in_genre(user, genre, max_songs):
  331. """Return count of artists in genre.
  332. :user: User object to return data for.
  333. :genre: genre to count artists for.
  334. :max_songs: max total songs to include to prevent overflow due to having
  335. multiple artists on each track.
  336. :returns: dict of artists in the genre along with the number of songs they
  337. have.
  338. """
  339. artist_counts = (Artist.objects.filter(track__users=user)
  340. .filter(track__genre=genre)
  341. .annotate(num_songs=Count('track', distinct=True))
  342. .order_by('-num_songs')
  343. )
  344. processed_artist_counts = {}
  345. songs_added = 0
  346. for artist in artist_counts:
  347. if songs_added + artist.num_songs <= max_songs:
  348. processed_artist_counts[artist.name] = artist.num_songs
  349. songs_added += artist.num_songs
  350. # processed_artist_counts = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts]
  351. # processed_artist_counts = {artist.name: artist.num_songs for artist in artist_counts}
  352. # pprint.pprint(processed_artist_counts)
  353. return processed_artist_counts
  354. # }}} get_artists_in_genre #