-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_playlist.py
More file actions
371 lines (302 loc) · 13 KB
/
create_playlist.py
File metadata and controls
371 lines (302 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import config
import requests
import json
import pandas as pd
from tqdm import tqdm
import spotipy.util as util
import pandas_gbq
from google.oauth2 import service_account
from datetime import datetime,timezone, timedelta
credentials = service_account.Credentials.from_service_account_file(
r'/Users/Nicholas/Desktop/GCP/GCP_Keys/spotify-project-287802-e5e6c43e8ecb.json'
)
client_id = config.client_id
client_secret = config.client_secret
username = config.username
# Access to Spotify API
username = config.username
client_id = config.client_id
client_secret = config.client_secret
redirect_uri = 'http://localhost:7777/callback'
scope = 'user-read-recently-played, playlist-modify-public, playlist-modify-private'
auth_token = util.prompt_for_user_token(username=username,
scope=scope,
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri)
def gcp_top5():
'''
Queries GCP BQ to pull your top 5 most played tracks for the month
:return: top5_mtracks
'''
project_id = "spotify-project-287802"
# Query GCP BQ for top 5 played tracks
sql = """
SELECT track_id
, album_id
, artist_id
, track_name
, count(track_id) AS track_count
, artist_name
, album_name
FROM `spotify-project-287802.spotify_api.recently_played_tracks`
WHERE CAST(CAST(local_time AS TIMESTAMP) AS DATE) >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
GROUP BY track_id
, album_id
, artist_id
, track_name
, artist_name
, album_name
order by track_count DESC
"""
# Load table into df
bq_df2 = pandas_gbq.read_gbq(sql, project_id=project_id, credentials=credentials)
# Query the BQ table for case_ids
project_id = "spotify-project-287802"
sql = """
SELECT track_id
FROM `spotify-project-287802.spotify_api.spotify_python_playlist`
"""
# Load table into df
track_check = pandas_gbq.read_gbq(sql, project_id=project_id, credentials=credentials)
# Create list of dq_df case_ids
case_to_drop = track_check['track_id'].tolist()
# Compare case_ids from df1 if already in case_to_drop list
bq_df2_clean = bq_df2[~bq_df2['track_id'].str.contains('|'.join(case_to_drop))]
print('After duplicate check, there are now {} new Case IDs from the API.'.format(len(bq_df2_clean['track_id'])))
top5_mtracks = bq_df2_clean.iloc[:5]
return top5_mtracks
def gcp_dup_check(auth_token):
'''
Checks for duplicate songs already added to the playlist. If duplicated, it removes the song(s) from
the dataframe.
:param auth_token: Spotify auth token
:return: spotify_urls_ls
'''
top5_mtracks = gcp_top5()
# load data into GCP for later use
print('Loading data into GCP BigQuery')
# Load into GCP BigQuery
# Connect to Google Cloud API and upload dataframe
destinatoin_table = 'spotify_api.spotify_python_playlist'
project_id = 'spotify-project-287802'
pandas_gbq.to_gbq(top5_mtracks, destinatoin_table, project_id, if_exists='append',
credentials=credentials)
print('Script is complete; check table for details.')
track_id_ls=top5_mtracks['track_id'].tolist()
track_data = []
for id in tqdm(track_id_ls):
base_url = f'https://api.spotify.com/v1/audio-features/{id}?'
#2. Authentication
#3. Parameters -- would be stored with authentication
headers = {
"Authorization": f"Bearer {auth_token}"
}
r = requests.get(base_url, headers=headers)
track_data.append(json.loads(r.text))
track_df = pd.json_normalize(track_data)
# Used to post songs to playlist
spotify_urls_ls = track_df['uri'].tolist()
return spotify_urls_ls
def pull_playlist_info():
'''
Pulls spotify playlist info
:return: playlist_df
'''
# Check user's playlist
username = config.username
client_id = config.client_id
client_secret = config.client_secret
redirect_uri = 'http://localhost:7777/callback'
scope = 'playlist-read-collaborative, playlist-read-private, playlist-modify-public, playlist-modify-private'
auth_token = util.prompt_for_user_token(username=username,
scope=scope,
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri)
base_url = f'https://api.spotify.com/v1/users/{username}/playlists?'
#2. Authentication
#3. Parameters -- would be stored with authentication
headers = {
"Authorization": f"Bearer {auth_token}"
}
#4. Create an empty list
personal_playlist_data = [] #would be good explore how to capture data at different points in time
r = requests.get(base_url+"&limit=50", headers=headers)
personal_playlist_data.append(json.loads(r.text))
playlist_ids = []
playlist_names = []
playlist_descriptions = []
playlist_owners = []
playlist_publics = []
for i in range(len(personal_playlist_data[0]['items'])):
playlist_ids.append(personal_playlist_data[0]['items'][i]['id'])
playlist_names.append(personal_playlist_data[0]['items'][i]['name'])
playlist_descriptions.append(personal_playlist_data[0]['items'][i]['description'])
playlist_owners.append(personal_playlist_data[0]['items'][i]['owner']['display_name'])
playlist_publics.append(personal_playlist_data[0]['items'][i]['public'])
list_dic4={'playlist_id':playlist_ids,
'playlist_name':playlist_names,
'playlist_description':playlist_descriptions,
'playlist_owner':playlist_owners,
'playlist_public':playlist_publics
}
playlist_df = pd.DataFrame(list_dic4)
return playlist_df
def playlist_check():
'''
Checks to see if automated playlist already exist. If not, it creates it.
:return: playlist_df
'''
playlist_df = pull_playlist_info()
cur_year = datetime.today().strftime('%Y')
# Check to verify if playlist exist, if not create it
if f'Test Python Playlist {cur_year}' in set(playlist_df['playlist_name']):
print("Playlist exist!")
base_url = f'https://api.spotify.com/v1/users/{username}/playlists?'
# 2. Authentication
# 3. Parameters -- would be stored with authentication
headers = {
"Authorization": f"Bearer {auth_token}"
}
# 4. Create an empty list
personal_playlist_data = [] # would be good explore how to capture data at different points in time
r = requests.get(base_url + "&limit=50", headers=headers)
personal_playlist_data.append(json.loads(r.text))
playlist_ids = []
playlist_names = []
playlist_descriptions = []
playlist_owners = []
playlist_publics = []
for i in range(len(personal_playlist_data[0]['items'])):
playlist_ids.append(personal_playlist_data[0]['items'][i]['id'])
playlist_names.append(personal_playlist_data[0]['items'][i]['name'])
playlist_descriptions.append(personal_playlist_data[0]['items'][i]['description'])
playlist_owners.append(personal_playlist_data[0]['items'][i]['owner']['display_name'])
playlist_publics.append(personal_playlist_data[0]['items'][i]['public'])
list_dic4 = {'playlist_id': playlist_ids,
'playlist_name': playlist_names,
'playlist_description': playlist_descriptions,
'playlist_owner': playlist_owners,
'playlist_public': playlist_publics
}
playlist_df = pd.DataFrame(list_dic4)
return playlist_df
else:
print("Creating Playlist...")
base_url = f'https://api.spotify.com/v1/users/{username}/playlists'
# 2. Authentication
# 3. Parameters -- would be stored with authentication
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {auth_token}"
}
request_body = json.dumps({
"name": f"Test Python Playlist {cur_year}",
"description": f"This is a test playlist generated by Python for {cur_year}.",
"public": False # private
})
# 4. Create an empty list
r = requests.post(url=base_url, data=request_body, headers=headers)
print(r.text)
base_url = f'https://api.spotify.com/v1/users/{username}/playlists?'
# 2. Authentication
# 3. Parameters -- would be stored with authentication
headers = {
"Authorization": f"Bearer {auth_token}"
}
# 4. Create an empty list
personal_playlist_data = [] # would be good explore how to capture data at different points in time
r = requests.get(base_url + "&limit=50", headers=headers)
personal_playlist_data.append(json.loads(r.text))
playlist_ids = []
playlist_names = []
playlist_descriptions = []
playlist_owners = []
playlist_publics = []
for i in range(len(personal_playlist_data[0]['items'])):
playlist_ids.append(personal_playlist_data[0]['items'][i]['id'])
playlist_names.append(personal_playlist_data[0]['items'][i]['name'])
playlist_descriptions.append(personal_playlist_data[0]['items'][i]['description'])
playlist_owners.append(personal_playlist_data[0]['items'][i]['owner']['display_name'])
playlist_publics.append(personal_playlist_data[0]['items'][i]['public'])
list_dic4 = {'playlist_id': playlist_ids,
'playlist_name': playlist_names,
'playlist_description': playlist_descriptions,
'playlist_owner': playlist_owners,
'playlist_public': playlist_publics
}
playlist_df = pd.DataFrame(list_dic4)
return playlist_df
def pull_playlist_id():
'''
Calls playlist API and pulls playlist ID to push tracks to in next function.
:return: playlist_id
'''
playlist_df = playlist_check()
# Pull playlist ID
username = config.username
client_id = config.client_id
client_secret = config.client_secret
redirect_uri = 'http://localhost:7777/callback'
scope = 'playlist-read-private'
auth_token = util.prompt_for_user_token(username=username,
scope=scope,
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri)
base_url = f'https://api.spotify.com/v1/users/{username}/playlists?'
#2. Authentication
#3. Parameters -- would be stored with authentication
headers = {
"Authorization": f"Bearer {auth_token}"
}
#4. Create an empty list
personal_playlist_data = [] #would be good explore how to capture data at different points in time
r = requests.get(base_url+"&limit=50", headers=headers)
personal_playlist_data.append(json.loads(r.text))
playlist_ids = []
playlist_names = []
playlist_descriptions = []
playlist_owners = []
playlist_publics = []
for i in range(len(personal_playlist_data[0]['items'])):
playlist_ids.append(personal_playlist_data[0]['items'][i]['id'])
playlist_names.append(personal_playlist_data[0]['items'][i]['name'])
playlist_descriptions.append(personal_playlist_data[0]['items'][i]['description'])
playlist_owners.append(personal_playlist_data[0]['items'][i]['owner']['display_name'])
playlist_publics.append(personal_playlist_data[0]['items'][i]['public'])
list_dic4={'playlist_id':playlist_ids,
'playlist_name':playlist_names,
'playlist_description':playlist_descriptions,
'playlist_owner':playlist_owners,
'playlist_public':playlist_publics
}
playlist_df = pd.DataFrame(list_dic4)
playlist_id = playlist_df.loc[playlist_df['playlist_name'] == 'Test Python Playlist 2020', 'playlist_id'].tolist()[0]
return playlist_id
def add_songs():
'''
Adds top 5 new tracks to automated playlist
:return: N/A
'''
playlist_id = pull_playlist_id()
spotify_urls_ls = gcp_dup_check(auth_token)
# Push songs to playlist
#playlist_id = '79tXL4BD7MnqvpMZtKDho9'
base_url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"
# Must be in list to load into playlist
uris = spotify_urls_ls
# Authentication
# Parameters -- would be stored with authentication
headers = {
"Content-Type":"application/json",
"Authorization": f"Bearer {auth_token}"
}
request_body = json.dumps({
"uris":uris
})
# Make request
r = requests.post(url = base_url, data = request_body, headers=headers)
r.text
add_songs()