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.

271 lines
9.4 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. import os
  6. import json
  7. from django.db.models import Count, Q, F
  8. from django.http import JsonResponse
  9. from django.core import serializers
  10. from django.utils import timezone
  11. from .models import *
  12. from login.models import User
  13. # }}} imports #
  14. # console_logging = True
  15. console_logging = False
  16. artists_genre_processed = 0
  17. features_processed = 0
  18. # update_track_genres {{{ #
  19. def update_track_genres(user_obj):
  20. """Updates user_obj's tracks with the most common genre associated with the
  21. songs' artist(s).
  22. :user_obj: User object who's tracks are being updated.
  23. :returns: None
  24. """
  25. tracks_processed = 0
  26. user_tracks = Track.objects.filter(users__exact=user_obj)
  27. for track in user_tracks:
  28. # just using this variable to save another call to db
  29. track_artists = track.artists.all()
  30. # set genres to first artist's genres then find intersection with others
  31. shared_genres = track_artists.first().genres.all()
  32. for artist in track_artists:
  33. shared_genres = shared_genres.intersection(artist.genres.all())
  34. shared_genres = shared_genres.order_by('-num_songs')
  35. undefined_genre_obj = Genre.objects.get(name="undefined")
  36. most_common_genre = shared_genres.first() if shared_genres.first() is \
  37. not undefined_genre_obj else shared_genres[1]
  38. track.genre = most_common_genre if most_common_genre is not None \
  39. else undefined_genre_obj
  40. track.save()
  41. tracks_processed += 1
  42. if console_logging:
  43. print("Added '{}' as genre for song #{} - '{}'".format(
  44. track.genre,
  45. tracks_processed,
  46. track.name,
  47. ))
  48. # }}} update_track_genres #
  49. # save_track_obj {{{ #
  50. def save_track_obj(track_dict, artists, user_obj):
  51. """Make an entry in the database for this track if it doesn't exist already.
  52. :track_dict: dictionary from the API call containing track information.
  53. :artists: artists of the song, passed in as a list of Artist objects.
  54. :user_obj: User object for which this Track is to be associated with.
  55. :returns: (The created/retrieved Track object, created)
  56. """
  57. track_query = Track.objects.filter(id__exact=track_dict['id'])
  58. if len(track_query) != 0:
  59. return track_query[0], False
  60. else:
  61. # check if track is simple or full, simple Track object won't have year
  62. # if 'album' in track_dict:
  63. try:
  64. new_track = Track.objects.create(
  65. id=track_dict['id'],
  66. year=track_dict['album']['release_date'].split('-')[0],
  67. popularity=int(track_dict['popularity']),
  68. runtime=int(float(track_dict['duration_ms']) / 1000),
  69. name=track_dict['name'],
  70. )
  71. # else:
  72. except KeyError:
  73. new_track = Track.objects.create(
  74. id=track_dict['id'],
  75. popularity=int(track_dict['popularity']),
  76. runtime=int(float(track_dict['duration_ms']) / 1000),
  77. name=track_dict['name'],
  78. )
  79. # have to add artists and user_obj after saving object since track needs to
  80. # have ID before filling in m2m field
  81. for artist in artists:
  82. new_track.artists.add(artist)
  83. # print(new_track.name, artist.name)
  84. if user_obj != None:
  85. new_track.users.add(user_obj)
  86. new_track.save()
  87. return new_track, True
  88. # }}} save_track_obj #
  89. # get_audio_features {{{ #
  90. def get_audio_features(headers, track_objs):
  91. """Creates and saves a new AudioFeatures objects for the respective
  92. track_objs. track_objs should contain the API limit for a single call
  93. (FEATURES_LIMIT) for maximum efficiency.
  94. :headers: headers containing the API token
  95. :track_objs: Track objects to associate with the new AudioFeatures object
  96. :returns: None
  97. """
  98. track_ids = str.join(",", [track_obj.id for track_obj in track_objs])
  99. params = {'ids': track_ids}
  100. features_response = requests.get("https://api.spotify.com/v1/audio-features",
  101. headers=headers,
  102. params={'ids': track_ids}
  103. ).json()['audio_features']
  104. # pprint.pprint(features_response)
  105. useless_keys = [ "key", "mode", "type", "liveness", "id", "uri",
  106. "track_href", "analysis_url", "time_signature", ]
  107. for i in range(len(track_objs)):
  108. if features_response[i] is not None:
  109. # Data that we don't need
  110. cur_features_obj = AudioFeatures()
  111. cur_features_obj.track = track_objs[i]
  112. for key, val in features_response[i].items():
  113. if key not in useless_keys:
  114. setattr(cur_features_obj, key, val)
  115. cur_features_obj.save()
  116. if console_logging:
  117. global features_processed
  118. features_processed += 1
  119. print("Added features for song #{} - {}".format(
  120. features_processed, track_objs[i].name))
  121. # }}} get_audio_features #
  122. # process_artist_genre {{{ #
  123. def process_artist_genre(genre_name, artist_obj):
  124. """Increase count for correspoding Genre object to genre_name and add that
  125. Genre to artist_obj.
  126. :genre_name: Name of genre.
  127. :artist_obj: Artist object to add Genre object to.
  128. :returns: None
  129. """
  130. genre_obj, created = Genre.objects.get_or_create(name=genre_name,
  131. defaults={'num_songs':1})
  132. if not created:
  133. genre_obj.num_songs = F('num_songs') + 1
  134. genre_obj.save()
  135. artist_obj.genres.add(genre_obj)
  136. artist_obj.save()
  137. # }}} process_artist_genre #
  138. # add_artist_genres {{{ #
  139. def add_artist_genres(headers, artist_objs):
  140. """Adds genres to artist_objs and increases the count the respective Genre
  141. object. artist_objs should contain the API limit for a single call
  142. (ARTIST_LIMIT) for maximum efficiency.
  143. :headers: For making the API call.
  144. :artist_objs: List of Artist objects for which to add/tally up genres for.
  145. :returns: None
  146. """
  147. artist_ids = str.join(",", [artist_obj.id for artist_obj in artist_objs])
  148. params = {'ids': artist_ids}
  149. artists_response = requests.get('https://api.spotify.com/v1/artists/',
  150. headers=headers,
  151. params={'ids': artist_ids},
  152. ).json()['artists']
  153. for i in range(len(artist_objs)):
  154. if len(artists_response[i]['genres']) == 0:
  155. process_artist_genre("undefined", artist_objs[i])
  156. else:
  157. for genre in artists_response[i]['genres']:
  158. process_artist_genre(genre, artist_objs[i])
  159. # print(artist_objs[i].name, genre)
  160. if console_logging:
  161. global artists_genre_processed
  162. artists_genre_processed += 1
  163. print("Added genres for artist #{} - {}".format(
  164. artists_genre_processed, artist_objs[i].name))
  165. # }}} add_artist_genres #
  166. # get_artists_in_genre {{{ #
  167. def get_artists_in_genre(user, genre, max_songs):
  168. """Return count of artists in genre.
  169. :user: User object to return data for.
  170. :genre: genre to count artists for.
  171. :max_songs: max total songs to include to prevent overflow due to having
  172. multiple artists on each track.
  173. :returns: dict of artists in the genre along with the number of songs they
  174. have.
  175. """
  176. genre_obj = Genre.objects.get(name=genre)
  177. artist_counts = (Artist.objects.filter(track__users=user)
  178. .filter(genres=genre_obj)
  179. .annotate(num_songs=Count('track', distinct=True))
  180. .order_by('-num_songs')
  181. )
  182. processed_artist_counts = {}
  183. songs_added = 0
  184. for artist in artist_counts:
  185. # hacky way to not have total count overflow due to there being multiple
  186. # artists on a track
  187. if songs_added + artist.num_songs <= max_songs:
  188. processed_artist_counts[artist.name] = artist.num_songs
  189. songs_added += artist.num_songs
  190. # processed_artist_counts = [{'name': artist.name, 'num_songs': artist.num_songs} for artist in artist_counts]
  191. # processed_artist_counts = {artist.name: artist.num_songs for artist in artist_counts}
  192. # pprint.pprint(processed_artist_counts)
  193. return processed_artist_counts
  194. # }}} get_artists_in_genre #
  195. def create_artist_for_track(artist_dict):
  196. """TODO: Docstring for create_artist_for_track.
  197. :artist_dict: TODO
  198. :returns: None
  199. """
  200. pass
  201. def get_user_header(user_obj):
  202. """Returns the authorization string needed to make an API call.
  203. :user_obj: User to return the auth string for.
  204. :returns: the authorization string used for the header in a Spotify API
  205. call.
  206. """
  207. seconds_elapsed = (timezone.now() -
  208. user_obj.access_obtained_at).total_seconds()
  209. if seconds_elapsed >= user_obj.access_expires_in:
  210. req_body = {
  211. 'grant_type': 'refresh_token',
  212. 'refresh_token': user_obj.refresh_token,
  213. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  214. 'client_secret': os.environ['SPOTIFY_CLIENT_SECRET']
  215. }
  216. token_response = requests.post('https://accounts.spotify.com/api/token',
  217. data=req_body).json()
  218. user_obj.access_token = token_response['access_token']
  219. user_obj.access_expires_in = token_response['expires_in']
  220. user_obj.save()
  221. return {'Authorization': "Bearer " + user_obj.access_token}