Building a Personalized Music Recommendation System with Spotify API and Python

Eren jade - Sep 2 - - Dev Community

Spotify Premium has revolutionized how we listen to music, offering personalized playlists, ad-free streaming, and the ability to download music for offline listening. But have you ever wondered how Spotify tailors these music recommendations just for you? In this article, we'll explore how to build a simple personalized music recommendation system using Spotify's API and Python. We'll dive into the basics of working with the Spotify API, retrieving user data, and creating a custom playlist based on a user's listening habits.

Setting Up the Environment

Before we start coding, let's set up our environment. You'll need Python installed on your machine, along with the spotipy library, which is a lightweight Python library for the Spotify Web API. Install it using pip:

pip install spotipy

Additionally, you'll need to register your application on the Spotify Developer Dashboard to get your client ID and secret.

Authenticating with the Spotify API

First, we need to authenticate with the Spotify API. Here's a simple function to do that:

`import spotipy
from spotipy.oauth2 import SpotifyOAuth

Replace these with your own credentials

SPOTIPY_CLIENT_ID = 'your-client-id'
SPOTIPY_CLIENT_SECRET = 'your-client-secret'
SPOTIPY_REDIRECT_URI = 'http://localhost:8888/callback/'

Authentication

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope="user-library-read user-top-read playlist-modify-public"))`

This code snippet will handle the authentication process, allowing us to interact with the Spotify API using our Python scripts.

Retrieving User Data

To create a personalized music recommendation system, we'll need to retrieve data about the user's listening habits. Specifically, we'll fetch the user's top tracks and artists:

`def get_top_tracks(sp, time_range='medium_term', limit=20):
results = sp.current_user_top_tracks(time_range=time_range, limit=limit)
top_tracks = [track['id'] for track in results['items']]
return top_tracks

def get_top_artists(sp, time_range='medium_term', limit=10):
results = sp.current_user_top_artists(time_range=time_range, limit=limit)
top_artists = [artist['id'] for artist in results['items']]
return top_artists`

Here, time_range can be 'short_term', 'medium_term', or 'long_term', which correspond to the last 4 weeks, 6 months, and several years, respectively. The limit parameter specifies how many tracks or artists to retrieve.

Generating Recommendations

With the top tracks and artists, we can now generate recommendations. Spotify's API allows you to get recommendations based on seed tracks, seed artists, and seed genres. Here's how you can use it:

def get_recommendations(sp, seed_tracks, seed_artists, limit=20):
recommendations = sp.recommendations(seed_tracks=seed_tracks[:5],
seed_artists=seed_artists[:5],
limit=limit)
recommended_tracks = [track['id'] for track in recommendations['tracks']]
return recommended_tracks

This function uses up to 5 seed tracks and artists to generate a list of recommended tracks. You can tweak the limit parameter to control how many recommendations you get.

Creating a Playlist

Finally, let's create a playlist with these recommendations. We'll use the Spotify API to create a new playlist and add the recommended tracks to it:

`def create_playlist(sp, user_id, name, track_ids):
playlist = sp.user_playlist_create(user_id, name, public=True)
sp.playlist_add_items(playlist['id'], track_ids)
print(f"Playlist '{name}' created successfully!")

Example usage

user_id = sp.current_user()['id']
top_tracks = get_top_tracks(sp)
top_artists = get_top_artists(sp)
recommended_tracks = get_recommendations(sp, top_tracks, top_artists)

create_playlist(sp, user_id, "My Custom Recommendations", recommended_tracks)`

This function will create a new playlist in the userโ€™s account and add the recommended tracks to it. Just like that, youโ€™ve built a personalized music recommendation system!

Conclusion

Spotify Premium offers an incredible platform for music lovers, and with the power of Spotify's API, developers can create unique and personalized experiences for users. Whether you're looking to build a simple recommendation system or a more complex music analysis tool, the possibilities are endless.

For more in-depth guides and resources on Spotify Premium, check out Spotify Premium APK. Dive into the world of music and start creating your own custom playlists today!

.
Terabox Video Player