Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import spotipy
- from spotipy.oauth2 import SpotifyOAuth
- # Authentication - Replace with your Spotify Developer credentials
- sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
- client_id='insert your client id here',
- client_secret='insert your secret here',
- redirect_uri='http://localhost:8888/callback',
- scope='playlist-modify-private playlist-modify-public playlist-read-private'))
- # Playlist ID, keyword, and minimum track length in seconds
- playlist_id = 'insert your playlist id here'
- keyword = 'your keyword here' # Leave as an empty string if you want to ignore the keyword filter
- min_length_seconds = 60 # Minimum length of 60 seconds
- # Convert minimum length to milliseconds
- min_length_ms = min_length_seconds * 1000
- # Function to get all tracks from a playlist (handles pagination)
- def get_all_tracks(playlist_id):
- tracks = []
- results = sp.playlist_tracks(playlist_id)
- tracks.extend(results['items'])
- while results['next']:
- results = sp.next(results)
- tracks.extend(results['items'])
- return tracks
- # Function to remove tracks in batches
- def remove_tracks_in_batches(playlist_id, tracks_to_remove, batch_size=100):
- for i in range(0, len(tracks_to_remove), batch_size):
- batch = tracks_to_remove[i:i + batch_size]
- sp.playlist_remove_specific_occurrences_of_items(playlist_id, batch)
- # Get all tracks in the playlist
- tracks = get_all_tracks(playlist_id)
- # Find tracks to remove
- tracks_to_remove = []
- for item in tracks:
- track = item['track']
- # Check if keyword is present in the track name or keyword is empty
- if (keyword == '' or keyword.lower() in track['name'].lower()) or track['duration_ms'] <= min_length_ms:
- tracks_to_remove.append({'uri': track['uri'], 'positions': [item['track']['track_number']-1]})
- # Remove tracks from playlist in batches
- if tracks_to_remove:
- remove_tracks_in_batches(playlist_id, tracks_to_remove)
- print(f"Removed {len(tracks_to_remove)} tracks containing the keyword '{keyword}' and shorter than {min_length_seconds} seconds from the playlist.")
- else:
- print(f"No tracks found containing the keyword '{keyword}' and shorter than {min_length_seconds} seconds.")
- # Debugging: Print track names that were not removed but match the criteria
- remaining_tracks = get_all_tracks(playlist_id)
- for item in remaining_tracks:
- track = item['track']
- if (keyword == '' or keyword.lower() in track['name'].lower()) and track['duration_ms'] >= min_length_ms:
- print(f"Track not removed: {track['name']}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement