Python Music Recommender: A Practical Guide Part-4

Python Music Recommender: A Practical Guide Part-4

Building a web-app using Streamlit.

In this tutorial, we will learn how to build a simple music recommendation system using Streamlit and the Spotify API.

Streamlit is a Python framework that allows you to quickly create web applications. With Streamlit, you can create interactive dashboards, data visualizations, and more. The Spotify API is a powerful tool that allows you to access the Spotify music catalog and retrieve information about tracks, albums, artists, and more.


Building the app

Before building the app, install the Streamlit library

pip install streamlit

Now that we have our credentials set up and our libraries installed, we can start building our music recommendation system. Create a new Python file. Let’s call it app.py.

First, we need to import the necessary libraries and set up our Spotify API credentials:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import requests

from streamlit_lottie import st_lottie
# Getting Client Id and Client Secret
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
auth_manage = SpotifyClientCredentials(client_id = client_id, client_secret = client_secret)
sp = spotipy.Spotify(client_credentials_manager = auth_manage) # Spotify object to access API

Note: Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your API credentials.

Defining Functions

Now, let’s define a function load_musicurl that will help us to extract the image URL from LottieFiles:

def load_musicurl(url: str):
    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.json()

The second function be defined as get_recommendation that takes a song name as input and returns a list of recommended songs:

def get_recommendations(track_name):
    # Getring track URI
    results = sp.search(q = track_name, type = "track")
    track_uri = results["tracks"]["items"][0]["uri"]

    # Get recommended tracks
    recommendations = sp.recommendations(seed_tracks = [track_uri], limit = 10)["tracks"]
    return recommendations

What is the aim of this function? You might ask.

This function takes a song name as input, searches for the corresponding track URI using the Spotify API, and then uses that URI to retrieve a list of recommended tracks.

Third and the last one will be get_analysis. This function will return the analysis of the year range that would be selected by the user.

You could refer to this file on my GitHub as it's a long code and it will not look good if write it here.


We can create our Streamlit app. In the same app.py file, add the following code:

Read the Streamlit documentation to learn how to use it.

# Creating Streamlit App
def main():

    ##==============================
    ## Get Song Recommendation
    ##==============================

    lottie_music = load_musicurl("https://lottie.host/96ee915d-6c68-4989-9415-49c4396a1a4a/eH1LnsMXmA.json")
    st_lottie(lottie_music, speed=1, height=200, key="initial")

    row0_1, row0_2= st.columns((2, 1))
    row0_1.title("Music Recommendation System")

    row0_2.subheader(
        "A music recommendation web app by Vineet Singh Negi"
        )

    st.markdown(
        "The algorithm doesn't get you, we get that a lot. Maybe you want to rediscover\
        some new songs as per your music taste. Or maybe you you want top songs from school days and\
        don't want to mess with making your own playlist."
    )
    st.markdown(
        "**TO GET SONG RECOMMENDATION.** 👇"
        )

    track_name = st.text_input("Enter the song name:")

    if st.button("Get Recommendations"):
        recommendations = get_recommendations(track_name)

        if recommendations is not None:
            st.write("Recommended Songs Are:")
            for track in recommendations:
                st.write(track["name"])
                track_image = track["album"]["images"][0]["url"]
                st.image(track_image, width = 60)

        else:
            st.error("No such song exists")

    st.markdown("")
    st.markdown("")

    ##==============================
    ## Get Top Singles Playlist
    ##==============================
    st.markdown("**You can use this tool to find a pre-generated playlist of English songs that made\
                the Top 10 for the years you select.**")

    df = pd.read_csv("playlists.csv")
    years = list(range(1958, 2022))

    year_range = st.slider(label="Start Year", 
                        min_value=1958, 
                        max_value=2022, 
                        value=(1995, 2010))


    if st.button('Get Playlist'):
        if (int(year_range[0]) - int(year_range[1])) == 0:
            playlist_name = f"Top Singles: {year_range[0]}"
        else:
            playlist_name = f"Top Singles: {year_range[0]} - {year_range[1]}"

        if df[df['name'] == playlist_name].shape[0] > 0:
            playlist = df[df['name'] == playlist_name].to_dict(orient='records')[0]
        else:
            playlist = "Ooops, it looks like we didn't make that playlist yet. Playlists with a range of 1-20 years were created. Try again with a more narrow year range."

        if isinstance(playlist, dict):
            link = f"#### Your Spotify Playlist: [{playlist['name']}]({playlist['link']})"
            st.markdown(link, unsafe_allow_html=True)
            get_analysis(year_range[0], year_range[1])

        else:
            st.markdown(playlist)


if __name__ == "__main__":
    main()

And that’s it! We have created a simple music recommendation system that allows users to enter a track name and receive a list of recommended tracks based on their input.


So in this tutorial, we learned how we can run any Python code using the Streamlit library.

Do look out for the upcoming Part 5, which will be the last part of this whole project in which I will be containerizing this application using Docker.

Until then take care, Happy Learning!

Thanks for Reading!