From d319c6e09ff4936b5a6867050fe7f896c70c0b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Bruckert?= Date: Sun, 19 Jan 2025 17:21:18 +0000 Subject: [PATCH] Move examples to spotipy-dev/spotipy-examples, add as submodule --- .gitmodules | 3 + FAQ.md | 4 +- docs/index.rst | 4 +- examples | 1 + examples/add_a_saved_album.py | 27 ---- examples/add_a_saved_track.py | 29 ----- examples/add_saved_episodes.py | 29 ----- examples/add_saved_shows.py | 29 ----- examples/add_tracks_to_playlist.py | 29 ----- examples/app.py | 115 ------------------ examples/artist_albums.py | 52 -------- examples/artist_discography.py | 71 ----------- examples/artist_recommendations.py | 43 ------- examples/audio_analysis_for_track.py | 22 ---- examples/audio_features.py | 34 ------ examples/audio_features_analysis.py | 33 ----- examples/audio_features_for_track.py | 22 ---- examples/change_playlist_details.py | 47 ------- examples/check_show_is_saved.py | 32 ----- examples/client_credentials_flow.py | 11 -- examples/contains_a_saved_track.py | 19 --- examples/create_playlist.py | 31 ----- examples/delete_a_saved_track.py | 19 --- examples/delete_saved_episodes.py | 29 ----- examples/follow_playlist.py | 25 ---- examples/get_audiobook_chapters_info.py | 30 ----- examples/get_audiobooks_info.py | 31 ----- examples/headless.py | 7 -- examples/multiple_accounts.py | 10 -- examples/my_playlists.py | 11 -- examples/my_top_artists.py | 17 --- examples/my_top_tracks.py | 16 --- examples/personalized_playlist.py | 53 -------- examples/player.py | 22 ---- examples/playlist_all_non_local_tracks.py | 30 ----- examples/playlist_tracks.py | 22 ---- examples/read_a_playlist.py | 11 -- .../remove_specific_tracks_from_playlist.py | 26 ---- examples/remove_tracks_from_playlist.py | 21 ---- examples/replace_tracks_in_playlist.py | 21 ---- examples/search.py | 16 --- examples/show_album.py | 16 --- examples/show_artist.py | 17 --- examples/show_artist_top_tracks.py | 18 --- examples/show_artist_tracks.py | 17 --- examples/show_featured_artists.py | 28 ----- examples/show_featured_playlists.py | 19 --- examples/show_my_saved_tracks.py | 22 ---- examples/show_new_releases.py | 18 --- examples/show_related.py | 25 ---- examples/show_track_info.py | 17 --- examples/show_tracks.py | 28 ----- examples/show_user.py | 18 --- examples/simple_artist_albums.py | 16 --- examples/simple_artist_top_tracks.py | 14 --- examples/simple_me.py | 13 -- examples/simple_search_artist.py | 9 -- examples/simple_search_artist_image_url.py | 18 --- examples/title_chain.py | 70 ----------- examples/track_recommendations.py | 43 ------- examples/unfollow_playlist.py | 33 ----- examples/user_playlists.py | 20 --- examples/user_playlists_contents.py | 31 ----- examples/user_public_playlists.py | 26 ---- examples/user_saved_albums_delete.py | 12 -- examples/user_saved_episodes.py | 30 ----- examples/user_saved_shows.py | 30 ----- 67 files changed, 8 insertions(+), 1704 deletions(-) create mode 100644 .gitmodules create mode 160000 examples delete mode 100644 examples/add_a_saved_album.py delete mode 100644 examples/add_a_saved_track.py delete mode 100644 examples/add_saved_episodes.py delete mode 100644 examples/add_saved_shows.py delete mode 100644 examples/add_tracks_to_playlist.py delete mode 100644 examples/app.py delete mode 100644 examples/artist_albums.py delete mode 100644 examples/artist_discography.py delete mode 100644 examples/artist_recommendations.py delete mode 100644 examples/audio_analysis_for_track.py delete mode 100644 examples/audio_features.py delete mode 100644 examples/audio_features_analysis.py delete mode 100644 examples/audio_features_for_track.py delete mode 100644 examples/change_playlist_details.py delete mode 100644 examples/check_show_is_saved.py delete mode 100644 examples/client_credentials_flow.py delete mode 100644 examples/contains_a_saved_track.py delete mode 100644 examples/create_playlist.py delete mode 100644 examples/delete_a_saved_track.py delete mode 100644 examples/delete_saved_episodes.py delete mode 100644 examples/follow_playlist.py delete mode 100644 examples/get_audiobook_chapters_info.py delete mode 100644 examples/get_audiobooks_info.py delete mode 100644 examples/headless.py delete mode 100644 examples/multiple_accounts.py delete mode 100644 examples/my_playlists.py delete mode 100644 examples/my_top_artists.py delete mode 100644 examples/my_top_tracks.py delete mode 100644 examples/personalized_playlist.py delete mode 100644 examples/player.py delete mode 100644 examples/playlist_all_non_local_tracks.py delete mode 100644 examples/playlist_tracks.py delete mode 100644 examples/read_a_playlist.py delete mode 100644 examples/remove_specific_tracks_from_playlist.py delete mode 100644 examples/remove_tracks_from_playlist.py delete mode 100644 examples/replace_tracks_in_playlist.py delete mode 100644 examples/search.py delete mode 100644 examples/show_album.py delete mode 100644 examples/show_artist.py delete mode 100644 examples/show_artist_top_tracks.py delete mode 100644 examples/show_artist_tracks.py delete mode 100644 examples/show_featured_artists.py delete mode 100644 examples/show_featured_playlists.py delete mode 100644 examples/show_my_saved_tracks.py delete mode 100644 examples/show_new_releases.py delete mode 100644 examples/show_related.py delete mode 100644 examples/show_track_info.py delete mode 100644 examples/show_tracks.py delete mode 100644 examples/show_user.py delete mode 100644 examples/simple_artist_albums.py delete mode 100644 examples/simple_artist_top_tracks.py delete mode 100644 examples/simple_me.py delete mode 100644 examples/simple_search_artist.py delete mode 100644 examples/simple_search_artist_image_url.py delete mode 100644 examples/title_chain.py delete mode 100644 examples/track_recommendations.py delete mode 100644 examples/unfollow_playlist.py delete mode 100644 examples/user_playlists.py delete mode 100644 examples/user_playlists_contents.py delete mode 100644 examples/user_public_playlists.py delete mode 100644 examples/user_saved_albums_delete.py delete mode 100644 examples/user_saved_episodes.py delete mode 100644 examples/user_saved_shows.py diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..0975586b --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "examples"] + path = examples + url = git@github.com:spotipy-dev/spotipy-examples.git diff --git a/FAQ.md b/FAQ.md index de3caf81..28756512 100644 --- a/FAQ.md +++ b/FAQ.md @@ -6,7 +6,7 @@ spotipy can only return fields documented on the Spotify web API https://develop ### How to use spotipy in an API? -Check out [this example Flask app](examples/app.py) +Check out [this example Flask app](https://github.com/spotipy-dev/spotipy-examples/tree/main/apps/flask_api) ### How can I store tokens in a database rather than on the filesystem? @@ -51,7 +51,7 @@ must be specified: `search("abba", market="DE")`. If you cannot open a browser, set `open_browser=False` when instantiating SpotifyOAuth or SpotifyPKCE. You will be prompted to open the authorization URI manually. -See the [headless auth example](examples/headless.py). +See the [headless auth example](https://github.com/spotipy-dev/spotipy-examples/blob/main/scripts/headless.py). ### My application is not responding diff --git a/docs/index.rst b/docs/index.rst index 990205cb..c205488b 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -254,8 +254,8 @@ artist's name:: artist = items[0] print(artist['name'], artist['images'][0]['url']) -There are many more examples of how to use *Spotipy* in the `Examples -Directory `_ on GitHub. +There are many more examples of how to use *Spotipy* in the `spotipy-examples +repository `_ on GitHub. API Reference ============== diff --git a/examples b/examples new file mode 160000 index 00000000..c610a797 --- /dev/null +++ b/examples @@ -0,0 +1 @@ +Subproject commit c610a79705ef4aa55e4d61572a012f77b6f7245d diff --git a/examples/add_a_saved_album.py b/examples/add_a_saved_album.py deleted file mode 100644 index 04e762c1..00000000 --- a/examples/add_a_saved_album.py +++ /dev/null @@ -1,27 +0,0 @@ -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -logger = logging.getLogger('examples.add_a_saved_album') -logging.basicConfig(level='DEBUG') - -scope = 'user-library-modify' - - -def get_args(): - parser = argparse.ArgumentParser(description='Creates a playlist for user') - parser.add_argument('-a', '--aids', action='append', - required=True, help='Album ids') - return parser.parse_args() - - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - sp.current_user_saved_albums_add(albums=args.aids) - - -if __name__ == '__main__': - main() diff --git a/examples/add_a_saved_track.py b/examples/add_a_saved_track.py deleted file mode 100644 index 84dbfe15..00000000 --- a/examples/add_a_saved_track.py +++ /dev/null @@ -1,29 +0,0 @@ -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-modify' - -logger = logging.getLogger('examples.add_a_saved_track') -logging.basicConfig(level='DEBUG') - - -def get_args(): - parser = argparse.ArgumentParser(description='Add tracks to Your ' - 'Collection of saved tracks') - parser.add_argument('-t', '--tids', action='append', - required=True, help='Track ids') - return parser.parse_args() - - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - - sp.current_user_saved_tracks_add(tracks=args.tids) - - -if __name__ == '__main__': - main() diff --git a/examples/add_saved_episodes.py b/examples/add_saved_episodes.py deleted file mode 100644 index 8e34f947..00000000 --- a/examples/add_saved_episodes.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -Add episodes to current user's library -Usage: add_saved_episodes.py -e episode_id episode_id ... -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-modify' - -def get_args(): - parser = argparse.ArgumentParser(description='Add episodes to library') - # Default args set to This American Life episodes 814 and 815 - parser.add_argument('-e', '--eids', nargs='+', - default=['6rxg9Lpt2ywNHFea8LxEBO', '7q8or6oYYRFQFYlA0remoy'], - help='Episode ids') - return parser.parse_args() - -def main(): - args = get_args() - print('Adding following episode ids to library: ' + str(args.eids)) - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - sp.current_user_saved_episodes_add(episodes=args.eids) - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/examples/add_saved_shows.py b/examples/add_saved_shows.py deleted file mode 100644 index 1bbaf9de..00000000 --- a/examples/add_saved_shows.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -Add shows to current user's library -Usage: add_saved_shows.py -s show_id show_id ... -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-modify' - -def get_args(): - parser = argparse.ArgumentParser(description='Add shows to library') - # Default args set to Radiolab and 99% invisible - parser.add_argument('-s', '--sids', nargs='+', - default=['2hmkzUtix0qTqvtpPcMzEL', '2VRS1IJCTn2Nlkg33ZVfkM'], - help='Show ids') - return parser.parse_args() - -def main(): - args = get_args() - print('Adding following show ids to library: ' + str(args.sids)) - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - sp.current_user_saved_shows_add(shows=args.sids) - - -if __name__ == '__main__': - main() diff --git a/examples/add_tracks_to_playlist.py b/examples/add_tracks_to_playlist.py deleted file mode 100644 index eaaa6637..00000000 --- a/examples/add_tracks_to_playlist.py +++ /dev/null @@ -1,29 +0,0 @@ -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -logger = logging.getLogger('examples.add_tracks_to_playlist') -logging.basicConfig(level='DEBUG') -scope = 'playlist-modify-public' - - -def get_args(): - parser = argparse.ArgumentParser(description='Adds track to user playlist') - parser.add_argument('-u', '--uris', action='append', - required=True, help='Track ids') - parser.add_argument('-p', '--playlist', required=True, - help='Playlist to add track to') - return parser.parse_args() - - -def main(): - args = get_args() - - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - sp.playlist_add_items(args.playlist, args.uris) - - -if __name__ == '__main__': - main() diff --git a/examples/app.py b/examples/app.py deleted file mode 100644 index ca2a3401..00000000 --- a/examples/app.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -Prerequisites - - pip3 install spotipy Flask Flask-Session - - // from your [app settings](https://developer.spotify.com/dashboard/applications) - export SPOTIPY_CLIENT_ID=client_id_here - export SPOTIPY_CLIENT_SECRET=client_secret_here - export SPOTIPY_REDIRECT_URI='http://127.0.0.1:8080' // must contain a port - // SPOTIPY_REDIRECT_URI must be added to your [app settings](https://developer.spotify.com/dashboard/applications) - OPTIONAL - // in development environment for debug output - export FLASK_ENV=development - // so that you can invoke the app outside the file's directory include - export FLASK_APP=/path/to/spotipy/examples/app.py - - // on Windows, use `SET` instead of `export` - -Run app.py - - python3 app.py OR python3 -m flask run - NOTE: If receiving "port already in use" error, try other ports: 5000, 8090, 8888, etc... - (will need to be updated in your Spotify app and SPOTIPY_REDIRECT_URI variable) -""" - -import os - -from flask import Flask, redirect, request, session -from flask_session import Session - -import spotipy - -app = Flask(__name__) -app.config['SECRET_KEY'] = os.urandom(64) -app.config['SESSION_TYPE'] = 'filesystem' -app.config['SESSION_FILE_DIR'] = './.flask_session/' -Session(app) - - -@app.route('/') -def index(): - - cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session) - auth_manager = spotipy.oauth2.SpotifyOAuth(scope='user-read-currently-playing playlist-modify-private', - cache_handler=cache_handler, - show_dialog=True) - - if request.args.get("code"): - # Step 2. Being redirected from Spotify auth page - auth_manager.get_access_token(request.args.get("code")) - return redirect('/') - - if not auth_manager.validate_token(cache_handler.get_cached_token()): - # Step 1. Display sign in link when no token - auth_url = auth_manager.get_authorize_url() - return f'

Sign in

' - - # Step 3. Signed in, display data - spotify = spotipy.Spotify(auth_manager=auth_manager) - return f'

Hi {spotify.me()["display_name"]}, ' \ - f'[sign out]

' \ - f'my playlists | ' \ - f'currently playing | ' \ - f'me' \ - - - -@app.route('/sign_out') -def sign_out(): - session.pop("token_info", None) - return redirect('/') - - -@app.route('/playlists') -def playlists(): - cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session) - auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler) - if not auth_manager.validate_token(cache_handler.get_cached_token()): - return redirect('/') - - spotify = spotipy.Spotify(auth_manager=auth_manager) - return spotify.current_user_playlists() - - -@app.route('/currently_playing') -def currently_playing(): - cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session) - auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler) - if not auth_manager.validate_token(cache_handler.get_cached_token()): - return redirect('/') - spotify = spotipy.Spotify(auth_manager=auth_manager) - track = spotify.current_user_playing_track() - if not track is None: - return track - return "No track currently playing." - - -@app.route('/current_user') -def current_user(): - cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session) - auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler) - if not auth_manager.validate_token(cache_handler.get_cached_token()): - return redirect('/') - spotify = spotipy.Spotify(auth_manager=auth_manager) - return spotify.current_user() - - -''' -Following lines allow application to be run more conveniently with -`python app.py` (Make sure you're using python3) -(Also includes directive to leverage pythons threading capacity.) -''' -if __name__ == '__main__': - app.run(threaded=True, port=int(os.environ.get("PORT", - os.environ.get("SPOTIPY_REDIRECT_URI", 8080).split(":")[-1]))) diff --git a/examples/artist_albums.py b/examples/artist_albums.py deleted file mode 100644 index 42f26e65..00000000 --- a/examples/artist_albums.py +++ /dev/null @@ -1,52 +0,0 @@ -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -logger = logging.getLogger('examples.artist_albums') -logging.basicConfig(level='INFO') - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) - - -def get_args(): - parser = argparse.ArgumentParser(description='Gets albums from artist') - parser.add_argument('-a', '--artist', required=True, - help='Name of Artist') - return parser.parse_args() - - -def get_artist(name): - results = sp.search(q='artist:' + name, type='artist') - items = results['artists']['items'] - return items[0] if items else None - - -def show_artist_albums(artist): - albums = [] - results = sp.artist_albums(artist['id'], album_type='album') - albums.extend(results['items']) - while results['next']: - results = sp.next(results) - albums.extend(results['items']) - seen = set() # to avoid dups - albums.sort(key=lambda album: album['name'].lower()) - for album in albums: - name = album['name'] - if name not in seen: - logger.info(f'ALBUM: {name}') - seen.add(name) - - -def main(): - args = get_args() - artist = get_artist(args.artist) - if artist: - show_artist_albums(artist) - else: - logger.error(f"Can't find artist: {artist}") - - -if __name__ == '__main__': - main() diff --git a/examples/artist_discography.py b/examples/artist_discography.py deleted file mode 100644 index 68e4576c..00000000 --- a/examples/artist_discography.py +++ /dev/null @@ -1,71 +0,0 @@ -# Shows the list of all songs sung by the artist or the band -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -logger = logging.getLogger('examples.artist_discography') -logging.basicConfig(level='INFO') - - -def get_args(): - parser = argparse.ArgumentParser(description='Shows albums and tracks for ' - 'given artist') - parser.add_argument('-a', '--artist', required=True, - help='Name of Artist') - return parser.parse_args() - - -def get_artist(name): - results = sp.search(q='artist:' + name, type='artist') - items = results['artists']['items'] - return items[0] if items else None - - -def show_album_tracks(album): - tracks = [] - results = sp.album_tracks(album['id']) - tracks.extend(results['items']) - while results['next']: - results = sp.next(results) - tracks.extend(results['items']) - for i, track in enumerate(tracks): - logger.info(f'{i + 1}. {track["name"]}') - - -def show_artist_albums(artist): - albums = [] - results = sp.artist_albums(artist['id'], album_type='album') - albums.extend(results['items']) - while results['next']: - results = sp.next(results) - albums.extend(results['items']) - logger.info(f'Total albums: {len(albums)}') - unique = set() # skip duplicate albums - for album in albums: - name = album['name'].lower() - if name not in unique: - logger.info(f'ALBUM: {name}') - unique.add(name) - show_album_tracks(album) - - -def show_artist(artist): - logger.info(f'===={artist["name"]}====') - logger.info(f'Popularity: {artist["popularity"]}') - if len(artist['genres']) > 0: - logger.info(f"Genres: {', '.join(artist['genres'])}") - - -def main(): - args = get_args() - artist = get_artist(args.artist) - show_artist(artist) - show_artist_albums(artist) - - -if __name__ == '__main__': - client_credentials_manager = SpotifyClientCredentials() - sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - main() diff --git a/examples/artist_recommendations.py b/examples/artist_recommendations.py deleted file mode 100644 index 79939c27..00000000 --- a/examples/artist_recommendations.py +++ /dev/null @@ -1,43 +0,0 @@ -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -logger = logging.getLogger('examples.artist_recommendations') -logging.basicConfig(level='INFO') - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - - -def get_args(): - parser = argparse.ArgumentParser(description='Recommendations for the ' - 'given artist') - parser.add_argument('-a', '--artist', required=True, help='Name of Artist') - return parser.parse_args() - - -def get_artist(name): - results = sp.search(q='artist:' + name, type='artist') - items = results['artists']['items'] - return items[0] if items else None - - -def show_recommendations_for_artist(artist): - results = sp.recommendations(seed_artists=[artist['id']]) - for track in results['tracks']: - logger.info(f'Recommendation: {track["name"]} - {track["artists"][0]["name"]}') - - -def main(): - args = get_args() - artist = get_artist(args.artist) - if artist: - show_recommendations_for_artist(artist) - else: - logger.error("Can't find that artist", args.artist) - - -if __name__ == '__main__': - main() diff --git a/examples/audio_analysis_for_track.py b/examples/audio_analysis_for_track.py deleted file mode 100644 index 177ed37e..00000000 --- a/examples/audio_analysis_for_track.py +++ /dev/null @@ -1,22 +0,0 @@ -# shows audio analysis for the given track - -import json -import sys -import time - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -if len(sys.argv) > 1: - tid = sys.argv[1] -else: - tid = 'spotify:track:4TTV7EcfroSLWzXRY6gLv6' - -start = time.time() -analysis = sp.audio_analysis(tid) -delta = time.time() - start -print(json.dumps(analysis, indent=4)) -print(f"analysis retrieved in {delta:.2f} seconds") diff --git a/examples/audio_features.py b/examples/audio_features.py deleted file mode 100644 index dbc1c4ff..00000000 --- a/examples/audio_features.py +++ /dev/null @@ -1,34 +0,0 @@ -# shows acoustic features for tracks for the given artist - -import json -import sys -import time - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) -sp.trace = False - -if len(sys.argv) > 1: - artist_name = ' '.join(sys.argv[1:]) -else: - artist_name = 'weezer' - -results = sp.search(q=artist_name, limit=50) -tids = [] -for i, t in enumerate(results['tracks']['items']): - print(' ', i, t['name']) - tids.append(t['uri']) - -start = time.time() -features = sp.audio_features(tids) -delta = time.time() - start -for feature in features: - print(json.dumps(feature, indent=4)) - print() - analysis = sp._get(feature['analysis_url']) - print(json.dumps(analysis, indent=4)) - print() -print(f"features retrieved in {delta:.2f} seconds") diff --git a/examples/audio_features_analysis.py b/examples/audio_features_analysis.py deleted file mode 100644 index ada18466..00000000 --- a/examples/audio_features_analysis.py +++ /dev/null @@ -1,33 +0,0 @@ -import matplotlib.pyplot as plt -# Import the extra necessary libraries for this example -# These libraries are not included in the default packages -import pandas as pd -import seaborn as sns - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -# 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() diff --git a/examples/audio_features_for_track.py b/examples/audio_features_for_track.py deleted file mode 100644 index ce47bf8f..00000000 --- a/examples/audio_features_for_track.py +++ /dev/null @@ -1,22 +0,0 @@ -# shows acoustic features for tracks for the given artist - -import json -import sys -import time - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) -sp.trace = True - -if len(sys.argv) > 1: - tids = sys.argv[1:] - print(tids) - - start = time.time() - features = sp.audio_features(tids) - delta = time.time() - start - print(json.dumps(features, indent=4)) - print(f"features retrieved in {delta:.2f} seconds") diff --git a/examples/change_playlist_details.py b/examples/change_playlist_details.py deleted file mode 100644 index 759b94d4..00000000 --- a/examples/change_playlist_details.py +++ /dev/null @@ -1,47 +0,0 @@ -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -logger = logging.getLogger('examples.change_playlist_details') -logging.basicConfig(level='DEBUG') - -scope = 'playlist-modify-public playlist-modify-private' - - -def get_args(): - parser = argparse.ArgumentParser(description='Modify details of playlist') - parser.add_argument('-p', '--playlist', required=True, - help='Playlist id to alter details') - parser.add_argument('-n', '--name', required=False, - help='Name of playlist') - parser.add_argument('--public', action='store_true', required=False, - help='Include param if playlist is public') - parser.add_argument('--private', action='store_false', required=False, - default=None, - help='Include param to make playlist is private') - parser.add_argument('-c', '--collaborative', action='store_true', - required=False, default=None, - help='Include param if playlist is collaborative') - parser.add_argument('-i', '--independent', action='store_false', - required=False, default=None, - help='Include param to make playlist non collaborative') - parser.add_argument('-d', '--description', default=None, required=False, - help='Description of playlist') - return parser.parse_args() - - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - sp.playlist_change_details( - args.playlist, - name=args.name, - public=args.public or args.private, - collaborative=args.collaborative or args.independent, - description=args.description) - - -if __name__ == '__main__': - main() diff --git a/examples/check_show_is_saved.py b/examples/check_show_is_saved.py deleted file mode 100644 index 5da3b0f6..00000000 --- a/examples/check_show_is_saved.py +++ /dev/null @@ -1,32 +0,0 @@ -""" -Check if shows are saved in user's library -Usage: check_show_is_saved -s show_id show_id ... -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-read' - -def get_args(): - parser = argparse.ArgumentParser(description='Check that a show is saved') - # Default args set to Radiolab and 99% invisible - parser.add_argument('-s', '--sids', nargs='+', - default=['2hmkzUtix0qTqvtpPcMzEL', '2VRS1IJCTn2Nlkg33ZVfkM'], - help='Show ids') - return parser.parse_args() - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - results = sp.current_user_saved_episodes_contains(episodes=args.sids) - show_names = sp.shows(shows=args.sids) - # Print show names and if show is saved by current user - for i, show in enumerate(show_names['shows']): - print(show['name'] + ': ' + str(results[i])) - - -if __name__ == '__main__': - main() diff --git a/examples/client_credentials_flow.py b/examples/client_credentials_flow.py deleted file mode 100644 index d6c77882..00000000 --- a/examples/client_credentials_flow.py +++ /dev/null @@ -1,11 +0,0 @@ -from pprint import pprint - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -search_str = 'Muse' -result = sp.search(search_str) -pprint(result) diff --git a/examples/contains_a_saved_track.py b/examples/contains_a_saved_track.py deleted file mode 100644 index fb6175dc..00000000 --- a/examples/contains_a_saved_track.py +++ /dev/null @@ -1,19 +0,0 @@ -# Prints whether a track exists in your collection of saved tracks - -import pprint -import sys - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-read' - -if len(sys.argv) > 1: - tid = sys.argv[1] -else: - print(f"Usage: {sys.argv[0]} track-id ...") - sys.exit() - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) -results = sp.current_user_saved_tracks_contains(tracks=[tid]) -pprint.pprint(results) diff --git a/examples/create_playlist.py b/examples/create_playlist.py deleted file mode 100644 index 702c25c6..00000000 --- a/examples/create_playlist.py +++ /dev/null @@ -1,31 +0,0 @@ -# Creates a playlist for a user - -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -logger = logging.getLogger('examples.create_playlist') -logging.basicConfig(level='DEBUG') - - -def get_args(): - parser = argparse.ArgumentParser(description='Creates a playlist for user') - parser.add_argument('-p', '--playlist', required=True, - help='Name of Playlist') - parser.add_argument('-d', '--description', required=False, default='', - help='Description of Playlist') - return parser.parse_args() - - -def main(): - args = get_args() - scope = "playlist-modify-public" - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - user_id = sp.me()['id'] - sp.user_playlist_create(user_id, args.playlist, description=args.description) - - -if __name__ == '__main__': - main() diff --git a/examples/delete_a_saved_track.py b/examples/delete_a_saved_track.py deleted file mode 100644 index 2f461531..00000000 --- a/examples/delete_a_saved_track.py +++ /dev/null @@ -1,19 +0,0 @@ -# Delete a track from 'Your Collection' of saved tracks - -import pprint -import sys - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-modify' - -if len(sys.argv) > 1: - tid = sys.argv[1] -else: - print(f"Usage: {sys.argv[0]} track-id ...") - sys.exit() - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) -results = sp.current_user_saved_tracks_delete(tracks=[tid]) -pprint.pprint(results) diff --git a/examples/delete_saved_episodes.py b/examples/delete_saved_episodes.py deleted file mode 100644 index 349bb756..00000000 --- a/examples/delete_saved_episodes.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -Delete episodes from current user's library -Usage: delete_saved_episodes.py -e episode_id episode_id ... -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-modify' - -def get_args(): - parser = argparse.ArgumentParser(description='Delete episodes from library') - # Default args set to This American Life episodes 814 and 815 - parser.add_argument('-e', '--eids', nargs='+', - default=['6rxg9Lpt2ywNHFea8LxEBO', '7q8or6oYYRFQFYlA0remoy'], - help='Episode ids') - return parser.parse_args() - -def main(): - args = get_args() - print('Deleting following episode ids from library: ' + str(args.eids)) - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - sp.current_user_saved_episodes_delete(episodes=args.eids) - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/examples/follow_playlist.py b/examples/follow_playlist.py deleted file mode 100644 index 598e9509..00000000 --- a/examples/follow_playlist.py +++ /dev/null @@ -1,25 +0,0 @@ -# Follow a playlist - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'playlist-modify-public' -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -def get_args(): - parser = argparse.ArgumentParser(description='Follows a playlist based on playlist ID') - # Default to Top 50 Global if no playlist is provided - parser.add_argument('-p', '--playlist', help='Playlist ID', nargs='?', default='37i9dQZEVXbMDoHDwVN2tF') - return parser.parse_args() - - -def main(): - args = get_args() - # Uses Lofi Girl playlist - playlist = args.playlist or '0vvXsWCC9xrXsKd4FyS8kM' - spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(playlist) - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/examples/get_audiobook_chapters_info.py b/examples/get_audiobook_chapters_info.py deleted file mode 100644 index 094c8185..00000000 --- a/examples/get_audiobook_chapters_info.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -Print chapter titles and lengths for given audiobook -Usage: get_audiobooks_chapters_info.py -a audiobook_id -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - - -def get_args(): - parser = argparse.ArgumentParser(description='Get chapter info for an audiobook') - # Default set to Dune - parser.add_argument('-a', '--audiobook', default='2h01INWMBvfpzNMpGFzhdF', help='Audiobook id') - return parser.parse_args() - - -def main(): - args = get_args() - print('Getting chapter info for follow audiobook id: ' + str(args.audiobook)) - sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) - results = sp.get_audiobook_chapters(id=args.audiobook) - # Print chapter name and length - for item in results['items']: - print('Name: ' + item['name'] + ', length: ' + str(round(item['duration_ms']/60000,1)) + ' minutes') - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/examples/get_audiobooks_info.py b/examples/get_audiobooks_info.py deleted file mode 100644 index 5e8f010f..00000000 --- a/examples/get_audiobooks_info.py +++ /dev/null @@ -1,31 +0,0 @@ -""" -Print audiobook title and description for a list of audiobook ids -Usage: get_audiobooks_info.py -a audiobook_id audiobook_id ... -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - - -def get_args(): - parser = argparse.ArgumentParser(description='Get information for a list of audiobooks') - # Defaults set to The Great Gatsby, The Chronicles of Narnia and Dune - parser.add_argument('-a', '--aids', nargs='+', - default=['6qjpt1CUHhKXiNoeNoU7nu', '1ezmXd68LbDtxebvygEQ2U', '2h01INWMBvfpzNMpGFzhdF'], - help='Audiobook ids') - return parser.parse_args() - -def main(): - args = get_args() - print('Getting info for follow audiobook ids: ' + str(args.aids) + '\n') - sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) - results = sp.get_audiobooks(ids=args.aids) - # Print book title and description - for book in results['audiobooks']: - print('Title: ' + book['name'] + '\n' + book['description'] + '\n') - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/examples/headless.py b/examples/headless.py deleted file mode 100644 index b354a603..00000000 --- a/examples/headless.py +++ /dev/null @@ -1,7 +0,0 @@ -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -# set open_browser=False to prevent Spotipy from attempting to open the default browser -spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(open_browser=False)) - -print(spotify.me()) diff --git a/examples/multiple_accounts.py b/examples/multiple_accounts.py deleted file mode 100644 index 6323053e..00000000 --- a/examples/multiple_accounts.py +++ /dev/null @@ -1,10 +0,0 @@ -from pprint import pprint - -import spotipy -import spotipy.util as util - -while True: - username = input("Type the Spotify user ID to use: ") - token = util.prompt_for_user_token(username, show_dialog=True) - sp = spotipy.Spotify(token) - pprint(sp.me()) diff --git a/examples/my_playlists.py b/examples/my_playlists.py deleted file mode 100644 index 7a5f46c3..00000000 --- a/examples/my_playlists.py +++ /dev/null @@ -1,11 +0,0 @@ -# Shows a user's playlists - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'playlist-read-private' -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -results = sp.current_user_playlists(limit=50) -for i, item in enumerate(results['items']): - print(f"{i} {item['name']}") diff --git a/examples/my_top_artists.py b/examples/my_top_artists.py deleted file mode 100644 index e24ab083..00000000 --- a/examples/my_top_artists.py +++ /dev/null @@ -1,17 +0,0 @@ -# Shows the top artists for a user -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-top-read' -ranges = ['short_term', 'medium_term', 'long_term'] - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -for sp_range in ['short_term', 'medium_term', 'long_term']: - print("range:", sp_range) - - results = sp.current_user_top_artists(time_range=sp_range, limit=50) - - for i, item in enumerate(results['items']): - print(i, item['name']) - print() diff --git a/examples/my_top_tracks.py b/examples/my_top_tracks.py deleted file mode 100644 index 23169730..00000000 --- a/examples/my_top_tracks.py +++ /dev/null @@ -1,16 +0,0 @@ -# Shows the top tracks for a user - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-top-read' -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -ranges = ['short_term', 'medium_term', 'long_term'] - -for sp_range in ranges: - print("range:", sp_range) - results = sp.current_user_top_tracks(time_range=sp_range, limit=50) - for i, item in enumerate(results['items']): - print(i, item['name'], '//', item['artists'][0]['name']) - print() diff --git a/examples/personalized_playlist.py b/examples/personalized_playlist.py deleted file mode 100644 index f0e062ac..00000000 --- a/examples/personalized_playlist.py +++ /dev/null @@ -1,53 +0,0 @@ -# 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 - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -# 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']) diff --git a/examples/player.py b/examples/player.py deleted file mode 100644 index 73b7b283..00000000 --- a/examples/player.py +++ /dev/null @@ -1,22 +0,0 @@ -from pprint import pprint -from time import sleep - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = "user-read-playback-state,user-modify-playback-state" -sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(scope=scope)) - -# Shows playing devices -res = sp.devices() -pprint(res) - -# Change track -sp.start_playback(uris=['spotify:track:6gdLoMygLsgktydTQ71b15']) - -# Change volume -sp.volume(100) -sleep(2) -sp.volume(50) -sleep(2) -sp.volume(100) diff --git a/examples/playlist_all_non_local_tracks.py b/examples/playlist_all_non_local_tracks.py deleted file mode 100644 index 54a04655..00000000 --- a/examples/playlist_all_non_local_tracks.py +++ /dev/null @@ -1,30 +0,0 @@ -# get all non-local tracks of a playlist -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -# playlist id of global top 50 -PlaylistExample = '37i9dQZEVXbMDoHDwVN2tF' - -# create spotipy client -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) - -# load the first 100 songs -tracks = [] -result = sp.playlist_items(PlaylistExample, additional_types=['track']) -tracks.extend(result['items']) - -# if playlist is larger than 100 songs, continue loading it until end -while result['next']: - result = sp.next(result) - tracks.extend(result['items']) - -# remove all local songs -i = 0 # just for counting how many tracks are local -for item in tracks: - if item['is_local']: - tracks.remove(item) - i += 1 - - -# print result -print("Playlist length: " + str(len(tracks)) + "\nExcluding: " + str(i)) diff --git a/examples/playlist_tracks.py b/examples/playlist_tracks.py deleted file mode 100644 index 6e756ffe..00000000 --- a/examples/playlist_tracks.py +++ /dev/null @@ -1,22 +0,0 @@ -from pprint import pprint - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) - -pl_id = 'spotify:playlist:5RIbzhG2QqdkaP24iXLnZX' -offset = 0 - -while True: - response = sp.playlist_items(pl_id, - offset=offset, - fields='items.track.id,total', - additional_types=['track']) - - if len(response['items']) == 0: - break - - pprint(response['items']) - offset = offset + len(response['items']) - print(offset, "/", response['total']) diff --git a/examples/read_a_playlist.py b/examples/read_a_playlist.py deleted file mode 100644 index a5ccc7e5..00000000 --- a/examples/read_a_playlist.py +++ /dev/null @@ -1,11 +0,0 @@ -import json - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -playlist_id = '37i9dQZEVXbJiZcmkrIHGU' -results = sp.playlist(playlist_id) -print(json.dumps(results, indent=4)) diff --git a/examples/remove_specific_tracks_from_playlist.py b/examples/remove_specific_tracks_from_playlist.py deleted file mode 100644 index 340f3795..00000000 --- a/examples/remove_specific_tracks_from_playlist.py +++ /dev/null @@ -1,26 +0,0 @@ -# Removes tracks from a playlist - -import pprint -import sys - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -if len(sys.argv) > 2: - playlist_id = sys.argv[1] - track_ids_and_positions = sys.argv[2:] - track_ids = [] - for t_pos in sys.argv[2:]: - tid, pos = t_pos.split(',') - track_ids.append({"uri": tid, "positions": [int(pos)]}) -else: - print( - f"Usage: {sys.argv[0]} playlist_id track_id,pos track_id,pos ...") - sys.exit() - -scope = 'playlist-modify-public' -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -results = sp.playlist_remove_specific_occurrences_of_items( - playlist_id, track_ids) -pprint.pprint(results) diff --git a/examples/remove_tracks_from_playlist.py b/examples/remove_tracks_from_playlist.py deleted file mode 100644 index 91a7e8e3..00000000 --- a/examples/remove_tracks_from_playlist.py +++ /dev/null @@ -1,21 +0,0 @@ -# Removes tracks from playlist -import pprint -import sys - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -if len(sys.argv) > 2: - playlist_id = sys.argv[1] - track_ids = sys.argv[2:] -else: - print(f"Usage: {sys.argv[0]} playlist_id track_id ...") - sys.exit() - -scope = 'playlist-modify-public' - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -results = sp.playlist_remove_all_occurrences_of_items( - playlist_id, track_ids) -pprint.pprint(results) diff --git a/examples/replace_tracks_in_playlist.py b/examples/replace_tracks_in_playlist.py deleted file mode 100644 index 2a46d46f..00000000 --- a/examples/replace_tracks_in_playlist.py +++ /dev/null @@ -1,21 +0,0 @@ -# Replaces all tracks in a playlist - -import pprint -import sys - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -if len(sys.argv) > 2: - playlist_id = sys.argv[1] - track_ids = sys.argv[2:] -else: - print(f"Usage: {sys.argv[0]} playlist_id track_id ...") - sys.exit() - -scope = 'playlist-modify-public' - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -results = sp.playlist_replace_items(playlist_id, track_ids) -pprint.pprint(results) diff --git a/examples/search.py b/examples/search.py deleted file mode 100644 index 69306bcc..00000000 --- a/examples/search.py +++ /dev/null @@ -1,16 +0,0 @@ -# shows artist info for a URN or URL - -import pprint -import sys - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - search_str = sys.argv[1] -else: - search_str = 'Radiohead' - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) -result = sp.search(search_str) -pprint.pprint(result) diff --git a/examples/show_album.py b/examples/show_album.py deleted file mode 100644 index 7847ec7c..00000000 --- a/examples/show_album.py +++ /dev/null @@ -1,16 +0,0 @@ -# shows album info for a URN or URL - -import sys -from pprint import pprint - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - urn = sys.argv[1] -else: - urn = 'spotify:album:5yTx83u3qerZF7GRJu7eFk' - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) -album = sp.album(urn) -pprint(album) diff --git a/examples/show_artist.py b/examples/show_artist.py deleted file mode 100644 index d07bf228..00000000 --- a/examples/show_artist.py +++ /dev/null @@ -1,17 +0,0 @@ -# shows artist info for a URN or URL - -import sys -from pprint import pprint - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - urn = sys.argv[1] -else: - urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) - -artist = sp.artist(urn) -pprint(artist) diff --git a/examples/show_artist_top_tracks.py b/examples/show_artist_top_tracks.py deleted file mode 100644 index 599c2d83..00000000 --- a/examples/show_artist_top_tracks.py +++ /dev/null @@ -1,18 +0,0 @@ -# shows artist info for a URN or URL -# scope is not required for this function - -import sys - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - urn = sys.argv[1] -else: - urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) -response = sp.artist_top_tracks(urn) - -for track in response['tracks']: - print(track['name']) diff --git a/examples/show_artist_tracks.py b/examples/show_artist_tracks.py deleted file mode 100644 index ad690b0d..00000000 --- a/examples/show_artist_tracks.py +++ /dev/null @@ -1,17 +0,0 @@ -# shows tracks for the given artist - -# usage: python tracks.py [artist name] - -import sys - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -if len(sys.argv) > 1: - artist_name = ' '.join(sys.argv[1:]) - results = sp.search(q=artist_name, limit=20) - for i, t in enumerate(results['tracks']['items']): - print(' ', i, t['name']) diff --git a/examples/show_featured_artists.py b/examples/show_featured_artists.py deleted file mode 100644 index 1471c128..00000000 --- a/examples/show_featured_artists.py +++ /dev/null @@ -1,28 +0,0 @@ -# Shows all artists featured on an album - -# usage: featured_artists.py spotify:album:[album urn] - -import sys -from pprint import pprint - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - urn = sys.argv[1] -else: - urn = 'spotify:album:5yTx83u3qerZF7GRJu7eFk' - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) -album = sp.album(urn) - -featured_artists = set() - -items = album['tracks']['items'] - -for item in items: - for ele in item['artists']: - if 'name' in ele: - featured_artists.add(ele['name']) - -pprint(featured_artists) diff --git a/examples/show_featured_playlists.py b/examples/show_featured_playlists.py deleted file mode 100644 index d2d59654..00000000 --- a/examples/show_featured_playlists.py +++ /dev/null @@ -1,19 +0,0 @@ -# shows artist info for a URN or URL - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) - -response = sp.featured_playlists() -print(response['message']) - -while response: - playlists = response['playlists'] - for i, item in enumerate(playlists['items']): - print(playlists['offset'] + i, item['name']) - - if playlists['next']: - response = sp.next(playlists) - else: - response = None diff --git a/examples/show_my_saved_tracks.py b/examples/show_my_saved_tracks.py deleted file mode 100644 index d606f06b..00000000 --- a/examples/show_my_saved_tracks.py +++ /dev/null @@ -1,22 +0,0 @@ -# Shows a user's saved tracks (need to be authenticated via oauth) - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-read' - - -def show_tracks(results): - for item in results['items']: - track = item['track'] - print(f"{track['artists'][0]['name']:>32.32} {track['name']}") - - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -results = sp.current_user_saved_tracks() -show_tracks(results) - -while results['next']: - results = sp.next(results) - show_tracks(results) diff --git a/examples/show_new_releases.py b/examples/show_new_releases.py deleted file mode 100644 index e4ab63e7..00000000 --- a/examples/show_new_releases.py +++ /dev/null @@ -1,18 +0,0 @@ -# shows artist info for a URN or URL - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) - -response = sp.new_releases() - -while response: - albums = response['albums'] - for i, item in enumerate(albums['items']): - print(albums['offset'] + i, item['name']) - - if albums['next']: - response = sp.next(albums) - else: - response = None diff --git a/examples/show_related.py b/examples/show_related.py deleted file mode 100644 index 3865bd6d..00000000 --- a/examples/show_related.py +++ /dev/null @@ -1,25 +0,0 @@ -# shows related artists for the given seed artist - -import sys - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - artist_name = sys.argv[1] -else: - artist_name = 'weezer' - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) -result = sp.search(q='artist:' + artist_name, type='artist') -try: - name = result['artists']['items'][0]['name'] - uri = result['artists']['items'][0]['uri'] - - related = sp.artist_related_artists(uri) - print('Related artists for', name) - for artist in related['artists']: - print(' ', artist['name']) -except BaseException: - print("usage show_related.py [artist-name]") diff --git a/examples/show_track_info.py b/examples/show_track_info.py deleted file mode 100644 index 4a63e611..00000000 --- a/examples/show_track_info.py +++ /dev/null @@ -1,17 +0,0 @@ -# shows track info for a URN or URL - -import sys -from pprint import pprint - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - urn = sys.argv[1] -else: - urn = 'spotify:track:0Svkvt5I79wficMFgaqEQJ' - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) - -track = sp.track(urn) -pprint(track) diff --git a/examples/show_tracks.py b/examples/show_tracks.py deleted file mode 100644 index ceb82496..00000000 --- a/examples/show_tracks.py +++ /dev/null @@ -1,28 +0,0 @@ -''' - usage: show_tracks.py path_of_ids - - given a list of track IDs show the artist and track name -''' -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - - -def get_args(): - parser = argparse.ArgumentParser(description='Print artist and track name given a list of track IDs') - parser.add_argument('-u', '--uris', nargs='+', - required=True, help='Track ids') - return parser.parse_args() - - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) - track_list = sp.tracks(args.uris) - for track in track_list['tracks']: - print(track['name'] + ' - ' + track['artists'][0]['name']) - - -if __name__ == '__main__': - main() diff --git a/examples/show_user.py b/examples/show_user.py deleted file mode 100644 index b3cb8538..00000000 --- a/examples/show_user.py +++ /dev/null @@ -1,18 +0,0 @@ -# Shows artist info for a URN or URL - -import pprint -import sys - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -if len(sys.argv) > 1: - username = sys.argv[1] -else: - username = 'plamere' - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) -sp.trace = True -user = sp.user(username) -pprint.pprint(user) diff --git a/examples/simple_artist_albums.py b/examples/simple_artist_albums.py deleted file mode 100644 index 55c9733c..00000000 --- a/examples/simple_artist_albums.py +++ /dev/null @@ -1,16 +0,0 @@ -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -birdy_uri = 'spotify:artist:2WX2uTcsvV5OnS0inACecP' - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -results = sp.artist_albums(birdy_uri, album_type='album') -albums = results['items'] -while results['next']: - results = sp.next(results) - albums.extend(results['items']) - -for album in albums: - print(album['name']) diff --git a/examples/simple_artist_top_tracks.py b/examples/simple_artist_top_tracks.py deleted file mode 100644 index 7ab96203..00000000 --- a/examples/simple_artist_top_tracks.py +++ /dev/null @@ -1,14 +0,0 @@ -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp' - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -results = sp.artist_top_tracks(lz_uri) - -for track in results['tracks'][:10]: - print('track : ' + track['name']) - print('audio : ' + track['preview_url']) - print('cover art: ' + track['album']['images'][0]['url']) diff --git a/examples/simple_me.py b/examples/simple_me.py deleted file mode 100644 index b10113d0..00000000 --- a/examples/simple_me.py +++ /dev/null @@ -1,13 +0,0 @@ -from pprint import pprint - -import spotipy - - -def main(): - spotify = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth()) - me = spotify.me() - pprint(me) - - -if __name__ == "__main__": - main() diff --git a/examples/simple_search_artist.py b/examples/simple_search_artist.py deleted file mode 100644 index c1ea7d7d..00000000 --- a/examples/simple_search_artist.py +++ /dev/null @@ -1,9 +0,0 @@ -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -results = sp.search(q='weezer', limit=20) -for i, t in enumerate(results['tracks']['items']): - print(' ', i, t['name']) diff --git a/examples/simple_search_artist_image_url.py b/examples/simple_search_artist_image_url.py deleted file mode 100644 index eab43541..00000000 --- a/examples/simple_search_artist_image_url.py +++ /dev/null @@ -1,18 +0,0 @@ -# Shows the name of the artist/band and their image by giving a link -import sys - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) - -if len(sys.argv) > 1: - name = ' '.join(sys.argv[1:]) -else: - name = 'Radiohead' - -results = sp.search(q='artist:' + name, type='artist') -items = results['artists']['items'] -if len(items) > 0: - artist = items[0] - print(artist['name'], artist['images'][0]['url']) diff --git a/examples/title_chain.py b/examples/title_chain.py deleted file mode 100644 index 0785e7ae..00000000 --- a/examples/title_chain.py +++ /dev/null @@ -1,70 +0,0 @@ -import random - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -''' - generates a list of songs where the first word in each subsequent song - matches the last word of the previous song. - - usage: python title_chain.py [song name] -''' - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - - -skiplist = {'dm', 'remix'} -max_offset = 500 -seen = set() - - -def find_songs_that_start_with_word(word): - max_titles = 20 - max_offset = 200 - offset = 0 - - out = [] - while offset < max_offset and len(out) < max_titles: - results = sp.search(q=word, type='track', limit=50, offset=offset) - if len(results['tracks']['items']) == 0: - break - - for item in results['tracks']['items']: - name = item['name'].lower() - if name in seen: - continue - seen.add(name) - if '(' in name: - continue - if '-' in name: - continue - if '/' in name: - continue - words = name.split() - if len(words) > 1 and words[0] == word \ - and words[-1] not in skiplist: - # print " ", name, len(out) - out.append(item) - offset += 50 - # print "found", len(out), "matches" - return out - - -def make_chain(word): - which = 1 - while True: - songs = find_songs_that_start_with_word(word) - if len(songs) > 0: - song = random.choice(songs) - print(which, song['name'] + " by " + song['artists'][0]['name']) - which += 1 - word = song['name'].lower().split()[-1] - else: - break - - -if __name__ == '__main__': - import sys - title = ' '.join(sys.argv[1:]) - make_chain(sys.argv[1].lower()) diff --git a/examples/track_recommendations.py b/examples/track_recommendations.py deleted file mode 100644 index 563c568a..00000000 --- a/examples/track_recommendations.py +++ /dev/null @@ -1,43 +0,0 @@ -import random - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -# 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(f"{i+1}. {track['name']} by " - f"{', '.join([artist['name'] for artist in track['artists']])}") diff --git a/examples/unfollow_playlist.py b/examples/unfollow_playlist.py deleted file mode 100644 index eebf216a..00000000 --- a/examples/unfollow_playlist.py +++ /dev/null @@ -1,33 +0,0 @@ -import argparse -import logging - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'playlist-modify-public' - -logger = logging.getLogger('examples.unfollow_playlist') -logging.basicConfig(level='DEBUG') - -''' -Spotify doesn't have a dedicated endpoint for deleting a playlist. However, -unfollowing a playlist has the effect of deleting it from the user's account. -When a playlist is removed from the user's account, the system unfollows it, -and then no longer shows it in playlist list.''' - - -def get_args(): - parser = argparse.ArgumentParser(description='Unfollows a playlist') - parser.add_argument('-p', '--playlist', required=True, - help='Playlist id') - return parser.parse_args() - - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - sp.current_user_unfollow_playlist(args.playlist) - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/examples/user_playlists.py b/examples/user_playlists.py deleted file mode 100644 index 69960f2a..00000000 --- a/examples/user_playlists.py +++ /dev/null @@ -1,20 +0,0 @@ -# Shows a user's playlists (need to be authenticated via oauth) - -import sys - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Whoops, need a username!") - print("usage: python user_playlists.py [username]") - sys.exit() - -sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) - -playlists = sp.user_playlists(username) - -for playlist in playlists['items']: - print(playlist['name']) diff --git a/examples/user_playlists_contents.py b/examples/user_playlists_contents.py deleted file mode 100644 index e5a8ee11..00000000 --- a/examples/user_playlists_contents.py +++ /dev/null @@ -1,31 +0,0 @@ -# Shows a user's playlists (need to be authenticated via oauth) - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - - -def show_tracks(results): - for i, item in enumerate(results['items']): - track = item['track'] - print(f" {i} {track['artists'][0]['name']:>32.32} {track['name']}") - - -if __name__ == '__main__': - scope = 'playlist-read-private' - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - - playlists = sp.current_user_playlists() - user_id = sp.me()['id'] - - for playlist in playlists['items']: - if playlist['owner']['id'] == user_id: - print() - print(playlist['name']) - print(' total tracks', playlist['tracks']['total']) - - tracks = sp.playlist_items(playlist['id'], fields="items,next", additional_types=('tracks', )) - show_tracks(tracks) - - while tracks['next']: - tracks = sp.next(tracks) - show_tracks(tracks) diff --git a/examples/user_public_playlists.py b/examples/user_public_playlists.py deleted file mode 100644 index cae7cc01..00000000 --- a/examples/user_public_playlists.py +++ /dev/null @@ -1,26 +0,0 @@ -# Gets all the public playlists for the given -# user. Uses Client Credentials flow -# - -import sys - -import spotipy -from spotipy.oauth2 import SpotifyClientCredentials - -client_credentials_manager = SpotifyClientCredentials() -sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - -user = 'spotify' - -if len(sys.argv) > 1: - user = sys.argv[1] - -playlists = sp.user_playlists(user) - -while playlists: - for i, playlist in enumerate(playlists['items']): - print(f"{i + 1 + playlists['offset']:4d} {playlist['uri']} {playlist['name']}") - if playlists['next']: - playlists = sp.next(playlists) - else: - playlists = None diff --git a/examples/user_saved_albums_delete.py b/examples/user_saved_albums_delete.py deleted file mode 100644 index e071ee83..00000000 --- a/examples/user_saved_albums_delete.py +++ /dev/null @@ -1,12 +0,0 @@ -# Deletes user saved album - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-modify' -sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - -uris = input("input a list of album URIs, URLs or IDs: ") -uris = list(map(str, uris.split())) -deleted = sp.current_user_saved_albums_delete(uris) -print("Deletion successful.") diff --git a/examples/user_saved_episodes.py b/examples/user_saved_episodes.py deleted file mode 100644 index 56dfa51f..00000000 --- a/examples/user_saved_episodes.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -List current user's saved episodes -Usage: user_saved_episodes -l -o -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-read' - -def get_args(): - parser = argparse.ArgumentParser(description='Show user\'s saved episodes') - parser.add_argument('-l', '--limit', default=20, help='Num of episodes to return') - parser.add_argument('-o', '--offset', default=0, help='Index of first show to return') - - return parser.parse_args() - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - results = sp.current_user_saved_episodes(limit=args.limit, offset=args.offset) - # Print episode names - for item in results['items']: - print(item['episode']['name']) - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/examples/user_saved_shows.py b/examples/user_saved_shows.py deleted file mode 100644 index ebe9e0c6..00000000 --- a/examples/user_saved_shows.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -List current user's saved shows -Usage: user_saved_shows -l -o -""" - -import argparse - -import spotipy -from spotipy.oauth2 import SpotifyOAuth - -scope = 'user-library-read' - -def get_args(): - parser = argparse.ArgumentParser(description='Show user\'s saved shows') - parser.add_argument('-l', '--limit', default=20, help='Num of shows to return') - parser.add_argument('-o', '--offset', default=0, help='Index of first show to return') - - return parser.parse_args() - -def main(): - args = get_args() - sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - results = sp.current_user_saved_shows(limit=args.limit, offset=args.offset) - # Print episode names - for item in results['items']: - print(item['show']['name']) - - -if __name__ == '__main__': - main() \ No newline at end of file