mirror of
https://github.com/spotipy-dev/spotipy.git
synced 2026-06-19 01:03:53 +00:00
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 <stephane.bruckert@gmail.com>
This commit is contained in:
parent
1e05bdba67
commit
51c5bd8d7d
@ -16,6 +16,7 @@ Add your changes below.
|
||||
- Added test_artist_id, test_artist_url, and test_artists_mixed_ids to non_user_endpoints test.py
|
||||
- Added rate/request limit to FAQ
|
||||
- Added custom `urllib3.Retry` class for printing a warning when a rate/request limit is reached.
|
||||
- Added `personalized_playlist.py`, `track_recommendations.py`, and `audio_features_analysis.py` to `/examples`.
|
||||
|
||||
### Fixed
|
||||
- Audiobook integration tests
|
||||
|
||||
33
examples/audio_features_analysis.py
Normal file
33
examples/audio_features_analysis.py
Normal file
@ -0,0 +1,33 @@
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
# Import the extra necessary libraries for this example
|
||||
# These libraries are not included in the default packages
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
|
||||
# Set up Spotify credentials
|
||||
client_credentials_manager = SpotifyClientCredentials()
|
||||
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
|
||||
|
||||
# Fetch audio features of tracks from any playlist
|
||||
playlist_id = '37i9dQZEVXbMDoHDwVN2tF'
|
||||
results = sp.playlist_tracks(playlist_id)
|
||||
tracks = results['items']
|
||||
track_ids = [track['track']['id'] for track in tracks]
|
||||
audio_features = sp.audio_features(track_ids)
|
||||
|
||||
# Create a DataFrame of audio features
|
||||
df = pd.DataFrame(audio_features)
|
||||
df = df[['danceability', 'energy', 'speechiness', 'acousticness',
|
||||
'instrumentalness', 'liveness', 'valence', 'tempo']]
|
||||
|
||||
# Generate a correlation matrix
|
||||
correlation_matrix = df.corr()
|
||||
|
||||
# Plot the correlation matrix using seaborn
|
||||
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm')
|
||||
|
||||
# Show the plot
|
||||
plt.show()
|
||||
53
examples/personalized_playlist.py
Normal file
53
examples/personalized_playlist.py
Normal file
@ -0,0 +1,53 @@
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
# Import the extra necessary libraries for this example
|
||||
# These libraries are not included in the default packages
|
||||
import pandas as pd
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
# Set up Spotify credentials
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
|
||||
client_id="YOUR_APP_CLIENT_ID",
|
||||
client_secret="YOUR_APP_CLIENT_SECRET",
|
||||
redirect_uri="YOUR_APP_REDIRECT_URI",
|
||||
scope="playlist-modify-private,user-library-read"))
|
||||
|
||||
|
||||
# get the user's username
|
||||
username = sp.me()['id']
|
||||
|
||||
# Get the user's liked tracks
|
||||
saved_tracks = sp.current_user_saved_tracks(limit=50)['items']
|
||||
|
||||
# Extract audio features for liked tracks
|
||||
track_ids = []
|
||||
audio_features = []
|
||||
for track in saved_tracks:
|
||||
track_ids.append(track['track']['id'])
|
||||
audio_features.append(sp.audio_features(track['track']['id'])[0])
|
||||
|
||||
# Create a DataFrame from the audio features
|
||||
df = pd.DataFrame(audio_features)
|
||||
|
||||
# Perform clustering on some audio features
|
||||
features = df[['danceability', 'energy', 'valence', 'acousticness']]
|
||||
kmeans = KMeans(n_clusters=5, random_state=42, n_init=10)
|
||||
df['cluster'] = kmeans.fit_predict(features)
|
||||
|
||||
# Select a representative track from each cluster
|
||||
representative_tracks = []
|
||||
for cluster in range(5):
|
||||
cluster_tracks = df[df['cluster'] == cluster]
|
||||
representative_track = cluster_tracks.iloc[0]['id']
|
||||
representative_tracks.append(representative_track)
|
||||
|
||||
# Create a playlist with the representative tracks
|
||||
playlist = sp.user_playlist_create(
|
||||
user=username, name='Personalized Playlist', public=False)
|
||||
sp.playlist_add_items(
|
||||
playlist_id=playlist['id'], items=representative_tracks)
|
||||
|
||||
# Print the URL of the created playlist
|
||||
print("Playlist created successfully. You can access it at:",
|
||||
playlist['external_urls']['spotify'])
|
||||
45
examples/track_recommendations.py
Normal file
45
examples/track_recommendations.py
Normal file
@ -0,0 +1,45 @@
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
import random
|
||||
|
||||
# Set up Spotify credentials
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
|
||||
client_id="YOUR_APP_CLIENT_ID",
|
||||
client_secret="YOUR_APP_CLIENT_SECRET",
|
||||
redirect_uri="YOUR_APP_REDIRECT_URI",
|
||||
scope="user-top-read,user-library-read,user-read-recently-played"))
|
||||
|
||||
# Get the user's top tracks
|
||||
top_tracks = sp.current_user_top_tracks(limit=10, time_range='long_term')
|
||||
|
||||
# Get the user's liked tracks
|
||||
liked_tracks = sp.current_user_saved_tracks(limit=10)
|
||||
|
||||
# Get the user's listening history
|
||||
history = sp.current_user_recently_played(limit=10)
|
||||
|
||||
# Extract a list of the top track IDs
|
||||
top_track_ids = [track['id'] for track in top_tracks['items']]
|
||||
|
||||
# Extract a list of the liked track IDs
|
||||
liked_track_ids = [track['track']['id'] for track in liked_tracks['items']]
|
||||
|
||||
# Extract a list of the history track IDs
|
||||
history_track_ids = [track['track']['id'] for track in history['items']]
|
||||
|
||||
# Combine the three lists and shuffle them randomly
|
||||
seed_track_ids = top_track_ids + liked_track_ids + history_track_ids
|
||||
random.shuffle(seed_track_ids)
|
||||
|
||||
# Use the IDs to get some recommendations
|
||||
# Note: the seed_tracks parameter can accept up to 5 tracks
|
||||
recommendations = sp.recommendations(
|
||||
seed_tracks=seed_track_ids[0:5], limit=10, country='US')
|
||||
|
||||
# Display the recommendations
|
||||
for i, track in enumerate(recommendations['tracks']):
|
||||
print(
|
||||
"{}. {} by {}"
|
||||
.format(i+1, track['name'], ', '
|
||||
.join([artist['name'] for artist in track['artists']]))
|
||||
)
|
||||
Loading…
Reference in New Issue
Block a user