This script will suggest playlists based on the text of your choice. For example, if you enter 'If I can't let it go out of my mind' [the default value], your playlist may include songs titled 'Out of my mind'. You also need to specify the number of track suggested [default value is 3]. The first time you run this script, it will ask authorization to access your Spotify account. The script also needs the 'Spotify' library installed in your system.
To start, please tell me the text you want to match and the number of playlists
In [1]:
#install spotipy
! pip install spotipy
#This command above only from Jupyter notebooks
# Load Libraries
import math
import spotipy
import spotipy.util as util
#Request User Input
cuesline = input("Enter your text here [Default: 'If I can't let it go out of my mind'] : ")
playlistno = input("Enter the number of playlists you want to generate? [Default: 3] : ")
In [2]:
#Handle Missing Input/Error in Entry
default = "If I can't let it go out of my mind"
try:
if not bool(cuesline.strip()) or cuesline in ('','""',"''"):
cuesline = default
print ("")
print ("Using text default value:",default)
except:
cuesline = default
print ("")
print ("Using text default value:",default)
cues = cuesline.split()
try:
playlistno = eval(playlistno)
if playlistno<=0:
if len(cues)>=3:
playlistno = 3
print ("")
print ("Using default value of",playlistno,"playlists")
else:
playlistno = len(cues)
print ("")
print ("Your text contains less than 3 words, I'll search for",playlistno," playlists")
elif playlistno>len(cues):
playlistno = len(cues)
print ("")
print ("Maximum playlists per your text is",len(cues))
except:
if len(cues)>=3:
playlistno = 3
print ("")
print ("Using default value of",playlistno,"playlists")
else:
playlistno = len(cues)
print ("")
print ("Your text contains less than 3 words, I'll search for",playlistno," playlists")
#Split blocks of text in parts based on tracks requested
cues = cuesline.split()
phraseslength = math.floor(len(cues)/playlistno)
cueswords=[]
for index in range(playlistno):
if index + 1 == playlistno:
cueswords.append(' '.join(cues[(index)*phraseslength:]))
break
cueswords.append(' '.join(cues[index*phraseslength:phraseslength*(index+1)]))
Now you may need to authorize this app to access your playlist, your browser will direct you to a new page, copy and paste the URL in the form below
In [3]:
# Connect to Spotify API
client_id='95df4271622e424b84e1dd2a48233907'
client_secret='e81854a1889a4285ab29bf1d41b9009b'
redirect_uri='http://localhost:8888/callback'
scope = 'playlist-modify-public'
class credentials():
def __init__(self,name):
global username
self.username=name
token = util.prompt_for_user_token(self.username, scope,client_id, client_secret,redirect_uri)
self.sp = spotipy.Spotify(auth=token)
username=self.username
credentials("")
token = util.prompt_for_user_token(username,scope,client_id,client_secret,redirect_uri)
In [4]:
#Generate playlist urls
print('')
print("These are my suggested playlists:")
print("")
if token:
sp = spotipy.Spotify(auth=token)
sp.trace = False
for x in range(0,len(cueswords)):
if cueswords[x]=='':
print ("Bummer!. Some playlists were not found!")
break
results = sp.search(q=str(cueswords[x]), limit=1)
if results['tracks']['items']==[]:
print ("Bummer!. Some playlists were not found!")
for i, t in enumerate(results['tracks']['items']):
print(''.join(['Playlist #',str(x+1),':']),t['name'],"@",''.join(["https://open.spotify.com/track/",t['id']]))
else:
print("Can't get token for", username)
print("")
print("You are welcome!")