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.

299 lines
10 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  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. # global vars {{{ #
  12. console_logging = True
  13. # console_logging = False
  14. USER_TRACKS_LIMIT = 50
  15. ARTIST_LIMIT = 50
  16. FEATURES_LIMIT = 100
  17. # ARTIST_LIMIT = 25
  18. # FEATURES_LIMIT = 25
  19. # }}} global vars #
  20. # parse_library {{{ #
  21. def parse_library(headers, num_tracks, user):
  22. """Scans user's library for num_tracks and store the information in a database
  23. :headers: For API call.
  24. :num_tracks: Number of tracks to get from user's library (0 scans the entire
  25. library).
  26. :user: a User object representing the user whose library we are parsing
  27. :returns: None
  28. """
  29. offset = 0
  30. payload = {'limit': str(USER_TRACKS_LIMIT)}
  31. artist_genre_queue = []
  32. features_queue = []
  33. # create this obj so loop runs at least once
  34. saved_tracks_response = [0]
  35. # scan until reach num_tracks or no tracks left if scanning entire library
  36. while (num_tracks == 0 or offset < num_tracks) and len(saved_tracks_response) > 0:
  37. payload['offset'] = str(offset)
  38. saved_tracks_response = requests.get('https://api.spotify.com/v1/me/tracks',
  39. headers=headers,
  40. params=payload).json()['items']
  41. for track_dict in saved_tracks_response:
  42. # add artists {{{ #
  43. # update artist info before track so that Track object can reference
  44. # Artist object
  45. track_artists = []
  46. for artist_dict in track_dict['track']['artists']:
  47. artist_obj, artist_created = Artist.objects.get_or_create(
  48. artist_id=artist_dict['id'],
  49. name=artist_dict['name'],)
  50. # only add/tally up artist genres if new
  51. if artist_created:
  52. artist_genre_queue.append(artist_obj)
  53. if len(artist_genre_queue) == ARTIST_LIMIT:
  54. add_artist_genres(headers, artist_genre_queue)
  55. artist_genre_queue = []
  56. track_artists.append(artist_obj)
  57. # }}} add artists #
  58. track_obj, track_created = save_track_obj(track_dict['track'],
  59. track_artists, user)
  60. # add audio features {{{ #
  61. # if a new track is not created, the associated audio feature does
  62. # not need to be created again
  63. if track_created:
  64. features_queue.append(track_obj)
  65. if len(features_queue) == FEATURES_LIMIT:
  66. get_audio_features(headers, features_queue)
  67. features_queue = []
  68. # }}} add audio features #
  69. if console_logging:
  70. print("Added track #{}-{}: {} - {}".format(offset + 1,
  71. offset + USER_TRACKS_LIMIT,
  72. track_obj.artists.first(),
  73. track_obj.name))
  74. # calculates num_songs with offset + songs retrieved
  75. offset += USER_TRACKS_LIMIT
  76. # clean-up {{{ #
  77. # update remaining artists without genres and songs without features if
  78. # there are any
  79. if len(artist_genre_queue) > 0:
  80. add_artist_genres(headers, artist_genre_queue)
  81. if len(features_queue) > 0:
  82. get_audio_features(headers, features_queue)
  83. # }}} clean-up #
  84. update_track_genres(user)
  85. # }}} parse_library #
  86. # update_track_genres {{{ #
  87. def update_track_genres(user):
  88. """Updates user's tracks with the most common genre associated with the
  89. songs' artist(s).
  90. :user: User object who's tracks are being updated.
  91. :returns: None
  92. """
  93. user_tracks = Track.objects.filter(users__exact=user)
  94. for track in user_tracks:
  95. # just using this variable to save another call to db
  96. track_artists = track.artists.all()
  97. # set genres to first artist's genres then find intersection with others
  98. shared_genres = track_artists.first().genres.all()
  99. for artist in track_artists:
  100. shared_genres = shared_genres.intersection(artist.genres.all())
  101. shared_genres = shared_genres.order_by('-num_songs')
  102. undefined_genre_obj = Genre.objects.get(name="undefined")
  103. most_common_genre = shared_genres.first() if shared_genres.first() is \
  104. not undefined_genre_obj else shared_genres[1]
  105. track.genre = most_common_genre if most_common_genre is not None \
  106. else undefined_genre_obj
  107. track.save()
  108. if console_logging:
  109. print("Added '{}' as genre for song '{}'".format(track.genre, track.name))
  110. # }}} update_track_genres #
  111. # save_track_obj {{{ #
  112. def save_track_obj(track_dict, artists, user):
  113. """Make an entry in the database for this track if it doesn't exist already.
  114. :track_dict: dictionary from the API call containing track information.
  115. :artists: artists of the song, passed in as a list of Artist objects.
  116. :top_genre: top genre associated with this track (see get_top_genre).
  117. :user: User object for which this Track is to be associated with.
  118. :returns: (The created/retrieved Track object, created)
  119. """
  120. track_query = Track.objects.filter(track_id__exact=track_dict['id'])
  121. if len(track_query) != 0:
  122. return track_query[0], False
  123. else:
  124. new_track = Track.objects.create(
  125. track_id=track_dict['id'],
  126. year=track_dict['album']['release_date'].split('-')[0],
  127. popularity=int(track_dict['popularity']),
  128. runtime=int(float(track_dict['duration_ms']) / 1000),
  129. name=track_dict['name'],
  130. )
  131. # have to add artists and user after saving object since track needs to
  132. # have ID before filling in m2m field
  133. for artist in artists:
  134. new_track.artists.add(artist)
  135. new_track.users.add(user)
  136. new_track.save()
  137. return new_track, True
  138. # }}} save_track_obj #
  139. # get_audio_features {{{ #
  140. def get_audio_features(headers, track_objs):
  141. """Creates and saves a new AudioFeatures objects for the respective
  142. track_objs. track_objs should contain the API limit for a single call
  143. (FEATURES_LIMIT) for maximum efficiency.
  144. :headers: headers containing the API token
  145. :track_objs: Track objects to associate with the new AudioFeatures object
  146. :returns: None
  147. """
  148. track_ids = str.join(",", [track_obj.track_id for track_obj in track_objs])
  149. params = {'ids': track_ids}
  150. features_response = requests.get("https://api.spotify.com/v1/audio-features",
  151. headers=headers,params=params).json()['audio_features']
  152. # pprint.pprint(features_response)
  153. useless_keys = [ "key", "mode", "type", "liveness", "id", "uri", "track_href", "analysis_url", "time_signature", ]
  154. for i in range(len(track_objs)):
  155. if features_response[i] is not None:
  156. # Data that we don't need
  157. cur_features_obj = AudioFeatures()
  158. cur_features_obj.track = track_objs[i]
  159. for key, val in features_response[i].items():
  160. if key not in useless_keys:
  161. setattr(cur_features_obj, key, val)
  162. cur_features_obj.save()
  163. if console_logging:
  164. print("Added features for song #{} - {}".format(i + 1,
  165. track_objs[i].name))
  166. # }}} get_audio_features #
  167. # process_artist_genre {{{ #
  168. def process_artist_genre(genre_name, artist_obj):
  169. """Increase count for correspoding Genre object to genre_name and add that
  170. Genre to artist_obj.
  171. :genre_name: Name of genre.
  172. :artist_obj: Artist object to add Genre object to.
  173. :returns: None
  174. """
  175. genre_obj, created = Genre.objects.get_or_create(name=genre_name,
  176. defaults={'num_songs':1})
  177. if not created:
  178. genre_obj.num_songs = F('num_songs') + 1
  179. genre_obj.save()
  180. artist_obj.genres.add(genre_obj)
  181. artist_obj.save()
  182. # }}} process_artist_genre #
  183. # add_artist_genres {{{ #
  184. def add_artist_genres(headers, artist_objs):
  185. """Adds genres to artist_objs and increases the count the respective Genre
  186. object. artist_objs should contain the API limit for a single call
  187. (ARTIST_LIMIT) for maximum efficiency.
  188. :headers: For making the API call.
  189. :artist_objs: List of Artist objects for which to add/tally up genres for.
  190. :returns: None
  191. """
  192. artist_ids = str.join(",", [artist_obj.artist_id for artist_obj in artist_objs])
  193. params = {'ids': artist_ids}
  194. artists_response = requests.get('https://api.spotify.com/v1/artists/',
  195. headers=headers, params=params).json()['artists']
  196. for i in range(len(artist_objs)):
  197. if len(artists_response[i]['genres']) == 0:
  198. process_artist_genre("undefined", artist_objs[i])
  199. else:
  200. for genre in artists_response[i]['genres']:
  201. process_artist_genre(genre, artist_objs[i])
  202. if console_logging:
  203. print("Added genres for artist #{} - {}".format(i + 1,
  204. artist_objs[i].name))
  205. # }}} add_artist_genres #
  206. # get_artists_in_genre {{{ #
  207. def get_artists_in_genre(user, genre, max_songs):
  208. """Return count of artists in genre.
  209. :user: User object to return data for.
  210. :genre: genre to count artists for.
  211. :max_songs: max total songs to include to prevent overflow due to having
  212. multiple artists on each track.
  213. :returns: dict of artists in the genre along with the number of songs they
  214. have.
  215. """
  216. genre_obj = Genre.objects.get(name=genre)
  217. artist_counts = (Artist.objects.filter(track__users=user)
  218. .filter(genres=genre_obj)
  219. .annotate(num_songs=Count('track', distinct=True))
  220. .order_by('-num_songs')
  221. )
  222. processed_artist_counts = {}
  223. songs_added = 0
  224. for artist in artist_counts:
  225. # hacky way to not have total count overflow due to there being multiple
  226. # artists on a track
  227. if songs_added + artist.num_songs <= max_songs:
  228. processed_artist_counts[artist.name] = artist.num_songs
  229. songs_added += artist.num_songs
  230. # processed_artist_counts = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts]
  231. # processed_artist_counts = {artist.name: artist.num_songs for artist in artist_counts}
  232. # pprint.pprint(processed_artist_counts)
  233. return processed_artist_counts
  234. # }}} get_artists_in_genre #