SongsReleased2017DataFormation



In [ ]:
import spotipy
import pprint
import json
from spotipy.oauth2 import SpotifyClientCredentials
import pandas as pd
import numpy as np

keys = {}
i=0

def getAudioFeature(id):
    feature = sp.audio_features(id)
    if feature[0]:
        s = pd.Series([feature[(0)]['danceability'], feature[(0)]['energy'], feature[(0)]['key'], feature[(0)]['loudness'],
                   feature[(0)]['mode'], feature[(0)]['speechiness'], feature[(0)]['acousticness'], feature[(0)]['instrumentalness'],
                   feature[(0)]['liveness'], feature[(0)]['valence'], feature[(0)]['tempo'], feature[(0)]['duration_ms'],
                   feature[(0)]['time_signature'] ],
                   index=['Danceability', 'Energy', 'Key', 'Loudness', 'Mode', 'Speechiness',
                          'Acousticness', 'Instrumentalness', 'Liveness', 'Valence', 'Tempo',
                          'Duration_ms', 'Time_signature'])
        return s
    else:
        return pd.Series()


with open('keys.txt') as fp:
    for line in fp:
        keys[i] = line
        i = i+1
print(keys[0])
print(keys[1])
client_credentials_manager = SpotifyClientCredentials(client_id= keys[0],client_secret= keys[1])
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

songTest = pd.DataFrame(columns=['Song Name','Artists Name', 'Danceability', 'Energy',
                                 'Key', 'Loudness', 'Mode', 'Speechiness', 'Acousticness', 'Instrumentalness',
                                 'Liveness', 'Valence', 'Tempo', 'Duration_ms', 'Time_signature'])

results = sp.search(q='year:2017', market='US', type='track', limit = 50, offset = 0)
offset = 0
while(results['tracks']['items']):
    for element in results['tracks']['items']:
        artistList = []
        for artist in element['artists']:
            artistList.append(artist['name'])

        artistString = ",".join(artistList)
        s = pd.Series(element['name'], index=['Song Name'])
        s = s.append(pd.Series(artistString, index=['Artists Name']))
        audioFeature = getAudioFeature(element['id'])
        if not audioFeature.empty:
            s = s.append(audioFeature)
            songTest = songTest.append(s,ignore_index=True)
    if not results['tracks']['next']:
        results['tracks']['items'] = False
    else:
        offset = offset + 50
        print(offset)
        results = sp.search(q='year:2017', market='US', type='track', limit = 50, offset = offset)

In [ ]:
songTest.to_csv('SongReleased2017WithFeatures.csv')

In [ ]: