Better Partying Thru Python

Sergio Lucero
4 min readAug 8, 2019
Solomun @ Espacio Riesco, Halloween 2018

It’s my birthday next week and I’ve decided to throw a proper party. Besides choosing a suitable joint for the shindig, I must procure drinks and music. First part’s easy, second requires talent. I love music and so I spent an hour compiling a funky Spotify playlist which I was convinced would get heads bobbing and hopefully even the most timid of my friends at least looking towards the dancefloor. Additionally, a good friend was hired as a real DJ for the latter part of the evening. My playlist would be the warm-up.

So my principal problem was how to arrange the songs I had picked in order to (i) progressively work up the crowd and (ii) get them ready to be later shaken by someone who truly knows his stuff (a proper DJ). Being a Python-enabled mathematician, I was sure this was just a matter of the right data analysis. Indeed, Spotify has a rich API and a library was available to help me.

Setup: Spotify API credentials + spotipy

As usual with all big services, it’s easy to access your own Spotify data via an API. All you need is to create a Spotify Developer acount and retain the credentials associated to an app. Then install spotipy:

pip install spotipy

to have access to the API without using REST or URLs. You will see what I mean in the next section.

Code it like you mean it

Spotipy easily allows me to access my most recent playlists. All I have to do is save my credentials (CLIENT_ID, CLIENT_SECRET) into a file named creds.py and provide a working URL, (in my case http://quant.cl). When this code is run, a browser will open up and provide the URL to retrieve the token. Code execution continues.

import spotipy
import spotipy.util as util
from creds import CLIENT_ID, CLIENT_SECRET
token = util.prompt_for_user_token(username = 'sergiolucero', scope='',client_id=CLIENT_ID,client_secret=CLIENT_SECRET, redirect_uri='http://quant.cl/')sp = spotipy.Spotify(auth=token)
sp.trace = False
results = sp.current_user_playlists(limit=5)
for i, item in enumerate(results['items']):
print("%d %s" %(i, item['name']))

https://gist.github.com/sergiolucero/f4a5629b512bfe9c66c777f3000bf821#gistcomment-2992969

Once this code is run, I will have an authorized Spotify API instance (in sp), which we will use from now on. For every playlist I can obtain generous info about every song (we’re using pandas for convenience):

import pandas as pdplaylist = results['items'][0]   # focusing on the first playlist
names = [t['track']['name'] for t in playlist]
uris = [t['track']['uri'] for t in playlist]
ids = [t['track']['id'] for t in playlist]
artists = [t['track']['artists'][0]['name'] for t in playlist]
durations = [t['track']['duration_ms']/60000 for t in playlist]
pdf = pd.DataFrame(dict(trackname=names, artist=artists,
duration=durations,uri=uris,id=ids))
pdf.head(5).round(2)
first five songs

In this simple process, we have obtained track name, artist, track duration in minutes, and the uri and Spotify id for every track on the playlist.

Obtaining further info

Scores for danceability, energy, tone and even tempo in beats per minute (bpm) are available for every song. I can’t say I agree that the great track by Bomba Estéreo is not as danceable as others, but hey! Your mileage may very well vary.

Building a smooth transition order

OK, so by now we know which track is the least and most “danceable” in my playlist, according to Spotify’s algorithms. But how to choose the order in which the tracks are followed? A smooth path from the least to the most danceable song can be constructed, by evolving from A to B in a multidimensional space, according to some criterion such as

(i) maintain tempo (bpm), tone, danceability

(ii) least variation in some combination of the above (vector norm)

I have chosen to minimize variation of an equal combination of danceability, bpm and tone.

Let’s visualize it!

How can we plot the path we have followed? Pick two dimensions and create a scatterplot, then trace the path between tracks.

A full video can be seen here http://quant.cl/static/rosita.avi

Incidentally, my relationship with the world of data (YouTube, Soundcloud, etc) provided me with a great punchline for this big joke. Just this week I was introduced by YouTube to the work of … DJ Python! His first track (and many others) grace my birthday playlist, which I’m glad to share with you all here.

--

--

Sergio Lucero

eclectic mathematician pythonista indie foodie consultant. Developing Web services for a living from quant.cl