<jupyter_start><jupyter_text>myspotipyThis notebook contains some use cases involving the uploaded functions.<jupyter_code>import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import pandas as pd

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="YOUR_APP_CLIENT_ID",
                                                           client_secret="YOUR_APP_CLIENT_SECRET"))<jupyter_output><empty_output><jupyter_text>list_single- This is a basic function that lists all the uploaded singles for a specific artist<jupyter_code>def list_single(uri):
    """ Listing all the online singles for an URI
    
    Parameters
    ----------
    uri : str
        uri of the artist
        'spotify:artist:INSERT_HERE_SPECIFIC_URI_CODE'

    Returns
    -------
    None.
    
    """
    artist = sp.artist(uri)
    print('ARTIST: ',artist['name'])
    print('GENRES: ',artist['genres'])
    print('POPULARITY: ',artist['popularity'])
    print('ACTUAL FOLLOWERS: ',artist['followers'])
    print('uri: ',artist['uri'])
    print('external_urls: ',artist['external_urls'],'\n')
    
    results = sp.artist_albums(uri, album_type='single')
    albums = results['items']
    name = []
    release_date = []
    total_tracks = []
    
    while results['next']:
        results = sp.next(results)
        albums.extend(results['items'])
    
    print('SINGLES UPLOADED:\n')
    
    for album in albums:
        name.append(album['name'])
        release_date.append(album['release_date'])
        total_tracks.append(album['total_tracks'])
    
    col = ['name','release_date','total_tracks']
    df = pd.DataFrame(list(zip(name,release_date,total_tracks)),columns=col).drop_duplicates(subset='name')
    print(df)
    
    print('\n---------------------------------------------------------------------------------\n')
        
    return None

# arctic example
list_single('spotify:artist:7Ln80lUS6He07XvHI8qqHH')
# razorbacks example
list_single('spotify:artist:3zAvbJuxv6xgNuROqGSmUA')<jupyter_output>ARTIST:  The Razorbacks
GENRES:  []
POPULARITY:  0
ACTUAL FOLLOWERS:  {'href': None, 'total': 5}
uri:  spotify:artist:3zAvbJuxv6xgNuROqGSmUA
external_urls:  {'spotify': 'https://open.spotify.com/artist/3zAvbJuxv6xgNuROqGSmUA'} 

SINGLES UPLOADED:

        name release_date  total_tracks
0         BB   2015-12-25             1
1  Sometimes   2015-09-27             4
2    Outlook   2013-11-07             2

---------------------------------------------------------------------------------<jupyter_text>list_album- This is a basic function that lists all the uploaded albums for a specific artist.<jupyter_code>def list_album(uri):
    """ Listing all the online albums for an artist
    
    Parameters
    ----------
    uri : str
        uri of the artist.
        'spotify:artist:INSERT_HERE_SPECIFIC_URI_CODE'

    Returns
    -------
    None.

    """
    artist = sp.artist(uri)
    print('ARTIST: ',artist['name'])
    print('GENRES: ',artist['genres'])
    print('POPULARITY: ',artist['popularity'])
    print('ACTUAL FOLLOWERS: ',artist['followers'])
    print('uri: ',artist['uri'])
    print('external_urls: ',artist['external_urls'],'\n')
   
    results = sp.artist_albums(uri, album_type='album')
    albums = results['items']
    name = []
    release_date = []
    total_tracks = []
    
    
    while results['next']:
        results = sp.next(results)
        albums.extend(results['items'])
    
    print('ALBUM:\n')
    
    for album in albums:
        name.append(album['name'])
        release_date.append(album['release_date'])
        total_tracks.append(album['total_tracks'])
    
    col = ['name','release_date','total_tracks']
    df = pd.DataFrame(list(zip(name,release_date,total_tracks)),columns=col).drop_duplicates(subset=['release_date'],keep='first')
    print(df)
    
    print('\n---------------------------------------------------------------------------------------------\n')
    
    return None

# green day example
list_album('spotify:artist:7oPftvlwr6VrsViSDV7fJY')
# dire straits example
list_album('https://open.spotify.com/artist/0WwSkZ7LtFUFjGjMZBMt6T')<jupyter_output>ARTIST:  Dire Straits
GENRES:  ['album rock', 'classic rock', 'mellow gold', 'rock', 'soft rock']
POPULARITY:  77
ACTUAL FOLLOWERS:  {'href': None, 'total': 4171858}
uri:  spotify:artist:0WwSkZ7LtFUFjGjMZBMt6T
external_urls:  {'spotify': 'https://open.spotify.com/artist/0WwSkZ7LtFUFjGjMZBMt6T'} 

ALBUM:

                          name release_date  total_tracks
0              Live At The BBC   1995-06-26             8
2                 On the Night   1993-05-10            10
4              On Every Street   1991-09-10            12
6             Brothers In Arms   1985-05-13             9
9   Alchemy: Dire Straits Live   1984-03-14            11
10              Love Over Gold   1982-09-20             5
12               Making Movies   1980-10-17             7
14                  Communiqué   1979-06-15             9
16                Dire Straits   1978-10-07             9

---------------------------------------------------------------------------------------------<jupyter_text>list_album_tracks- This is a basic function that lists the tracks for a specific album.<jupyter_code>def list_album_tracks(uri):
    """ List all the tracks for an album

    Parameters
    ----------
    uri : str
        uri/url of the album
        'spotify:artist:INSERT_HERE_SPECIFIC_URI_CODE'

    Returns
    -------
    None.

    """
    album = sp.album(uri)

    print('ALBUM NAME: ',album['name'])
    print('ARTIST: ',album['artists'][0]['name'])
    print('TYPE: ',album['album_type'])
    print('RELEASE DATE: ',album['release_date'])
    print('POPULARITY: ',album['popularity'],'\n')
    
    album_tracks = sp.album_tracks(uri)
    
    print('TRACKS: \n')
    
    for i in range(len(album_tracks['items'])):
        print('({}):'.format(i+1),album_tracks['items'][i]['name'])
     
    print('\n---------------------------------------------------------------------------------\n')   
     
    return None

# Whatever People Say I Am, That's What I'm Not example
list_album_tracks('https://open.spotify.com/album/50Zz8CkIhATKUlQMbHO3k1')
# Game of Thrones (Music from the HBO® Series - Season 6) example
list_album_tracks('https://open.spotify.com/album/7bBlW6L9r3ICFkbf2WRDXL')
# Dookie example
list_album_tracks('https://open.spotify.com/album/4uG8q3GPuWHQlRbswMIRS6')<jupyter_output>ALBUM NAME:  Dookie
ARTIST:  Green Day
TYPE:  album
RELEASE DATE:  1994-02-01
POPULARITY:  78 

TRACKS: 

(1): Burnout
(2): Having a Blast
(3): Chump
(4): Longview
(5): Welcome to Paradise
(6): Pulling Teeth
(7): Basket Case
(8): She
(9): Sassafras Roots
(10): When I Come Around
(11): Coming Clean
(12): Emenius Sleepus
(13): In the End
(14): F.O.D.
(15): All by Myself

---------------------------------------------------------------------------------<jupyter_text>playlist_to_df- This function takes as input the identifier of a playlist and returns it as a pandas DataFrame<jupyter_code>def playlist_to_df(uri):
    """ transforming a playlist into a df (max 595 songs)
    

    Parameters
    ----------
    uri : str
        uri/url of the album
        'spotify:artist:INSERT_HERE_SPECIFIC_URI_CODE'

    Returns
    -------
    df : pd.DataFrame
        DataFrame of the playlist in order to perform some actions

    """
    playlist_1 = sp.playlist(uri)
    playlist_2 = sp.playlist_items(uri,limit=None,offset=0)
    playlist_3 = sp.playlist_items(uri,limit=None,offset=99)
    playlist_4 = sp.playlist_items(uri,limit=None,offset=198)
    playlist_5 = sp.playlist_items(uri,limit=None,offset=297)
    playlist_6 = sp.playlist_items(uri,limit=None,offset=396)
    playlist_7 = sp.playlist_items(uri,limit=None,offset=495)
    
    all_playlist = [playlist_2, playlist_3, playlist_4, playlist_5, playlist_6, playlist_7]
    
    print('name: ', playlist_1['name'])
    print('public: ',playlist_1['public'])
    print('collaborative: ',playlist_1['collaborative'])
    print('description: ',playlist_1['description'])
    print('followers: ', playlist_1['followers']['total'])
    print('\n---------------------------------------------------------------------------------\n')
    
    artist_name = []
    album_name = []
    track_name = []
    track_number = []
    popularity = []
    uris = []
    col = ['artist','album','track_name','track_number','popularity','uri']
    
    for playlist in all_playlist:
        if playlist != 0:
            for i in range(len(playlist['items'])):
                artist_name.append(playlist['items'][i]['track']['artists'][0]['name'])
                album_name.append(playlist['items'][i]['track']['album']['name'])
                track_name.append(playlist['items'][i]['track']['name'])
                track_number.append(playlist['items'][i]['track']['track_number'])
                popularity.append(playlist['items'][i]['track']['popularity'])
                uris.append(playlist['items'][i]['track']['artists'][0]['uri'])
        else:
            pass
    

    df = pd.DataFrame(list(zip(artist_name,album_name,track_name,track_number,popularity,uris)), columns=col)
    
    print('<DataFrame completed>')
    print('\n---------------------------------------------------------------------------------\n')
        
    return df

# pyhton example
df_1 = playlist_to_df('https://open.spotify.com/playlist/4KVBI6CgDDldQGlQ5BihaU')
df_1
print('Number of different artists: ',len(set(df_1.artist)))
df_1_artists = list(set(df_1.artist))
df_1_artists.sort(reverse=False)
print('List of artists: ',df_1_artists)
print('\n---------------------------------------------------------------------------------\n')
# save a txt file in the same folder with these information, it can be used for playlist description

#with open('playlist_df_1.txt','w',encoding="utf-8") as txt:
#    txt.write('Number of different artists: '+str(len(set(df_1.artist)))+'-------- \n')
#    for element in df_1_artists:
#        txt.write('%s'%element+'/')<jupyter_output><empty_output><jupyter_text>playlist_to_artists_df- This function takes as input the identifier of a playlist and returns a pandas DataFrame containing the set of artists and their identifier in order to have a DataFrame to perform other operations.<jupyter_code>def playlist_to_artists_df(uri):
    """ transforming a playlist into a df of artists and uris (max 595 songs)
    

    Parameters
    ----------
    uri : str
        uri/url of the album
        'spotify:artist:INSERT_HERE_SPECIFIC_URI_CODE'

    Returns
    -------
    df : pd.DataFrame
        DataFrame of the playlist in order to perform some actions

    """
    playlist_1 = sp.playlist(uri)
    playlist_2 = sp.playlist_items(uri,limit=None,offset=0)
    playlist_3 = sp.playlist_items(uri,limit=None,offset=99)
    playlist_4 = sp.playlist_items(uri,limit=None,offset=198)
    playlist_5 = sp.playlist_items(uri,limit=None,offset=297)
    playlist_6 = sp.playlist_items(uri,limit=None,offset=396)
    playlist_7 = sp.playlist_items(uri,limit=None,offset=495)
    
    all_playlist = [playlist_2, playlist_3, playlist_4, playlist_5, playlist_6, playlist_7]
    
    print('name: ', playlist_1['name'])
    print('public: ',playlist_1['public'])
    print('collaborative: ',playlist_1['collaborative'])
    print('description: ',playlist_1['description'])
    print('followers: ', playlist_1['followers']['total'])
    print('\n---------------------------------------------------------------------------------\n')
    
    artist_name = []
    uris = []
    col = ['artist','uri']
    
    for playlist in all_playlist:
        if playlist != 0:
            for i in range(len(playlist['items'])):
                artist_name.append(playlist['items'][i]['track']['artists'][0]['name'])
                uris.append(playlist['items'][i]['track']['artists'][0]['uri'])
        else:
            pass
    

    df = pd.DataFrame(list(zip(artist_name,uris)), columns=col).drop_duplicates(subset=['uri'],keep='first')
    
    print('<DataFrame completed>')
    print('\n---------------------------------------------------------------------------------\n')
        
    return df

# the adults are talking example
df_1 = playlist_to_artists_df('https://open.spotify.com/playlist/2rQTtxMfmdrQOWHeEbStwM')
df_1
print('Number of different artists: ',len(set(df_1.artist)))<jupyter_output>Number of different artists:  72<jupyter_text>- so, once this function created the DataFrame we can perform other operation like suggesting artists starting with those contained in the playlist, using spotify information.    artist_df_suggested_artists_df- This function takes as input a DataFrame, that needs to contain the identifier of the artists, and returns another DataFrame that contains the information regarding the suggested artists.<jupyter_code>def artist_df_suggested_artists_df(df):
    """ From a df containing the information of a playlist, this function, suggests for the 15 most featured 
    artists a dataframe of related artists according to spotify.  similarity is based on analysis of the 
    spotify community’s listening history.

    df : pd.DataFrame (containing the columns 'artist' & 'uri')
        iterable containing the uris/urls of the artists
        'spotify:artist:INSERT_HERE_SPECIFIC_URI_CODE'

    Returns
    -------
    rel_df : pd.DataFrame
        DataFrame of the suggested artists in order to perform some actions

    """
    most_frequent = df['uri'].value_counts().head(15).to_frame('uri').index
    
    rel_name = []
    rel_genres = []
    rel_uri = []
    rel_pop = []
    rel_col = ['name','genres','uri','popularity']
    
    for uri in most_frequent:
        for i in range(len(sp.artist_related_artists(uri)['artists'])):
            rel_name.append(sp.artist_related_artists(uri)['artists'][i]['name'])
            rel_genres.append(sp.artist_related_artists(uri)['artists'][i]['genres'])
            rel_uri.append(sp.artist_related_artists(uri)['artists'][i]['uri'])
            rel_pop.append(sp.artist_related_artists(uri)['artists'][i]['popularity'])
            
    rel_df = pd.DataFrame(list(zip(rel_name,rel_genres,rel_uri,rel_pop)),columns=(rel_col)).drop_duplicates(subset=['name'],keep='first')
    
    print('<DataFrame completed>')
    print('\n---------------------------------------------------------------------------------\n')
        
    return rel_df<jupyter_output><empty_output><jupyter_text>- so, we use the previous function to obtain the DataFrame from which we want to get the suggested artists.<jupyter_code># sweet children's example
df = playlist_to_artists_df('https://open.spotify.com/playlist/0tLuWKIJqwMwj1RGSxZYYS?si=qoMitK0tQ46OLV56HJR2Mw')
rel_df = artist_df_suggested_artists_df(df)
rel_df<jupyter_output><DataFrame completed>

---------------------------------------------------------------------------------<jupyter_text>- now, we can also use the available info to filter the results as we want.<jupyter_code># example only if popularity is >= 70
rel_df[rel_df['popularity']>=70].sort_values('popularity',ascending=False)
# example only if popularity is <= 40 
rel_df[rel_df['popularity']<=40].sort_values('popularity',ascending=True)<jupyter_output><empty_output><jupyter_text>- now, we have a DataFrame of suggested artists, maybe can be usefull also obtaining some of their most famous tracks.  top_tracks- This is the basic function to obtain the top tracks of an artist. Then, the function will be developed in such a way to receive as input a DataFrame of artists.<jupyter_code>def top_tracks(artist, country, number_of_tracks):
    """ Get Spotify catalog information about an artist’s top 10 tracks by country.

    Parameters
    ----------
    artist : str
        uri/url/ID of the objective artist.
    country : str
        ex. 'US' in order to list the top tracks limiting the response to one particular country

    Returns
    -------
    None.

    """
    print('The objective aritst is: '+sp.artist(artist)['name'],'\n')
    
    for i in range(number_of_tracks):
        print('({}):'.format(i+1),sp.artist_top_tracks(artist,country=country)['tracks'][i]['name'])
        print('album: {}'.format(sp.artist_top_tracks(artist,country=country)['tracks'][i]['album']['name']))
        print('--------------\n')
        
    return None

# arctic example
top_tracks('spotify:artist:7Ln80lUS6He07XvHI8qqHH', 'IT', 7)<jupyter_output>The objective aritst is: Arctic Monkeys 

(1): Do I Wanna Know?
album: AM
--------------

(2): Why'd You Only Call Me When You're High?
album: AM
--------------

(3): I Wanna Be Yours
album: AM
--------------

(4): R U Mine?
album: AM
--------------

(5): 505
album: Favourite Worst Nightmare
--------------

(6): Fluorescent Adolescent
album: Favourite Worst Nightmare
--------------

(7): Arabella
album: AM
--------------<jupyter_text>artists_df_top_tracks_df- This function takes as input a DataFrame of different artists and returns their top tracks.<jupyter_code>def artists_df_top_tracks_df(df, country, number_of_tracks):
    """ From a df containing information of different artists, this function, suggests for every artist 
    dataframe of their top tracks according to spotify, limiting the response to one particular country.  
    
    Parameters
    ----------
    df : pd.DataFrame(containing the columns 'artist' & 'uri')
        iterable containing the uris/urls of the artists
        'spotify:artist:INSERT_HERE_SPECIFIC_URI_CODE'.
    country : str
        ex. 'US' in order to list the top tracks limiting the response to one particular country.
    number_of_tracks : int
        choose the number of top tracks to return for each artist.

    Returns
    -------
    top_tracks_df: pd.DataFrame
        DataFrame of the top tracks.

    """
    
    artist_name = []
    track_position = []
    track_name = []
    album_name = []
    uris = []
    col_name = ['artist','position','track','album','uri']
    
    artist_to_analyze = df['uri']
    
    for uri in artist_to_analyze:
        for i in range(number_of_tracks):
            artist_name.append(sp.artist(uri)['name'])
            track_position.append('({})'.format(i+1))
            track_name.append(sp.artist_top_tracks(uri,country=country)['tracks'][i]['name'])
            album_name.append(sp.artist_top_tracks(uri,country=country)['tracks'][i]['album']['name'])
            uris.append(sp.artist(uri)['uri'])
            
    top_tracks_df = pd.DataFrame(list(zip(artist_name, track_position, track_name, album_name, uris)),columns=(col_name))
    top_tracks_df = top_tracks_df.drop_duplicates(subset=['track'],keep='first')
    
    
    print('<DataFrame completed>')
    print('\n---------------------------------------------------------------------------------\n')
        
    return top_tracks_df

# the adults are talking example
df = playlist_to_artists_df('https://open.spotify.com/playlist/2rQTtxMfmdrQOWHeEbStwM')
top_tracks_df = artists_df_top_tracks_df(df, 'IT', 3)
top_tracks_df<jupyter_output><empty_output><jupyter_text>- You are saying all the words I'm dreaming<jupyter_code>for artist in set(top_tracks_df['uri']):
    top_tracks(artist, 'IT', 3)<jupyter_output>The objective aritst is: The Smiths 

(1): There Is a Light That Never Goes Out - 2011 Remaster
album: The Queen Is Dead
--------------

(2): This Charming Man - 2011 Remaster
album: The Smiths
--------------

(3): How Soon Is Now? - 2011 Remaster
album: Hatful of Hollow
--------------

The objective aritst is: The Muffs 

(1): Kids in America
album: Hamburger
--------------

(2): Sad Tomorrow
album: Blonder And Blonder
--------------

(3): Lucky Guy
album: The Muffs
--------------

The objective aritst is: Modern Baseball 

(1): Your Graduation
album: You're Gonna Miss It All
--------------

(2): Fine, Great
album: You're Gonna Miss It All
--------------

(3): Tears Over Beers
album: Sports
--------------

The objective aritst is: The Snuts 

(1): <NAME>
album: Juan Belmonte
--------------

(2): Elephants
album: Elephants
--------------

(3): Always
album: Always
--------------

The objective aritst is: The Smashing Pumpkins 

(1): 1979 - Remastered 2012
album: <NAME> An[...]
{'fraction_non_alphanumeric': 0.19069284407299342, 'fraction_numerical': 0.019187972899460958, 'mean_word_length': 2.559584580179546, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 51, 'https://': 10, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '404007', 'license': 'Apache-2.0', 'n_tokens_mistral': 6573, 'n_tokens_neox': 6267, 'n_words': 1432, 'path': 'use cases/myspotipy_use_cases_1.ipynb', 'repo_name': 'falble/spotipy', 'size': '20235'}