Update app.py
Browse files
app.py
CHANGED
@@ -15,6 +15,154 @@ from spotipy import oauth2
|
|
15 |
|
16 |
import heatmap
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
PORT_NUMBER = 8080
|
19 |
SPOTIPY_CLIENT_ID = 'c087fa97cebb4f67b6f08ba841ed8378'
|
20 |
SPOTIPY_CLIENT_SECRET = 'ae27d6916d114ac4bb948bb6c58a72d9'
|
@@ -103,6 +251,8 @@ with gr.Blocks() as demo:
|
|
103 |
gr.Markdown("This app analyzes how cool your music taste is. We dare you to take this challenge!")
|
104 |
with gr.Row():
|
105 |
get_started_btn = gr.Button("Get Started")
|
|
|
|
|
106 |
with gr.Row():
|
107 |
with gr.Column():
|
108 |
with gr.Row():
|
@@ -126,6 +276,7 @@ with gr.Blocks() as demo:
|
|
126 |
)
|
127 |
demo.load(fn=scatter_plot_fn, outputs=plot)
|
128 |
demo.load(fn=heatmap_plot_fn, output=hm_plot)
|
|
|
129 |
|
130 |
|
131 |
gradio_app = gr.mount_gradio_app(app, demo, "/gradio")
|
|
|
15 |
|
16 |
import heatmap
|
17 |
|
18 |
+
import numpy as np
|
19 |
+
|
20 |
+
import matplotlib.pyplot as plt
|
21 |
+
from matplotlib.patches import Circle, RegularPolygon
|
22 |
+
from matplotlib.path import Path
|
23 |
+
from matplotlib.projections.polar import PolarAxes
|
24 |
+
from matplotlib.projections import register_projection
|
25 |
+
from matplotlib.spines import Spine
|
26 |
+
from matplotlib.transforms import Affine2D
|
27 |
+
import matplotlib
|
28 |
+
|
29 |
+
matplotlib.use('SVG')
|
30 |
+
|
31 |
+
|
32 |
+
def get_features2(spotify):
|
33 |
+
features = []
|
34 |
+
for index in range(0, 10):
|
35 |
+
results = spotify.current_user_saved_tracks(offset=index*50, limit=50)
|
36 |
+
track_ids = [item['track']['id'] for item in results['items']]
|
37 |
+
features.extend(spotify.audio_features(track_ids))
|
38 |
+
|
39 |
+
df = pd.DataFrame(data=features)
|
40 |
+
names = [
|
41 |
+
'danceability',
|
42 |
+
'energy',
|
43 |
+
# 'loudness',
|
44 |
+
'speechiness',
|
45 |
+
'acousticness',
|
46 |
+
'instrumentalness',
|
47 |
+
'liveness',
|
48 |
+
'valence',
|
49 |
+
]
|
50 |
+
return names, features_means.values
|
51 |
+
|
52 |
+
|
53 |
+
def radar_factory(num_vars, frame='circle'):
|
54 |
+
"""
|
55 |
+
Create a radar chart with `num_vars` axes.
|
56 |
+
|
57 |
+
This function creates a RadarAxes projection and registers it.
|
58 |
+
|
59 |
+
Parameters
|
60 |
+
----------
|
61 |
+
num_vars : int
|
62 |
+
Number of variables for radar chart.
|
63 |
+
frame : {'circle', 'polygon'}
|
64 |
+
Shape of frame surrounding axes.
|
65 |
+
|
66 |
+
"""
|
67 |
+
# calculate evenly-spaced axis angles
|
68 |
+
theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)
|
69 |
+
|
70 |
+
class RadarTransform(PolarAxes.PolarTransform):
|
71 |
+
|
72 |
+
def transform_path_non_affine(self, path):
|
73 |
+
# Paths with non-unit interpolation steps correspond to gridlines,
|
74 |
+
# in which case we force interpolation (to defeat PolarTransform's
|
75 |
+
# autoconversion to circular arcs).
|
76 |
+
if path._interpolation_steps > 1:
|
77 |
+
path = path.interpolated(num_vars)
|
78 |
+
return Path(self.transform(path.vertices), path.codes)
|
79 |
+
|
80 |
+
class RadarAxes(PolarAxes):
|
81 |
+
|
82 |
+
name = 'radar'
|
83 |
+
PolarTransform = RadarTransform
|
84 |
+
|
85 |
+
def __init__(self, *args, **kwargs):
|
86 |
+
super().__init__(*args, **kwargs)
|
87 |
+
# rotate plot such that the first axis is at the top
|
88 |
+
self.set_theta_zero_location('N')
|
89 |
+
|
90 |
+
def fill(self, *args, closed=True, **kwargs):
|
91 |
+
"""Override fill so that line is closed by default"""
|
92 |
+
return super().fill(closed=closed, *args, **kwargs)
|
93 |
+
|
94 |
+
def plot(self, *args, **kwargs):
|
95 |
+
"""Override plot so that line is closed by default"""
|
96 |
+
lines = super().plot(*args, **kwargs)
|
97 |
+
for line in lines:
|
98 |
+
self._close_line(line)
|
99 |
+
|
100 |
+
def _close_line(self, line):
|
101 |
+
x, y = line.get_data()
|
102 |
+
# FIXME: markers at x[0], y[0] get doubled-up
|
103 |
+
if x[0] != x[-1]:
|
104 |
+
x = np.append(x, x[0])
|
105 |
+
y = np.append(y, y[0])
|
106 |
+
line.set_data(x, y)
|
107 |
+
|
108 |
+
def set_varlabels(self, labels):
|
109 |
+
self.set_thetagrids(np.degrees(theta), labels)
|
110 |
+
|
111 |
+
def _gen_axes_patch(self):
|
112 |
+
# The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
|
113 |
+
# in axes coordinates.
|
114 |
+
if frame == 'circle':
|
115 |
+
return Circle((0.5, 0.5), 0.5)
|
116 |
+
elif frame == 'polygon':
|
117 |
+
return RegularPolygon((0.5, 0.5), num_vars,
|
118 |
+
radius=.5, edgecolor="k")
|
119 |
+
else:
|
120 |
+
raise ValueError("Unknown value for 'frame': %s" % frame)
|
121 |
+
|
122 |
+
def _gen_axes_spines(self):
|
123 |
+
if frame == 'circle':
|
124 |
+
return super()._gen_axes_spines()
|
125 |
+
elif frame == 'polygon':
|
126 |
+
# spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
|
127 |
+
spine = Spine(axes=self,
|
128 |
+
spine_type='circle',
|
129 |
+
path=Path.unit_regular_polygon(num_vars))
|
130 |
+
# unit_regular_polygon gives a polygon of radius 1 centered at
|
131 |
+
# (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
|
132 |
+
# 0.5) in axes coordinates.
|
133 |
+
spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
|
134 |
+
+ self.transAxes)
|
135 |
+
return {'polar': spine}
|
136 |
+
else:
|
137 |
+
raise ValueError("Unknown value for 'frame': %s" % frame)
|
138 |
+
|
139 |
+
register_projection(RadarAxes)
|
140 |
+
return theta
|
141 |
+
|
142 |
+
def get_spider_plot(request: gr.Request):
|
143 |
+
token = request.request.session.get('token')
|
144 |
+
sp = spotipy.Spotify(token)
|
145 |
+
names, data = get_features2(sp)
|
146 |
+
|
147 |
+
theta = radar_factory(len(names), frame='polygon')
|
148 |
+
|
149 |
+
fig = plt.figure(figsize=(9, 9))
|
150 |
+
ax = fig.add_axes([0, 0, 1, 1], projection='radar')
|
151 |
+
|
152 |
+
# Plot the four cases from the example data on separate axes
|
153 |
+
title = 'test'
|
154 |
+
ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
|
155 |
+
ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
|
156 |
+
horizontalalignment='center', verticalalignment='center')
|
157 |
+
|
158 |
+
ax.plot(theta, data)
|
159 |
+
ax.fill(theta, data, alpha=0.25, label='_nolegend_')
|
160 |
+
|
161 |
+
ax.set_varlabels(names)
|
162 |
+
|
163 |
+
return fig
|
164 |
+
|
165 |
+
|
166 |
PORT_NUMBER = 8080
|
167 |
SPOTIPY_CLIENT_ID = 'c087fa97cebb4f67b6f08ba841ed8378'
|
168 |
SPOTIPY_CLIENT_SECRET = 'ae27d6916d114ac4bb948bb6c58a72d9'
|
|
|
251 |
gr.Markdown("This app analyzes how cool your music taste is. We dare you to take this challenge!")
|
252 |
with gr.Row():
|
253 |
get_started_btn = gr.Button("Get Started")
|
254 |
+
with gr.Row():
|
255 |
+
spider_plot = gr.Plot()
|
256 |
with gr.Row():
|
257 |
with gr.Column():
|
258 |
with gr.Row():
|
|
|
276 |
)
|
277 |
demo.load(fn=scatter_plot_fn, outputs=plot)
|
278 |
demo.load(fn=heatmap_plot_fn, output=hm_plot)
|
279 |
+
demo.load(fn=get_spider_plot, outputs=spider_plot)
|
280 |
|
281 |
|
282 |
gradio_app = gr.mount_gradio_app(app, demo, "/gradio")
|