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.

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