-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspotify_test.py
More file actions
124 lines (98 loc) · 3.47 KB
/
spotify_test.py
File metadata and controls
124 lines (98 loc) · 3.47 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import spotipy
import pandas as pd
from spotipy.oauth2 import SpotifyClientCredentials
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
from math import pi
from credentials import client_id, client_secret
min_max_scaler = MinMaxScaler()
client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# playlist_id = "spotify:playlist:3lRvb9RIb0MyUTU4O0IZAv"
def playlist_stats(playlist_url):
temp = playlist_url.split("/")[::-1]
playlist_id = "spotify:" + temp[1] + ":" + temp[0].split("?")[0]
results = sp.playlist(playlist_id)
# create a list of song ids
ids = []
for item in results["tracks"]["items"]:
track = item["track"]["id"]
ids.append(track)
song_meta = {
"id": [],
"album": [],
"name": [],
"artist": [],
"explicit": [],
"popularity": [],
}
for song_id in ids:
# get song's meta data
meta = sp.track(song_id)
# song id
song_meta["id"].append(song_id)
# album name
album = meta["album"]["name"]
song_meta["album"] += [album]
# song name
song = meta["name"]
song_meta["name"] += [song]
# artists name
s = ", "
artist = s.join([singer_name["name"] for singer_name in meta["artists"]])
song_meta["artist"] += [artist]
# explicit: lyrics could be considered offensive or unsuitable for children
explicit = meta["explicit"]
song_meta["explicit"].append(explicit)
# song popularity
popularity = meta["popularity"]
song_meta["popularity"].append(popularity)
song_meta_df = pd.DataFrame.from_dict(song_meta)
song_meta_df = pd.DataFrame.from_dict(song_meta)
# check the song feature
features = sp.audio_features(song_meta["id"])
# change dictionary to dataframe
features_df = pd.DataFrame.from_dict(features)
# convert milliseconds to mins
# duration_ms: The duration of the track in milliseconds.
# 1 minute = 60 seconds = 60 × 1000 milliseconds = 60,000 ms
features_df["duration_ms"] = features_df["duration_ms"] / 60000
# combine two dataframe
final_df = song_meta_df.merge(features_df)
music_feature = features_df[
[
"danceability",
"energy",
"loudness",
"speechiness",
"acousticness",
"instrumentalness",
"liveness",
"valence",
"tempo",
"duration_ms",
]
]
music_feature.loc[:] = min_max_scaler.fit_transform(music_feature.loc[:])
# plot size
fig = plt.figure(figsize=(12, 8))
# convert column names into a list
categories = list(music_feature.columns)
# number of categories
N = len(categories)
# create a list with the average of all features
value = list(music_feature.mean())
# repeat first value to close the circle
# the plot is a circle, so we need to "complete the loop"
# and append the start value to the end.
value += value[:1]
# calculate angle for each category
angles = [n / float(N) * 2 * pi for n in range(N)]
angles += angles[:1]
# plot
plt.polar(angles, value)
plt.fill(angles, value, alpha=0.3)
plt.xticks(angles[:-1], categories, size=15)
plt.yticks(color="grey", size=15)
# plt.plot()
plt.savefig("templates/images/new_plot.pdf")