Skip to content

Instantly share code, notes, and snippets.

@musantro
Last active October 26, 2023 18:46
Show Gist options
  • Save musantro/64ebabac46165ca242f6ceb2deff5ded to your computer and use it in GitHub Desktop.
Save musantro/64ebabac46165ca242f6ceb2deff5ded to your computer and use it in GitHub Desktop.
How to be the nerdiest, coolest DJ at your party
# This script sorts your playlist into a new playlist by energy and danceability, two features given by Spotify.
# More info here https://developer.spotify.com/documentation/web-api/reference/get-several-audio-features
# STEP 0: pip install spotipy
# STEP 1: Create an Spotify Developer APP here https://developer.spotify.com/dashboard/create and create an API
# Input Variables - Fill these out and run
YOUR_APP_CLIENT_ID = "YOUR_APP_CLIENT_ID"
YOUR_APP_CLIENT_SECRET = "YOUR_APP_CLIENT_SECRET"
YOUR_APP_REDIRECT_URI = "http://localhost/"
ORIGINAL_PLAYLIST_ID = "YOUR_PLAYLIST_ID"
# Libraries
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# Authentication
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-public playlist-read-private"))
# Fetch ALL track IDs from the original playlist
track_ids = []
track_info = []
offset = 0
while True:
results = sp.playlist_tracks(ORIGINAL_PLAYLIST_ID, offset=offset)
if not results['items']:
break
for item in results['items']:
track = item['track']
track_ids.append(track['id'])
track_info.append({
'track_id': track['id'],
'song_name': track['name'],
'artist': track['artists'][0]['name']
})
offset += len(results['items'])
# Fetch audio features for each track in chunks of 100
all_track_features = []
for i in range(0, len(track_ids), 100):
chunk = track_ids[i:i+100]
features = sp.audio_features(chunk)
all_track_features.extend(features)
# Add 'energy' and 'danceability' to track_info
for i, features in enumerate(all_track_features):
track_info[i]['energy'] = features['energy']
track_info[i]['danceability'] = features['danceability']
# Sort track_info based on the sum of 'energy' and 'danceability'
track_info.sort(key=lambda x: x['energy'] + x['danceability'])
# List of track_ids in the new order
ordered_track_ids = [track['track_id'] for track in track_info]
# Create a new playlist
user_id = sp.me()['id']
new_playlist = sp.user_playlist_create(user_id, "Sorted Playlist by Energy + Danceability")
# Add the sorted tracks to the new playlist in chunks of 100
new_playlist_id = new_playlist['id']
for i in range(0, len(ordered_track_ids), 100):
chunk = ordered_track_ids[i:i+100]
sp.playlist_add_items(new_playlist_id, chunk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment