Unlock Your Unique Playlist: Personalized Song Recommendations Using Spotify API
Last Updated on February 13, 2024 by Editorial Team
Author(s): Sarvesh Talele
Originally published on Towards AI.
Have you ever been frustrated by the recommendations because you were so focused on choosing the perfect playlist? In that case, you are not alone. Looking through the vast array of songs and playlists on the many music streaming services available today to find what resonates with you could be frightening. But fear not β thanks to machine learning, we can now discover the key to creating a personalized playlist that appeals to your unique musical taste. To be more precise, weβre going to develop a customized hybrid and content-based recommendation system. By scraping the whole Spotify database and selecting the songs that best suit our taste in music, this machine-learning model will make song recommendations based on our playlist using Spotify API.
Access the Complete Code below given link-
GitHub – Wyverical/Music-Recommendation-System-using-Spotify-API
Contribute to Wyverical/Music-Recommendation-System-using-Spotify-API development by creating an account on GitHub.
github.com
Setting the stage
It would be more interesting to explore the recommendation systemβs outcomes rather than provide a step-by-step explanation of the code. Though the blog would simply go over some basic algorithmic theory and code snippets, letβs analyze our model using the data. Weβll explore the realm of music recommendation systems, where computers create personalized playlists based on your listening tastes, habits, and even the qualities of specific songs. Weβll look at how to use machine learning methods and the Spotify API to make customized music recommendations based on your favorite songs.
Demo Video:
Getting Started
We'll need to start our voyage by browsing the enormous selection of music on Spotify. We can access comprehensive data on millions of songs, such as their audio characteristics, popularity rankings, release dates, and more, with the use of the Spotify API. With the use of sophisticated algorithms and this abundance of data, we can find hidden links and patterns in the song content to provide insightful recommendations. The Python libraries listed below are the ones that we would need to install in order to create our ideal playlist.
import requests
import base64
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime
from sklearn.metrics.pairwise import cosine_similarity
import ipywidgets as widgets
from IPython.display import display, clear_output
import spotipy
from spotipy.oauth2 import SpotifyOAuth
Exploring Your Playlist
Letβs continue exploring a curated playlist on Spotify and collecting crucial insights about the songs it contains. Using the Spotify API, we can obtain information about each song in the playlist, such as the title of the track, the artist, the album, the popularity rating, the release date, and more audio characteristics. With this knowledge in hand, we may go deeper into the musical landscape and uncover hidden gems. The code that follows includes your unique playlist ID. For example, if your playlist URL is https://open.spotify.com/playlist/0zQTiQxLOgnsLg7drurLig, then your playlist ID is 0zQTiQxLOgnsLg7drurLig.
playlist_id = '0zQTiQxLOgnsLg7drurLig'
song_df = playlist_data(playlist_id, access_token)
Analyzing the Data
Itβs time to get in and truly get our hands cluttered with some analysis now that weβve gathered all the data from our playlist! Assume that we are delving deeply into the world of music while donning our detective caps. Letβs start by looking at the fascinating correlation between a songβs duration and popularity. To display this, weβll use Line plot, which are similar to putting Line on a map to identify potentially intriguing pathways. Next, weβll go further into the tracks, analyzing their danceability, intensity, and acoustic quality. Itβs similar to cutting through the layers of a musical orange to reveal the distinct tastes and sensations that are concealed in every track. So fasten your seatbelts and get ready for a musical journey like no other.
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.scatter(data['Popularity'], data['Duration (ms)'], s=50, alpha=0.8, color='skyblue', edgecolors='k')
plt.title('Popularity vs Duration', fontsize=16)
plt.xlabel('Popularity', fontsize=14)
plt.ylabel('Duration (ms)', fontsize=14)
plt.grid(True, linestyle='--', alpha=0.6)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.show()
Personalized Recommendations
Now comes the exciting partβgenerating personalized song recommendations based on your favorite tracks. We can find songs that not only suit musical preferences but also have resonance with the current trends and popularity scores by combining popularity-based weighting and content-based filtering, resulting in a hybrid recommendation system.
import ipywidgets as widgets
from IPython.display import display, clear_output
track_names = song_df['Track Name'].unique().tolist()
track_names.insert(0, "Select song from dropdown")
def update_recommendations(change):
clear_output()
input_song = change.new
recommendations = hybrid_recommendations(input_song, num_of_recom=5)
print(f"Hybrid recommended songs for '{input_song}':")
display(HTML(recommendations.to_html(index=False)))
dropdown = widgets.Dropdown(
options=track_names,
description='Track Name:',
disabled=False,
)
dropdown.observe(update_recommendations, names='value')
display(dropdown)
Conclusion
In conclusion, the process of making your own playlist is fascinating and exciting. Through the use of data analytics and machine learning, we may access a vast music library customized to suit our unique interests and inclinations. Thus, instead of settling for pre-made playlists, why not create your own musical journey? The soundtrack to your life may be found with only a click, thanks to our unique suggestion system. Enjoy your audio!
Reference Links
- Cosine Similarity : https://www.youtube.com/watch?v=e9U0QAFbfLI&t=69s&ab_channel=StatQuestwithJoshStarmer
- Spotify API Documentation: https://developer.spotify.com/documentation/web-api
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming aΒ sponsor.
Published via Towards AI