The world’s leading publication for data science, AI, and ML professionals.

Deploying a Spotify Recommendation Model with Flask

A quick and easy way to take your model from a HitHub repo to the real world

The real value of machine learning models lies in their usability. If the model is not properly deployed, used, and continuously updated through cycles of customer feedback, it is doomed to stay in a GitHub repository, never reaching its actual potential. In this article, we will learn how to deploy a Spotify Recommendation Model in Flask in a few simple steps.

The application we will deploy is stored in a recommendation_app folder. Its structure is shown below:

wsgi.py
requirements.txt
data/
application/
   model.py
   features.py
   templates/
      home.html
      results.html
      about.html
   static/
      style.css
   routes.py

In the root directory, we have the wsgi.py file which will be called when we run ‘$ flask run app’ in the terminal – it calls the create_app() function which creates our server on localhost. Requirements.txt contains the dependencies needed for our project to run in another requirement. The data folder contains the data required for the model to recommend songs.

The application folder contains the main components of our flask application. The first component we need is, obviously, a model itself. Here, we will use a Spotify Recommendation model that, given a Spotify playlist, recommends a number of songs that would fit into this playlist based on audio features retrieved from spotipy library. If you are interested in how to retrieve relevant data for such a model, perform clustering based on the audio features and develop a recommendation model, feel free to check out the following articles in this series:

Furthermore, we will need a function that converts a Spotify playlist link into a pandas dataframe that contains relevant features based on which the recommendations will be done – in our case it is stored in features.py file. Shortly, the function takes a link that can be taken from a desktop Spotify application and consecutively splits it to obtain a combination of letters and numbers that constitute a playlist ID. Finally, by using a ‘user_playlist’ function from spotipy library, and a series of dictionary manipulations, the function creates a final dataframe.

Finally, it’s time to create a simple flask application!

The simplest form of a flask application consists of two folders – templates and static, and a python file that contains the routes of our application. The former folder contains HTML templates that will be rendered when the user inputs data and the latter contains a CSS file with simple stylings. The routes file will contain three routes :

@app.route("/")
def home():
   return render_template('home.html')
@app.route("/about")
def about():
   return render_template('about.html')
@app.route('/recommend', methods=['POST'])
def recommend():
   URL = request.form['URL']
   df = extract(URL)
   edm_top40 = recommend_from_playlist(songDF, complete_feature_set,       df)
   number_of_recs = int(request.form['number-of-recs'])
my_songs = []
   for i in range(number_of_recs):
my_songs.append([str(edm_top40.iloc[i,1]) + ' - '+ '"'+str(edm_top40.iloc[i,4])+'"', "https://open.spotify.com/track/"+ str(edm_top40.iloc[i,-6]).split("/")[-1]])
   return render_template('results.html',songs= my_songs)
  • The home route (‘/’) where the user will end up when they open the app;
  • The recommendation route (‘/recommend) will handle input from the form and send a list of recommended songs back to the user;
  • The information route (‘/about’) which will contain basic information about the project;

What exactly does the recommend() function do?

  • Firstly, it takes the URL from the user’s input from an HTML form through a POST request;
  • It calls the extract() function which converts a URL into a dataframe of audio features;
  • It calls the recommend_from_playlist() function creates a dataframe of recommended songs based on the user’s playlist;
  • It requests the number of recommendations the user wants based on the value chosen in a dropdown menu through a POST request;
  • It creates an empty list and fills it with x recommended songs, where x is the chosen number of recommendations;
  • Finally, it renders the results.html template that takes my_songs list as an input and outputs song recommendations for the user;

To make the application look presentable, we will use Bootstrap which contains a variety of elements one can reuse such as buttons, headers, forms, etc. In my case, I used the bootstrap for the header, ‘About’ and ‘Home’ buttons. Furthermore, to make the recommendations appear gradually, I used the keyframes tag in CSS which provides some animation functionality.

@keyframes fastSlide {
0%   { transform: translate(120%) skewX(0deg) ; }
70%  { transform: translate(0%)   skewX(1deg) ; }
80%  { transform: translate(0%)   skewX(0deg)  ; }
95%  { transform: translate(0%)   skewX(0deg) ; }
100% { transform: translate(0%)   skewX(0deg)   ; }
}

For instance, this allowed me to make the recommendations appear gradually from the right side of the screen.

To run our recommendation app locally, we can run ‘$ python wsgi.py’ in the root directory – this will ensure that the server is in development mode and we can debug it and refresh it while making any changes.

Image by Author.
Image by Author.
Image by Author.
Image by Author.

As we can see, the app is functioning properly and a set of recommendations is returned based on the playlist link and the number of recommendations a user is choosing. However, we are not done yet! What if we want someone to use our app without having to install all of the folders locally?

This is where cloud Deployment comes in! There is a variety of services that can help one deploy their app but in this article, we will use Pythonanywhere.com which has a free trial and affordable options for larger applications. All we need to do is to create a beginner account, create an appropriate folder structure and upload all of our files there. In my case, I followed a tutorial by Sohan Dillikar on How to Host Your Flask App on PythonAnywhere for Free – in my case though, instead of using the requirements.txt file, I created a virtual environment and installed packages using the following tutorial.

And voilà we have a functioning website with our application, ready to be used and showcased to potential employers:

Easy, right?


Related Articles