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.

387 lines
13 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, F, Max
  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. from dateutil.parser import parse
  15. from datetime import datetime
  16. from django.db.models import FloatField
  17. from django.db.models.functions import Cast
  18. HISTORY_ENDPOINT = 'https://api.spotify.com/v1/me/player/recently-played'
  19. # }}} imports #
  20. # console_logging = True
  21. console_logging = False
  22. artists_genre_processed = 0
  23. features_processed = 0
  24. # update_track_genres {{{ #
  25. def update_track_genres(user_obj):
  26. """Updates user_obj's tracks with the most common genre associated with the
  27. songs' artist(s).
  28. :user_obj: User object who's tracks are being updated.
  29. :returns: None
  30. """
  31. tracks_processed = 0
  32. user_tracks = Track.objects.filter(users__exact=user_obj)
  33. for track in user_tracks:
  34. # just using this variable to save another call to db
  35. track_artists = list(track.artists.all())
  36. # TODO: Use the most popular genre of the first artist as the Track genre
  37. first_artist_genres = track_artists[0].genres.all().order_by('-num_songs')
  38. undefined_genre_obj = Genre.objects.get(name="undefined")
  39. most_common_genre = first_artist_genres.first() if first_artist_genres.first() is \
  40. not undefined_genre_obj else first_artist_genres[1]
  41. track.genre = most_common_genre if most_common_genre is not None \
  42. else undefined_genre_obj
  43. track.save()
  44. tracks_processed += 1
  45. if console_logging:
  46. print("Added '{}' as genre for song #{} - '{}'".format(
  47. track.genre,
  48. tracks_processed,
  49. track.name,
  50. ))
  51. # }}} update_track_genres #
  52. # save_track_obj {{{ #
  53. def save_track_obj(track_dict, artists, user_obj):
  54. """Make an entry in the database for this track if it doesn't exist already.
  55. :track_dict: dictionary from the API call containing track information.
  56. :artists: artists of the song, passed in as a list of Artist objects.
  57. :user_obj: User object for which this Track is to be associated with.
  58. :returns: (The created/retrieved Track object, created)
  59. """
  60. track_query = Track.objects.filter(id__exact=track_dict['id'])
  61. if len(track_query) != 0:
  62. return track_query[0], False
  63. else:
  64. # check if track is simple or full, simple Track object won't have year
  65. # if 'album' in track_dict:
  66. try:
  67. new_track = Track.objects.create(
  68. id=track_dict['id'],
  69. year=track_dict['album']['release_date'].split('-')[0],
  70. popularity=int(track_dict['popularity']),
  71. runtime=int(float(track_dict['duration_ms']) / 1000),
  72. name=track_dict['name'],
  73. )
  74. # else:
  75. except KeyError:
  76. new_track = Track.objects.create(
  77. id=track_dict['id'],
  78. popularity=int(track_dict['popularity']),
  79. runtime=int(float(track_dict['duration_ms']) / 1000),
  80. name=track_dict['name'],
  81. )
  82. # have to add artists and user_obj after saving object since track needs to
  83. # have ID before filling in m2m field
  84. for artist in artists:
  85. new_track.artists.add(artist)
  86. # print(new_track.name, artist.name)
  87. if user_obj != None:
  88. new_track.users.add(user_obj)
  89. new_track.save()
  90. return new_track, True
  91. # }}} save_track_obj #
  92. # get_audio_features {{{ #
  93. def get_audio_features(headers, track_objs):
  94. """Creates and saves a new AudioFeatures objects for the respective
  95. track_objs. track_objs should contain the API limit for a single call
  96. (FEATURES_LIMIT) for maximum efficiency.
  97. :headers: headers containing the API token
  98. :track_objs: Track objects to associate with the new AudioFeatures object
  99. :returns: None
  100. """
  101. track_ids = str.join(",", [track_obj.id for track_obj in track_objs])
  102. params = {'ids': track_ids}
  103. features_response = requests.get("https://api.spotify.com/v1/audio-features",
  104. headers=headers,
  105. params={'ids': track_ids}
  106. ).json()['audio_features']
  107. # pprint.pprint(features_response)
  108. useless_keys = [ "key", "mode", "type", "liveness", "id", "uri",
  109. "track_href", "analysis_url", "time_signature", ]
  110. for i in range(len(track_objs)):
  111. if features_response[i] is not None:
  112. # Data that we don't need
  113. cur_features_obj = AudioFeatures()
  114. cur_features_obj.track = track_objs[i]
  115. for key, val in features_response[i].items():
  116. if key not in useless_keys:
  117. setattr(cur_features_obj, key, val)
  118. cur_features_obj.save()
  119. if console_logging:
  120. global features_processed
  121. features_processed += 1
  122. print("Added features for song #{} - {}".format(
  123. features_processed, track_objs[i].name))
  124. # }}} get_audio_features #
  125. # process_artist_genre {{{ #
  126. def process_artist_genre(genre_name, artist_obj):
  127. """Increase count for corresponding Genre object to genre_name and associate that
  128. Genre object with artist_obj.
  129. :genre_name: Name of genre.
  130. :artist_obj: Artist object to associate Genre object with
  131. :returns: None
  132. """
  133. genre_obj, created = Genre.objects.get_or_create(name=genre_name, defaults={'num_songs': 1})
  134. if not created:
  135. genre_obj.num_songs = F('num_songs') + 1
  136. genre_obj.save()
  137. artist_obj.genres.add(genre_obj)
  138. artist_obj.save()
  139. # }}} process_artist_genre #
  140. # add_artist_genres {{{ #
  141. def add_artist_genres(headers, artist_objs):
  142. """Adds genres to artist_objs and increases the count the respective Genre
  143. object. artist_objs should contain the API limit for a single call
  144. (ARTIST_LIMIT) for maximum efficiency.
  145. :headers: For making the API call.
  146. :artist_objs: List of Artist objects for which to add/tally up genres for.
  147. :returns: None
  148. """
  149. artist_ids = str.join(",", [artist_obj.id for artist_obj in artist_objs])
  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):
  169. """Return count of artists in genre.
  170. :user: User object to return data for.
  171. :genre: genre to count artists for. (string)
  172. :returns: dict of artists in the genre along with the number of songs they
  173. have.
  174. """
  175. genre_obj = Genre.objects.get(name=genre)
  176. tracks_in_genre = Track.objects.filter(genre=genre_obj, users=user)
  177. track_count = tracks_in_genre.count()
  178. user_artists = Artist.objects.filter(track__users=user) # use this variable to save on db queries
  179. total_artist_counts = tracks_in_genre.aggregate(counts=Count('artists'))['counts']
  180. processed_artist_counts = {}
  181. for artist in user_artists:
  182. processed_artist_counts[artist.name] = round(artist.track_set
  183. .filter(genre=genre_obj, users=user)
  184. .count() * track_count / total_artist_counts, 2)
  185. return processed_artist_counts
  186. # }}} get_artists_in_genre #
  187. # save_track_artists {{{ #
  188. def save_track_artists(track_dict, artist_genre_queue, user_headers):
  189. """ Update artist info before creating Track so that Track object can
  190. reference Artist object.
  191. :track_dict: response from Spotify API for track
  192. :returns: list of Artist objects in Track
  193. """
  194. track_artists = []
  195. for artist_dict in track_dict['artists']:
  196. artist_obj, artist_created = Artist.objects.get_or_create(
  197. id=artist_dict['id'],
  198. name=artist_dict['name'],)
  199. # only add/tally up artist genres if new
  200. if artist_created:
  201. artist_genre_queue.append(artist_obj)
  202. if len(artist_genre_queue) == views.ARTIST_LIMIT:
  203. add_artist_genres(user_headers, artist_genre_queue)
  204. artist_genre_queue[:] = []
  205. track_artists.append(artist_obj)
  206. return track_artists
  207. # }}} save_track_artists #
  208. # get_user_header {{{ #
  209. def get_user_header(user_obj):
  210. """Returns the authorization string needed to make an API call.
  211. :user_obj: User to return the auth string for.
  212. :returns: the authorization string used for the header in a Spotify API
  213. call.
  214. """
  215. seconds_elapsed = (timezone.now() -
  216. user_obj.access_obtained_at).total_seconds()
  217. if seconds_elapsed >= user_obj.access_expires_in:
  218. req_body = {
  219. 'grant_type': 'refresh_token',
  220. 'refresh_token': user_obj.refresh_token,
  221. 'client_id': os.environ['SPOTIFY_CLIENT_ID'],
  222. 'client_secret': os.environ['SPOTIFY_CLIENT_SECRET']
  223. }
  224. token_response = requests.post('https://accounts.spotify.com/api/token',
  225. data=req_body).json()
  226. user_obj.access_token = token_response['access_token']
  227. user_obj.access_expires_in = token_response['expires_in']
  228. user_obj.save()
  229. return {'Authorization': "Bearer " + user_obj.access_token}
  230. # }}} get_user_header #
  231. # save_history_obj {{{ #
  232. def save_history_obj (user, timestamp, track):
  233. """Return (get/create) a History object with the specified parameters. Can't
  234. use built-in get_or_create since don't know auto PK.
  235. :user: User object History should be associated with
  236. :timestamp: time at which song was listened to
  237. :track: Track object for song
  238. :returns: History object
  239. """
  240. history_query = History.objects.filter(user__exact=user,
  241. timestamp__exact=timestamp)
  242. if len(history_query) == 0:
  243. history_obj = History.objects.create(user=user, timestamp=timestamp,
  244. track=track)
  245. else:
  246. history_obj = history_query[0]
  247. return history_obj
  248. # }}} save_history_obj #
  249. # get_next_history_row {{{ #
  250. def get_next_history_row(csv_reader, headers, prev_info):
  251. """Return formatted information from next row in history CSV file.
  252. :csv_reader: TODO
  253. :headers:
  254. :prev_info: history_obj_info of last row in case no more rows
  255. :returns: (boolean of if last row, dict with information of next row)
  256. """
  257. try:
  258. row = next(csv_reader)
  259. # if Track.objects.filter(id__exact=row[1]).exists():
  260. history_obj_info = {}
  261. for i in range(len(headers)):
  262. history_obj_info[headers[i]] = row[i]
  263. return False, history_obj_info
  264. except StopIteration:
  265. return True, prev_info
  266. # }}} get_next_history_row #
  267. # parse_history {{{ #
  268. def parse_history(user_secret):
  269. """Scans user's listening history and stores the information in a
  270. database.
  271. :user_secret: secret for User object who's library is being scanned.
  272. :returns: None
  273. """
  274. user_obj = User.objects.get(secret=user_secret)
  275. payload = {'limit': str(views.USER_TRACKS_LIMIT)}
  276. last_time_played = History.objects.filter(user=user_obj).aggregate(Max('timestamp'))['timestamp__max']
  277. if last_time_played is not None:
  278. payload['after'] = last_time_played.isoformat()
  279. artist_genre_queue = []
  280. user_headers = get_user_header(user_obj)
  281. history_response = requests.get(HISTORY_ENDPOINT,
  282. headers=user_headers,
  283. params=payload).json()['items']
  284. # pprint(history_response)
  285. tracks_processed = 0
  286. for track_dict in history_response:
  287. # don't associate history track with User, not necessarily in their
  288. # library
  289. # track_obj, track_created = save_track_obj(track_dict['track'],
  290. # track_artists, None)
  291. track_artists = save_track_artists(track_dict['track'], artist_genre_queue,
  292. user_headers)
  293. track_obj, track_created = save_track_obj(track_dict['track'],
  294. track_artists, None)
  295. history_obj = save_history_obj(user_obj, parse(track_dict['played_at']),
  296. track_obj)
  297. tracks_processed += 1
  298. if console_logging:
  299. print("Added history track #{}: {}".format(
  300. tracks_processed, history_obj,))
  301. if len(artist_genre_queue) > 0:
  302. add_artist_genres(user_headers, artist_genre_queue)
  303. # TODO: update track genres from History relation
  304. # update_track_genres(user_obj)
  305. print("Scanned {} history tracks for user {} at {}.".format(
  306. tracks_processed, user_obj.id, datetime.now()))
  307. # }}} get_history #