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.

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