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.

278 lines
9.0 KiB

  1. # imports {{{ #
  2. import math
  3. import random
  4. import requests
  5. import urllib
  6. import secrets
  7. import string
  8. import csv
  9. from django.shortcuts import render, redirect
  10. from django.http import JsonResponse
  11. from django.db.models import Count, Q, Max
  12. from django.core.files import File
  13. from .utils import *
  14. from .models import *
  15. from login.models import User
  16. from login.utils import get_user_context
  17. from dateutil.parser import parse
  18. from pprint import pprint
  19. from login.models import HistoryUpload
  20. # }}} imports #
  21. # constants {{{ #
  22. USER_TRACKS_LIMIT = 50
  23. TRACKS_LIMIT = 50
  24. HISTORY_LIMIT = 50
  25. ARTIST_LIMIT = 50
  26. FEATURES_LIMIT = 100
  27. # ARTIST_LIMIT = 25
  28. # FEATURES_LIMIT = 25
  29. TRACKS_TO_QUERY = 100
  30. TRACKS_ENDPOINT = 'https://api.spotify.com/v1/tracks'
  31. console_logging = True
  32. # console_logging = False
  33. # }}} constants #
  34. # parse_library {{{ #
  35. def parse_library(request, user_secret):
  36. """Scans user's library for num_tracks and store the information in a
  37. database.
  38. :user_secret: secret for User object who's library is being scanned.
  39. :returns: None
  40. """
  41. offset = 0
  42. payload = {'limit': str(USER_TRACKS_LIMIT)}
  43. artist_genre_queue = []
  44. features_queue = []
  45. user_obj = User.objects.get(secret=user_secret)
  46. user_headers = get_user_header(user_obj)
  47. # create this obj so loop runs at least once
  48. saved_tracks_response = [0]
  49. # scan until reach num_tracks or no tracks left if scanning entire library
  50. while ((TRACKS_TO_QUERY == 0 or offset < TRACKS_TO_QUERY) and
  51. len(saved_tracks_response) > 0):
  52. payload['offset'] = str(offset)
  53. saved_tracks_response = requests.get('https://api.spotify.com/v1/me/tracks',
  54. headers=user_headers,
  55. params=payload).json()['items']
  56. if console_logging:
  57. tracks_processed = 0
  58. for track_dict in saved_tracks_response:
  59. track_artists = save_track_artists(track_dict['track'], artist_genre_queue,
  60. user_headers)
  61. track_obj, track_created = save_track_obj(track_dict['track'],
  62. track_artists, user_obj)
  63. # add audio features {{{ #
  64. # if a new track is not created, the associated audio feature does
  65. # not need to be created again
  66. if track_created:
  67. features_queue.append(track_obj)
  68. if len(features_queue) == FEATURES_LIMIT:
  69. get_audio_features(user_headers, features_queue)
  70. features_queue = []
  71. # }}} add audio features #
  72. if console_logging:
  73. tracks_processed += 1
  74. print("Added track #{}: {} - {}".format(
  75. offset + tracks_processed,
  76. track_obj.artists.first(),
  77. track_obj.name,
  78. ))
  79. # calculates num_songs with offset + songs retrieved
  80. offset += USER_TRACKS_LIMIT
  81. # clean-up {{{ #
  82. # update remaining artists without genres and songs without features if
  83. # there are any
  84. if len(artist_genre_queue) > 0:
  85. add_artist_genres(user_headers, artist_genre_queue)
  86. if len(features_queue) > 0:
  87. get_audio_features(user_headers, features_queue)
  88. # }}} clean-up #
  89. update_track_genres(user_obj)
  90. return render(request, 'graphs/logged_in.html', get_user_context(user_obj))
  91. # }}} parse_library #
  92. # parse_history_request {{{ #
  93. def parse_history_request(request, user_secret):
  94. """Request function to call parse_history. Scans user's listening history
  95. and stores the information in a database.
  96. :user_secret: secret for User object who's library is being scanned.
  97. :returns: redirects user to logged in page
  98. """
  99. parse_history(user_secret)
  100. return render(request, 'graphs/logged_in.html',
  101. get_user_context(User.objects.get(secret=user_secret)))
  102. # }}} get_history #
  103. # get_artist_data {{{ #
  104. def get_artist_data(request, user_secret):
  105. """Returns artist data as a JSON serialized list of dictionaries
  106. The (key, value) pairs are (artist name, song count for said artist)
  107. :param request: the HTTP request
  108. :param user_secret: the user secret used for identification
  109. :return: a JsonResponse
  110. """
  111. user = User.objects.get(secret=user_secret)
  112. artist_counts = Artist.objects.annotate(num_songs=Count('track',
  113. filter=Q(track__users=user)))
  114. processed_artist_counts = [{'name': artist.name, 'num_songs': artist.num_songs}
  115. for artist in artist_counts]
  116. pprint(processed_artist_counts)
  117. return JsonResponse(data=processed_artist_counts, safe=False)
  118. # }}} get_artist_data #
  119. # get_audio_feature_data {{{ #
  120. def get_audio_feature_data(request, audio_feature, user_secret):
  121. """Returns all data points for a given audio feature
  122. Args:
  123. request: the HTTP request
  124. audio_feature: The audio feature to be queried
  125. user_secret: client secret, used to identify the user
  126. """
  127. user = User.objects.get(secret=user_secret)
  128. user_tracks = Track.objects.filter(users=user)
  129. response_payload = {
  130. 'data_points': [],
  131. }
  132. for track in user_tracks:
  133. try:
  134. audio_feature_obj = AudioFeatures.objects.get(track=track)
  135. response_payload['data_points'].append(getattr(audio_feature_obj, audio_feature))
  136. except AudioFeatures.DoesNotExist:
  137. continue
  138. return JsonResponse(response_payload)
  139. # }}} get_audio_feature_data #
  140. # get_genre_data {{{ #
  141. def get_genre_data(request, user_secret):
  142. """Return genre data needed to create the graph
  143. TODO
  144. """
  145. user = User.objects.get(secret=user_secret)
  146. genre_counts = (Track.objects.filter(users__exact=user)
  147. .values('genre')
  148. .order_by('genre')
  149. .annotate(num_songs=Count('genre'))
  150. )
  151. for genre_dict in genre_counts:
  152. genre_dict['artists'] = get_artists_in_genre(user, genre_dict['genre'],
  153. genre_dict['num_songs'])
  154. print("*** Genre Breakdown ***")
  155. pprint(list(genre_counts))
  156. return JsonResponse(data=list(genre_counts), safe=False)
  157. # }}} get_genre_data #
  158. # import_history {{{ #
  159. def import_history(request, upload_id):
  160. """Import history for the user from the file they uploaded.
  161. :upload_id: ID (PK) of the HistoryUpload entry
  162. :returns: None
  163. """
  164. # setup {{{ #
  165. headers = ['timestamp', 'track_id']
  166. upload_obj = HistoryUpload.objects.get(id=upload_id)
  167. user_headers = get_user_header(upload_obj.user)
  168. with upload_obj.document.open('r') as f:
  169. csv_reader = csv.reader(f, delimiter=',')
  170. rows_read = 0
  171. history_obj_info_lst = []
  172. artist_genre_queue = []
  173. # skip header row
  174. last_row, history_obj_info = get_next_history_row(csv_reader, headers,
  175. {})
  176. while not last_row:
  177. last_row, history_obj_info = get_next_history_row(csv_reader,
  178. headers, history_obj_info)
  179. # }}} setup #
  180. history_obj_info_lst.append(history_obj_info)
  181. # PU: refactor saving History object right away if Track obj already
  182. # exists
  183. # PU: refactor below?
  184. rows_read += 1
  185. if (rows_read % TRACKS_LIMIT == 0) or last_row:
  186. # get tracks_response {{{ #
  187. track_ids_lst = [info['track_id'] for info in history_obj_info_lst]
  188. # print(len(track_ids_lst))
  189. track_ids = ','.join(track_ids_lst)
  190. payload = {'ids': track_ids}
  191. tracks_response = requests.get(TRACKS_ENDPOINT,
  192. headers=user_headers,
  193. params=payload).json()['tracks']
  194. responses_processed = 0
  195. # }}} get tracks_response #
  196. for track_dict in tracks_response:
  197. # don't associate history track with User, not necessarily in their
  198. # library
  199. track_artists = save_track_artists(track_dict, artist_genre_queue,
  200. user_headers)
  201. track_obj, track_created = save_track_obj(track_dict,
  202. track_artists, None)
  203. timestamp = \
  204. parse(history_obj_info_lst[responses_processed]['timestamp'])
  205. history_obj = save_history_obj(upload_obj.user, timestamp,
  206. track_obj)
  207. if console_logging:
  208. print("Processed row #{}: {}".format(
  209. (rows_read - TRACKS_LIMIT) + responses_processed, history_obj,))
  210. responses_processed += 1
  211. history_obj_info_lst = []
  212. if len(artist_genre_queue) > 0:
  213. add_artist_genres(user_headers, artist_genre_queue)
  214. # TODO: update track genres from History relation
  215. # update_track_genres(user_obj)
  216. return redirect('graphs:display_history_table')
  217. # }}} get_history #