Skip to content

Commit 51c5bd8

Browse files
Advanced examples (#986)
* Created a testing suite for the spotipy client.Spotify class * Delete pyvenv.cfg * Corrected error in description * Added some advanced usage examples, some of which involve utilizing basic data analysis methods using other libraries such as Pandas * Minor formatting fixes --------- Co-authored-by: Stéphane Bruckert <[email protected]>
1 parent 1e05bdb commit 51c5bd8

4 files changed

+132
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Add your changes below.
1616
- Added test_artist_id, test_artist_url, and test_artists_mixed_ids to non_user_endpoints test.py
1717
- Added rate/request limit to FAQ
1818
- Added custom `urllib3.Retry` class for printing a warning when a rate/request limit is reached.
19+
- Added `personalized_playlist.py`, `track_recommendations.py`, and `audio_features_analysis.py` to `/examples`.
1920

2021
### Fixed
2122
- Audiobook integration tests

examples/audio_features_analysis.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import spotipy
2+
from spotipy.oauth2 import SpotifyClientCredentials
3+
4+
# Import the extra necessary libraries for this example
5+
# These libraries are not included in the default packages
6+
import pandas as pd
7+
import matplotlib.pyplot as plt
8+
import seaborn as sns
9+
10+
# Set up Spotify credentials
11+
client_credentials_manager = SpotifyClientCredentials()
12+
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
13+
14+
# Fetch audio features of tracks from any playlist
15+
playlist_id = '37i9dQZEVXbMDoHDwVN2tF'
16+
results = sp.playlist_tracks(playlist_id)
17+
tracks = results['items']
18+
track_ids = [track['track']['id'] for track in tracks]
19+
audio_features = sp.audio_features(track_ids)
20+
21+
# Create a DataFrame of audio features
22+
df = pd.DataFrame(audio_features)
23+
df = df[['danceability', 'energy', 'speechiness', 'acousticness',
24+
'instrumentalness', 'liveness', 'valence', 'tempo']]
25+
26+
# Generate a correlation matrix
27+
correlation_matrix = df.corr()
28+
29+
# Plot the correlation matrix using seaborn
30+
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm')
31+
32+
# Show the plot
33+
plt.show()

examples/personalized_playlist.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import spotipy
2+
from spotipy.oauth2 import SpotifyOAuth
3+
4+
# Import the extra necessary libraries for this example
5+
# These libraries are not included in the default packages
6+
import pandas as pd
7+
from sklearn.cluster import KMeans
8+
9+
# Set up Spotify credentials
10+
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
11+
client_id="YOUR_APP_CLIENT_ID",
12+
client_secret="YOUR_APP_CLIENT_SECRET",
13+
redirect_uri="YOUR_APP_REDIRECT_URI",
14+
scope="playlist-modify-private,user-library-read"))
15+
16+
17+
# get the user's username
18+
username = sp.me()['id']
19+
20+
# Get the user's liked tracks
21+
saved_tracks = sp.current_user_saved_tracks(limit=50)['items']
22+
23+
# Extract audio features for liked tracks
24+
track_ids = []
25+
audio_features = []
26+
for track in saved_tracks:
27+
track_ids.append(track['track']['id'])
28+
audio_features.append(sp.audio_features(track['track']['id'])[0])
29+
30+
# Create a DataFrame from the audio features
31+
df = pd.DataFrame(audio_features)
32+
33+
# Perform clustering on some audio features
34+
features = df[['danceability', 'energy', 'valence', 'acousticness']]
35+
kmeans = KMeans(n_clusters=5, random_state=42, n_init=10)
36+
df['cluster'] = kmeans.fit_predict(features)
37+
38+
# Select a representative track from each cluster
39+
representative_tracks = []
40+
for cluster in range(5):
41+
cluster_tracks = df[df['cluster'] == cluster]
42+
representative_track = cluster_tracks.iloc[0]['id']
43+
representative_tracks.append(representative_track)
44+
45+
# Create a playlist with the representative tracks
46+
playlist = sp.user_playlist_create(
47+
user=username, name='Personalized Playlist', public=False)
48+
sp.playlist_add_items(
49+
playlist_id=playlist['id'], items=representative_tracks)
50+
51+
# Print the URL of the created playlist
52+
print("Playlist created successfully. You can access it at:",
53+
playlist['external_urls']['spotify'])

examples/track_recommendations.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import spotipy
2+
from spotipy.oauth2 import SpotifyOAuth
3+
import random
4+
5+
# Set up Spotify credentials
6+
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
7+
client_id="YOUR_APP_CLIENT_ID",
8+
client_secret="YOUR_APP_CLIENT_SECRET",
9+
redirect_uri="YOUR_APP_REDIRECT_URI",
10+
scope="user-top-read,user-library-read,user-read-recently-played"))
11+
12+
# Get the user's top tracks
13+
top_tracks = sp.current_user_top_tracks(limit=10, time_range='long_term')
14+
15+
# Get the user's liked tracks
16+
liked_tracks = sp.current_user_saved_tracks(limit=10)
17+
18+
# Get the user's listening history
19+
history = sp.current_user_recently_played(limit=10)
20+
21+
# Extract a list of the top track IDs
22+
top_track_ids = [track['id'] for track in top_tracks['items']]
23+
24+
# Extract a list of the liked track IDs
25+
liked_track_ids = [track['track']['id'] for track in liked_tracks['items']]
26+
27+
# Extract a list of the history track IDs
28+
history_track_ids = [track['track']['id'] for track in history['items']]
29+
30+
# Combine the three lists and shuffle them randomly
31+
seed_track_ids = top_track_ids + liked_track_ids + history_track_ids
32+
random.shuffle(seed_track_ids)
33+
34+
# Use the IDs to get some recommendations
35+
# Note: the seed_tracks parameter can accept up to 5 tracks
36+
recommendations = sp.recommendations(
37+
seed_tracks=seed_track_ids[0:5], limit=10, country='US')
38+
39+
# Display the recommendations
40+
for i, track in enumerate(recommendations['tracks']):
41+
print(
42+
"{}. {} by {}"
43+
.format(i+1, track['name'], ', '
44+
.join([artist['name'] for artist in track['artists']]))
45+
)

0 commit comments

Comments
 (0)