-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextraction.py
70 lines (60 loc) · 3.04 KB
/
extraction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import pandas as pd
import spotipy
from spotipy.oauth2 import SpotifyOAuth
def get_trending_playlist_data(playlist_id, access_token):
# Set up Spotipy with the access token
sp = spotipy.Spotify(auth=access_token)
# Get the tracks from the playlist
playlist_tracks = sp.playlist_tracks(playlist_id, fields='items(track(id, name, artists, album(id, name)))')
# Extract relevant information and store in a list of dictionaries
music_data = []
for track_info in playlist_tracks['items']:
track = track_info['track']
track_name = track['name']
artists = ', '.join([artist['name'] for artist in track['artists']])
album_name = track['album']['name']
album_id = track['album']['id']
track_id = track['id']
# Get audio features for the track
audio_features = sp.audio_features(track_id)[0] if track_id != 'Not available' else None
# Get release date of the album
try:
album_info = sp.album(album_id) if album_id != 'Not available' else None
release_date = album_info['release_date'] if album_info else None
except:
release_date = None
# Get popularity of the track
try:
track_info = sp.track(track_id) if track_id != 'Not available' else None
popularity = track_info['popularity'] if track_info else None
except:
popularity = None
# Add additional track information to the track data
track_data = {
'Track Name': track_name,
'Artists': artists,
'Album Name': album_name,
'Album ID': album_id,
'Track ID': track_id,
'Popularity': popularity,
'Release Date': release_date,
'Duration (ms)': audio_features['duration_ms'] if audio_features else None,
'Explicit': track_info.get('explicit', None),
'External URLs': track_info.get('external_urls', {}).get('spotify', None),
'Danceability': audio_features['danceability'] if audio_features else None,
'Energy': audio_features['energy'] if audio_features else None,
'Key': audio_features['key'] if audio_features else None,
'Loudness': audio_features['loudness'] if audio_features else None,
'Mode': audio_features['mode'] if audio_features else None,
'Speechiness': audio_features['speechiness'] if audio_features else None,
'Acousticness': audio_features['acousticness'] if audio_features else None,
'Instrumentalness': audio_features['instrumentalness'] if audio_features else None,
'Liveness': audio_features['liveness'] if audio_features else None,
'Valence': audio_features['valence'] if audio_features else None,
'Tempo': audio_features['tempo'] if audio_features else None,
# Add more attributes as needed
}
music_data.append(track_data)
# Create a pandas DataFrame from the list of dictionaries
df = pd.DataFrame(music_data)
return df