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.

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