-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualization.py
1593 lines (1290 loc) · 61 KB
/
visualization.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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# visualization.py = contains Page Classes which have some unique and shared functions to make graphs
# Imports --------------------------------------------------------------------
import pickle
from collections import defaultdict
import datetime
from re import A
import pandas as pd
from flask import Markup
from matplotlib_venn import venn3
from matplotlib_venn import venn2
import base64
from matplotlib import pyplot as plt
from io import BytesIO
from plotly import subplots
import plotly.figure_factory as ff
import plotly.express as px
import plotly.graph_objs as go
import plotly
import os
import tempfile
temp_dir = tempfile.TemporaryDirectory()
os.environ['MPLCONFIGDIR'] = temp_dir.name
# Constants -------------------------------------------------------------------
PERCENTILE_COLS = ['popularity', 'danceability', 'energy', 'loudness',
'speechiness', 'acousticness', 'instrumentalness',
'liveness', 'valence', 'tempo', 'duration']
FEATURE_COLS = ['popularity', 'danceability', 'energy', 'speechiness', 'acousticness',
'instrumentalness', 'liveness', 'valence']
OTHER_COLS = ['loudness', 'tempo', 'duration']
LABEL_CUTOFF_LENGTH = 25
TIME_RANGE_DICT = {0: ['Last 4 Weeks', 'short_rank'], 1: [
'Last 6 Months', 'med_rank'], 2: ['All Time', 'long_rank']}
COLORS = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A',
'#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52']
# Helper Functions -----------------------------------------------------------------------------------------
def _h_bar(series, title=None, xaxis=None, yaxis=None, percents=False,
long_names=False, hovertext=None, to_html=True, name=None, color=None, markup=True):
if percents:
texty = [str(round(i, 2)) + '%' for i in series]
else:
texty = series
if long_names:
y_labels = [i if len(
i) < LABEL_CUTOFF_LENGTH else i[:LABEL_CUTOFF_LENGTH] + '...' for i in series.keys()]
else:
y_labels = series.keys()
fig = go.Bar(
x=series,
y=y_labels,
orientation='h',
text=texty,
textposition='auto',
hovertext=hovertext,
name=name,
marker_color=color
)
if to_html:
fig = go.Figure(fig)
if title:
fig.update_layout(title_text=title)
if xaxis:
fig.update_layout(xaxis_title=xaxis)
if yaxis:
fig.update_layout(yaxis_title=yaxis)
fig.update_layout(yaxis={'categoryorder': 'total ascending'})
fig.update_yaxes(automargin=True)
if markup:
return Markup(fig.to_html(full_html=False))
else:
return fig
else:
return fig
def _boxplot(x_data, y_data, text, title=None, xaxis=None, yaxis=None, to_html=True, name=None, color=None, markup=True):
if to_html:
fig = go.Figure()
i = 0
for xd, yd in zip(x_data, y_data):
fig.add_trace(go.Box(
y=yd,
name=xd,
boxpoints='all',
text=text,
marker_color=COLORS[i]
)
)
i += 1
if title:
fig.update_layout(title_text=title)
if xaxis:
fig.update_layout(xaxis_title=xaxis)
if yaxis:
fig.update_layout(yaxis_title=yaxis)
if markup:
return Markup(fig.to_html(full_html=False))
else:
return fig
else:
length = len(y_data[0])
box = go.Box(
y=[j for i in y_data for j in i],
x=[k for j in [[i]*length for i in x_data] for k in j],
name=name,
boxpoints='all',
hovertext=text*len(FEATURE_COLS),
marker_color=color,
offsetgroup=name
)
return box
def _venn_diagram_artist_genres(artists, genres):
if len(genres) == 2:
left = set(genres[0])
right = set(genres[1])
img = BytesIO()
plt.rcParams.update({'font.size': 18})
plt.figure(figsize=(18, 10))
fig = venn2([left, right], tuple(artists))
bubbles = ['10', '01', '11']
text = [left-right, right-left, left & right]
for i, j in zip(bubbles, text):
try:
fig.get_label_by_id(i).set_text('\n'.join(j))
except:
pass
for text in fig.set_labels:
text.set_fontsize(18)
# Save it to a temporary buffer
plt.savefig(img, format='png')
plt.close()
img.seek(0)
# Embed the result in the html output
plot_url = base64.b64encode(img.getvalue()).decode('utf8')
return plot_url
elif len(genres) >= 3:
first = set(genres[0])
second = set(genres[1])
third = set(genres[2])
img = BytesIO()
plt.rcParams.update({'font.size': 18})
plt.figure(figsize=(18, 10))
fig = venn3([first, second, third],
set_labels=tuple(artists))
bubbles = ['100', '010', '001', '110', '011', '101', '111']
text = [first-second-third, second-first-third, third-first-second,
first & second-third, second & third-first, first & third-second,
first & second & third]
for i, j in zip(bubbles, text):
try:
fig.get_label_by_id(i).set_text('\n'.join(j))
except:
pass
# Save it to a temporary buffer
plt.savefig(img, format='png')
plt.close()
img.seek(0)
# Embed the result in the html output
plot_url = base64.b64encode(img.getvalue()).decode('utf8')
return plot_url
def _timeline_trace(df, continuous, playlists, bar, trace=False):
df = df.groupby(['date_added'], as_index=False)[
['name', 'artist']].agg(lambda x: list(x))
df = df.sort_values(by='date_added')
total_count = []
count = 0
for i in df['name']:
if continuous:
count += len(i)
else:
count = len(i)
total_count.append(count)
df['total_count'] = total_count
df['songs'] = ['<br>'.join(i) for i in df['name']]
if playlists:
title = playlists[0] if len(playlists) == 1 else 'Individual Playlists'
else:
title = 'Any Playlist'
if trace:
if bar:
return go.Bar(name=trace, x=df['date_added'], y=df['total_count'], hovertext=df['songs'])
else:
return go.Scatter(name=trace, x=df['date_added'], y=df['total_count'], mode='lines', text=df['songs'])
else:
if bar:
return px.bar(df, x='date_added', y='total_count',
title='Timeline of When Songs Were Added to ' + title, hover_name='songs')
else:
return px.line(df, x='date_added', y='total_count',
title='Timeline of When Songs Were Added to ' + title, hover_name='songs')
def _get_top_n_from_dict(dicty, reverse=False, top_n=10):
return {k: dicty[k] for k in sorted(dicty.items(), key=lambda x: x[1], reverse=reverse)[:top_n]}
def _dump(path, obj):
with open(path, 'wb') as f:
pickle.dump(obj, f)
def _load(path):
with open(path, 'rb') as f:
return pickle.load(f)
# Shared Functions -----------------------------------------------------------------------------------------
def shared_graph_count_timeline(ALL_SONGS_DF, playlists=None, song_name=None, artists=None, continuous=False, bar=False, to_html=True):
song_in_playlist = False
if playlists and len(playlists) == 1:
df = ALL_SONGS_DF[ALL_SONGS_DF['playlist'] ==
playlists[0]][['name', 'artist', 'date_added']]
song_in_playlist = True if song_name in df['name'].values else False
if song_name and artists and len(artists) == 1 and song_in_playlist:
song_df = df[df['name'] == song_name]
song_df = song_df[song_df['artist'] == artists[0]]
song_dates = [song_df.iloc[0]['date_added']]
else:
df = ALL_SONGS_DF[['name', 'artist', 'date_added']]
song_in_playlist = True if song_name in df['name'].values else False
if song_name and artists and len(artists) == 1 and song_in_playlist:
song_df = df[df['name'] == song_name]
song_df = song_df[song_df['artist'] == artists[0]]
song_dates = song_df['date_added'].unique()
elif artists and len(artists) == 1:
df = ALL_SONGS_DF[ALL_SONGS_DF['artist'].apply(
lambda x: artists[0] in x.split(', '))]
if playlists and len(playlists) > 1:
fig = go.Figure()
for p in playlists:
df = ALL_SONGS_DF[ALL_SONGS_DF['playlist'] == p]
trace = _timeline_trace(
df, continuous, playlists, bar, trace=p)
fig.add_trace(trace)
elif artists and len(artists) > 1:
fig = go.Figure()
for a in artists:
df = ALL_SONGS_DF[ALL_SONGS_DF['artist'].apply(lambda x: a in x.split(', '))]
trace = _timeline_trace(
df, continuous, playlists, bar, trace=a)
fig.add_trace(trace)
else:
fig = _timeline_trace(df, continuous, playlists, bar)
if not to_html:
return fig
if song_name and artists and song_in_playlist:
for song_date in song_dates:
fig.add_vline(x=song_date, line_width=3,
line_dash="dash", line_color="green")
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="YTD", step="year", stepmode="todate"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all")
])
)
)
fig.update_layout(
yaxis_title='Total Songs' if continuous else 'Daily Added Songs')
return Markup(fig.to_html(full_html=False))
def shared_graph_count_timelines(all_songs_df, title, playlists=None, artists=None, to_html=True):
today = datetime.datetime.now().astimezone()
line_timeline = shared_graph_count_timeline(
all_songs_df, continuous=False, playlists=playlists, artists=artists, to_html=False)
continuous_timeline = shared_graph_count_timeline(
all_songs_df, continuous=True, playlists=playlists, artists=artists, to_html=False)
bar_timeline = shared_graph_count_timeline(
all_songs_df, bar=True, playlists=playlists, artists=artists, to_html=False)
labels = ["Line", "Continuous", 'Bar']
fig = subplots.make_subplots(rows=1, cols=1, vertical_spacing=.05,
subplot_titles=(title))
# Multi-colors for 1 Time Range = Short, Med, Long
length = len(line_timeline.data)
for i in range(length):
fig.add_trace(line_timeline.data[i], 1, 1)
fig.add_trace(continuous_timeline.data[i], 1, 1)
fig.add_trace(bar_timeline.data[i], 1, 1)
# Create buttons for drop down menu
buttons = []
for i, label in enumerate(labels):
visibility = [i == j for j in range(len(labels))]
button = dict(
method='update',
label=label,
args=[{'visible': visibility}])
buttons.append(button)
updatemenus = list([
dict(type='buttons',
direction='right',
active=0,
y=1.3,
x=.6,
buttons=buttons
)
])
# hoverlabel_font_color='white'
fig.update_layout(updatemenus=updatemenus,
showlegend=True, title=title, yaxis_title='# Songs', xaxis_title='Date', barmode='stack')
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="YTD", step="year", stepmode="todate"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all")
])
)
)
# Add vertical lines for current date
first_date = all_songs_df['date_added'].sort_values(
ascending=True).iloc[0]
first_year = str(first_date)[:4]
current_year = str(today.date())[:4]
today = str(today.date())[5:].split('-')
month = int(today[0])
day = int(today[1])
for year in range(int(first_year), int(current_year)+1):
fig.add_vline(x=datetime.datetime(year, month, day), line_width=3,
line_dash="dash", line_color="green")
# Only show 1st Trace on page-load
Ld = len(fig.data)
for k in range(Ld):
if k % 3 == 0:
fig.update_traces(visible=True, selector=k)
else:
fig.update_traces(visible=False, selector=k)
if to_html:
return Markup(fig.to_html(full_html=False))
else:
return fig
def shared_graph_top_playlists_by_artist(ALL_SONGS_DF, artist_name):
mask = ALL_SONGS_DF['artist'].apply(lambda x: artist_name in x.split(', '))
df = ALL_SONGS_DF[mask]
series = df['playlist'].value_counts(ascending=True)
return _h_bar(series, title='Most Common Playlists For Artist: ' + artist_name,
xaxis='Number of Artist Songs in the Playlist')
def shared_graph_top_songs_by_artist(UNIQUE_SONGS_DF, artist_name):
mask = UNIQUE_SONGS_DF['artist'].apply(lambda x: artist_name in x.split(', '))
df = UNIQUE_SONGS_DF[mask]
# Sort by Num Playlists
d = defaultdict(list)
for i, j in zip(df['name'], df['num_playlists']):
d[j].append(i)
d = {k: ', '.join(v) for k, v in sorted(
d.items(), key=lambda x: x[0], reverse=True)}
fig = go.Figure(data=[go.Table(
header=dict(
values=['# Playlists Song Is In', 'Artist Song(s)'],
line_color='darkslategray',
fill_color='royalblue',
font=dict(color='white', size=18),
height=40
),
cells=dict(
values=[list(d.keys()), list(d.values())],
line_color='darkslategray',
align='center',
font_size=[18, 14],
height=30)
)
])
fig.update_layout(autosize=True, title_text='Most Common Songs For Artist: ' + artist_name,
xaxis_title="Number of Playlists The Artist's Song Is In")
return Markup(fig.to_html(full_html=False))
# Currently Playing Page ----------------------------------------------------------------------------------------------
class CurrentlyPlayingPage():
def __init__(self, song, artist, playlist, all_songs_df, unique_songs_df):
self._song = song
self._artist = artist
self._playlist = playlist
self._all_songs_df = pd.DataFrame(all_songs_df)
self._unique_songs_df = pd.DataFrame(unique_songs_df)
song_df = self._unique_songs_df[self._unique_songs_df['artist'] == artist]
song_df = song_df[song_df['name'] == song]
if len(song_df.index) > 0:
self._artist_genres = song_df.iloc[0]['genres']
self._song_genres = list(
{j for i in self._artist_genres for j in i})
else:
self._artist_genres = []
self._song_genres = None
def graph_top_rank_table(self):
UNIQUE_SONGS_DF = self._unique_songs_df
df = UNIQUE_SONGS_DF[UNIQUE_SONGS_DF['name'] == self._song]
df = df[df['artist'] == self._artist]
values = [['Artists', 'Songs'], [df['artists_short_rank'], df['songs_short_rank']],
[df['artists_med_rank'], df['songs_med_rank']], [df['artists_long_rank'], df['songs_long_rank']]]
fig = go.Figure(data=[go.Table(
# columnorder = [1, 2, 3, 4],
# columnwidth = [80,400],
header=dict(
values=[['<b>Top 50 Rank</b>'],
['<b>Last 4 Weeks</b>'],
['<b>Last 6 Months</b>'],
['<b>All Time</b>']],
line_color='darkslategray',
fill_color='royalblue',
# align=['left','center'],
font=dict(color='white', size=18),
height=40
),
cells=dict(
values=values,
line_color='darkslategray',
# fill=dict(color=['paleturquoise', 'white']),
align='center',
font_size=18,
height=40)
)
])
fig.update_layout(
title_text='Song / Artist Rank in Top 50', height=300)
return Markup(fig.to_html(full_html=False))
def graph_song_features_vs_avg(self):
UNIQUE_SONGS_DF = self._unique_songs_df
ALL_SONGS_DF = self._all_songs_df
song_df = UNIQUE_SONGS_DF[UNIQUE_SONGS_DF['name'] == self._song]
song_df = song_df[song_df['artist'] == self._artist][FEATURE_COLS]
if self._playlist:
playlist_df = ALL_SONGS_DF[ALL_SONGS_DF['playlist']
== self._playlist][FEATURE_COLS]
artist_dfs = [UNIQUE_SONGS_DF[UNIQUE_SONGS_DF['artist']
== i][FEATURE_COLS] for i in self._artist.split(', ')]
avg_df = UNIQUE_SONGS_DF[FEATURE_COLS]
if self._playlist:
dfs = [playlist_df, avg_df, song_df]
else:
dfs = [avg_df, song_df]
for df in dfs:
df['popularity'] = df['popularity']/100
dfs = [df.mean(axis=0) for df in dfs]
for df in artist_dfs:
df['popularity'] = df['popularity']/100
artist_dfs = [df.mean(axis=0) for df in artist_dfs]
# add song values to last so features and percentiles avgs match colors
song_vals = dfs[-1]
dfs = dfs[:-1]
dfs.append(artist_dfs)
dfs.append(song_vals)
fig = go.Figure()
if self._playlist:
names = [self._playlist, 'All Playlists',
self._artist.split(', '), self._song]
else:
names = ['All Playlists', self._artist.split(', '), self._song]
for series, name in zip(dfs, names):
if type(name) == list:
for s, n in zip(series, name):
fig.add_trace(go.Scatterpolar(
r=s,
theta=FEATURE_COLS,
fill='toself',
name=n
))
else:
fig.add_trace(go.Scatterpolar(
r=series,
theta=FEATURE_COLS,
fill='toself',
name=name
))
if self._playlist:
title = 'Song Audio Features vs. AVG Song from Playlist, All Playlists, & Artist'
else:
title = 'Song Audio Features vs. AVG Song from All Playlists & Artist'
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 1]
)),
showlegend=True,
title_text=title
# margin=dict(l=20, r=20, t=20, b=20)
)
return Markup(fig.to_html(full_html=False))
def graph_song_percentiles_vs_avg(self):
UNIQUE_SONGS_DF = self._unique_songs_df
ALL_SONGS_DF = self._all_songs_df
# Since playlist and artist df length will vary, make new percentile cols for them and then isolate song
if self._playlist:
playlist_df = ALL_SONGS_DF[ALL_SONGS_DF['playlist'] == self._playlist]
exists_df = playlist_df[playlist_df['name'] == self._song]
exists_df = exists_df[exists_df['artist'] == self._artist]
if len(exists_df) == 0:
song_df = ALL_SONGS_DF[ALL_SONGS_DF['name'] == self._song]
song_df = song_df[song_df['artist'] == self._artist]
playlist_df = pd.concat([playlist_df, song_df])
for col in PERCENTILE_COLS:
sz = playlist_df[col].size-1
playlist_df[col + '_percentile'] = playlist_df[col].rank(
method='max').apply(lambda x: 100.0*(x-1)/sz)
playlist_df = playlist_df[(playlist_df['name'] == self._song) & (playlist_df['artist'] == self._artist)]
artist_dfs = []
for a in self._artist.split(', '):
mask = UNIQUE_SONGS_DF['artist'].apply(lambda x: a in x.split(', '))
artist_df = UNIQUE_SONGS_DF[mask]
for col in PERCENTILE_COLS:
sz = artist_df[col].size-1
if sz > 0:
artist_df[col + '_percentile'] = artist_df[col].rank(
method='max').apply(lambda x: 100.0*(x-1)/sz)
else:
artist_df[col + '_percentile'] = [0]
artist_df = artist_df[artist_df['name'] == self._song]
if len(artist_df.index) == 0:
return None
artist_dfs.append(artist_df)
# UNIQUE_SONGS_DF already has _percentile columns, so get the matching song by song and artist name
avg_df = UNIQUE_SONGS_DF[UNIQUE_SONGS_DF['name'] == self._song]
avg_df = avg_df[avg_df['artist'] == self._artist]
cols = [i + '_percentile' for i in PERCENTILE_COLS]
dfs = {}
if self._playlist:
dfs[self._playlist] = playlist_df[cols]
dfs['All Playlists'] = avg_df[cols]
for i, j in zip(self._artist.split(', '), [adf[cols] for adf in artist_dfs]):
dfs[i] = j
data = []
for name, df in dfs.items():
data.append(go.Bar(name=name, x=PERCENTILE_COLS, y=df.iloc[0], text=df.iloc[0].astype(int), textposition='auto'))
fig = go.Figure(data=data)
if self._playlist:
title = 'Percentile of Song Audio Features by Playlist, All Playlists, & Artist'
else:
title = 'Percentile of Audio Features by All Playlists & Artist'
fig.update_layout(barmode='group', title_text=title)
return Markup(fig.to_html(full_html=False))
def graph_date_added_to_playlist(self):
ALL_SONGS_DF = self._all_songs_df
df = ALL_SONGS_DF[ALL_SONGS_DF['name'] == self._song]
df = df[df['artist'] == self._artist]
# today = datetime.datetime.now().astimezone().date()
today = datetime.datetime.utcnow().date()
new = pd.DataFrame({'Task': df['playlist'], 'Start': df['date_added'], 'Finish': [
today]*len(df['playlist'])})
fig = ff.create_gantt(new)
fig.update_layout(title_text='Timeline Of When ' +
self._song + ' Was Added To Playlists')
return Markup(fig.to_html(full_html=False))
def graph_count_timeline(self):
if not self._playlist:
return None
return shared_graph_count_timeline(self._all_songs_df, playlists=[self._playlist], song_name=self._song, artists=[self._artist])
def graph_top_playlists_by_artist(self, artist_name):
return shared_graph_top_playlists_by_artist(self._all_songs_df, artist_name)
def graph_top_songs_by_artist(self, artist_name):
return shared_graph_top_songs_by_artist(self._unique_songs_df, artist_name)
def graph_artist_genres(self):
if len(self._artist_genres) == 1:
return [', '.join(self._song_genres), False]
else:
fig = _venn_diagram_artist_genres(
self._artist.split(', '), self._artist_genres)
return [fig, True]
# What percentage of songs in a playlist or among all playlists have these genres?
def graph_song_genres_vs_avg(self, playlist=False):
if self._song_genres != None:
UNIQUE_SONGS_DF = self._unique_songs_df
ALL_SONGS_DF = self._all_songs_df
if playlist:
mask = UNIQUE_SONGS_DF['playlist'].apply(
lambda x: self._playlist in x)
avg_df = UNIQUE_SONGS_DF[mask]
title = 'Percentage of Songs With Same Genres As ' + \
self._artist + ' in ' + self._playlist
xaxis = '% of Songs in ' + self._playlist
else:
avg_df = ALL_SONGS_DF
title = 'Percentage of Songs With Same Genres As ' + \
self._artist + ' Across All Playlists'
xaxis = '% of Songs with Genres'
percents = []
length = len(avg_df.index)
for g in self._song_genres:
mask = avg_df['genres'].apply(
lambda x: g in {z for y in x for z in y})
percents.append(len(avg_df[mask].index)/length*100)
series = pd.Series(dict(zip(self._song_genres, percents)))
return _h_bar(series, title=title, xaxis=xaxis, percents=True)
return None
def graph_all_artists(self):
artist_top_graphs = []
for i in self._artist.split(', '):
artist_top_playlists_bar = self.graph_top_playlists_by_artist(i)
artist_top_songs_table = self.graph_top_songs_by_artist(i)
artist_top_graphs.append(
(artist_top_playlists_bar, artist_top_songs_table))
return artist_top_graphs
# Home Page ----------------------------------------------------------------------------------------------
class HomePage():
def __init__(self, path, all_songs_df, unique_songs_df):
self._today = datetime.datetime.now().astimezone()
self._path = path
self._all_songs_df = pd.DataFrame(all_songs_df)
self._unique_songs_df = pd.DataFrame(unique_songs_df)
self._graph_on_this_date()
self._graph_count_timeline()
self._graph_last_added()
self._get_library_totals()
def load_on_this_date(self):
try:
return _load(f'{self._path}home_on_this_date.pkl')
except FileNotFoundError:
return 'No recorded data of adding songs to a playlist on this date'
def load_timeline(self):
return _load(f'{self._path}home_timeline.pkl')
def load_last_added(self):
return _load(f'{self._path}home_last_added.pkl')
def load_totals(self):
return _load(f'{self._path}home_totals.pkl')
def load_first_times(self):
try:
return _load(f'{self._path}home_first_times.pkl')
except FileNotFoundError:
return 'Uh Oh'
def _graph_on_this_date(self):
'''Output1 = Table = Year | Playlist | Songs Added
Output2 = List = You created playlist / added song from artist for the first time'''
ALL_SONGS_DF = self._all_songs_df
today = str(self._today.date())[5:]
df = ALL_SONGS_DF[ALL_SONGS_DF['date_added'].apply(lambda x: today in x)]
first_times = []
df['year'] = [i[:4] for i in df['date_added']]
df = df[['name', 'artist', 'playlist', 'year']]
if len(df.index) == 0:
first_times.append('No recorded data of adding songs to a playlist on this date')
else:
for a in {j for i in df['artist'] for j in i.split(', ')}:
artist_df = ALL_SONGS_DF[ALL_SONGS_DF['artist'].apply(
lambda x: a in x.split(', '))]
first_date = artist_df['date_added'].sort_values(
ascending=True).iloc[0]
if str(first_date)[5:] == today:
years_ago = int(str(self._today.date())[
:4])-int(str(first_date)[:4])
first_times.append(
(years_ago, 'You first added a song from the artist ' + a + ' ' + str(years_ago) + ' years ago today!'))
first_times = [i[1] for i in sorted(first_times, key = lambda x: x[0], reverse=True)]
for p in df['playlist'].unique():
playlist_df = ALL_SONGS_DF[ALL_SONGS_DF['playlist'] == p]
first_date = playlist_df['date_added'].sort_values(
ascending=True).iloc[0]
if str(first_date)[5:] == today:
years_ago = int(str(self._today.date())[
:4])-int(str(first_date)[:4])
first_times.append(
'You created the playlist ' + p + ' ' + str(years_ago) + ' years ago today!')
_dump(f'{self._path}home_first_times.pkl', first_times)
df = df.groupby(['playlist', 'year'], as_index=False)[
['name', 'artist']].agg(lambda x: ', '.join(x))
df = df.sort_values(by='year')
fig = go.Figure(data=[go.Table(
header=dict(
values=['Year', 'Playlist', 'Songs Added', 'Artists'],
line_color='darkslategray',
fill_color='royalblue',
font=dict(color='white', size=18),
height=40
),
cells=dict(
values=[df['year'].to_list(), df['playlist'].to_list(), df['name'].to_list(),
[', '.join(list(dict.fromkeys((i.split(', '))))) for i in df['artist']]
],
line_color='darkslategray',
align='center',
font_size=[18, 14],
height=30)
)
])
_dump(f'{self._path}home_on_this_date.pkl', Markup(fig.to_html(full_html=False)))
def _graph_count_timeline(self):
fig = shared_graph_count_timelines(
self._all_songs_df, title='<b>Timeline of Adding Songs to Playlists</b>', to_html=False)
_dump(f'{self._path}home_timeline.pkl',
Markup(fig.to_html(full_html=False)))
def _graph_last_added(self):
ALL_SONGS_DF = self._all_songs_df
df = ALL_SONGS_DF.sort_values(by='date_added', ascending=False)
last_date = df['date_added'].to_list()[0]
distance = (self._today.date() - datetime.date(*
map(int, last_date.split('-')))).days+1
df = ALL_SONGS_DF[ALL_SONGS_DF['date_added'] == last_date]
num_songs = len(df.index)
df = df[['name', 'playlist']]
df = df.groupby(['playlist'], as_index=False)[
['name']].agg(lambda x: list(x))
fig = go.Figure(data=[go.Table(
header=dict(
values=['Playlist', 'Songs Added'],
line_color='darkslategray',
fill_color='royalblue',
font=dict(color='white', size=18),
height=40
),
cells=dict(
values=[list(df['playlist']), [', '.join(i)
for i in df['name']]],
line_color='darkslategray',
align='center',
font_size=[18, 14],
height=30)
)
])
final = [distance, Markup(fig.to_html(
full_html=False)), num_songs, len(df['playlist'])]
_dump(f'{self._path}home_last_added.pkl', final)
def _get_library_totals(self):
ALL_SONGS_DF = self._all_songs_df
UNIQUE_SONGS_DF = self._unique_songs_df
overall_data = [len(ALL_SONGS_DF.index), len(UNIQUE_SONGS_DF),
len(ALL_SONGS_DF['playlist'].unique()), len(
UNIQUE_SONGS_DF['artist'].unique()),
len(UNIQUE_SONGS_DF['album'].unique())]
_dump(f'{self._path}home_totals.pkl', overall_data)
# Overall Stats = About Me Page ----------------------------------------------------------------------------------------------
class AboutPage():
def __init__(self, path, all_songs_df, unique_songs_df, artists, top_artists, top_songs):
self._path = path
self._all_songs_df = pd.DataFrame(all_songs_df)
self._unique_songs_df = pd.DataFrame(unique_songs_df)
self._artists = artists
self._top_artists = top_artists
self._top_songs = top_songs
self._graph_top_genres_by_followed_artists()
self._graph_top_playlists_by_top_50()
self._graph_top_playlists_by_top_50(artists=10)
self._graph_top_songs_by_num_playlists()
self._graph_top_artists_and_albums_by_num_playlists()
self._graph_top_artists_and_albums_by_num_playlists(albums=True)
def load_followed_artists(self):
return _load(f'{self._path}about_followed_artists.pkl')
def load_playlists_by_artists(self):
return _load(f'{self._path}about_playlists_by_artists.pkl')
def load_playlists_by_songs(self):
return _load(f'{self._path}about_playlists_by_songs.pkl')
def load_top_songs(self):
return _load(f'{self._path}about_overall_songs.pkl')
def load_top_artists(self):
return _load(f'{self._path}about_overall_artists.pkl')
def load_top_albums(self):
return _load(f'{self._path}about_overall_albums.pkl')
def _graph_top_genres_by_followed_artists(self):
d = defaultdict(int)
d2 = defaultdict(list)
for a in self._artists:
for g in a['genres']:
d[g] += 1
d2[g].append(a['name'])
top_n = 10
data = {i[0]: i[1] for i in sorted(
d.items(), key=lambda x: x[1], reverse=True)[:top_n][::-1]}
series = pd.Series(data)
final = _h_bar(series, title='Top Genres by Followed Artists', xaxis='# of Followed Artists',
hovertext=[', '.join(d2[i]) for i in data.keys()], yaxis='Genre', long_names=True)
_dump(f'{self._path}about_followed_artists.pkl', final)
def _graph_top_playlists_by_top_50(self, artists=False):
ALL_SONGS_DF = self._all_songs_df
final = []
for time_range in [0, 1, 2]:
if artists:
dicty = self._top_artists[time_range]
else:
dicty = self._top_songs[time_range]
playlist_dict = defaultdict(int)
if artists:
for name, playlist in zip(ALL_SONGS_DF['artist'], ALL_SONGS_DF['playlist']):
found = False
for n in name.split(', '):
if n in dicty[:artists]:
if not found:
playlist_dict[playlist] += 1
found = True
else:
for name, playlist in zip(ALL_SONGS_DF['name'], ALL_SONGS_DF['playlist']):
if name in dicty.keys():
playlist_dict[playlist] += 1
final.append(playlist_dict)
if artists:
df = pd.DataFrame(final, index=['# Top Short Term Artist Songs',
'# Top Medium Term Artist Songs', '# Top Long Term Artist Songs'])
else:
df = pd.DataFrame(final, index=[
'# Top Short Term Songs', '# Top Medium Term Songs', '# Top Long Term Songs'])
df = df.T.fillna(0)
df['Playlist'] = df.index
if artists:
fig = px.scatter(df, x="# Top Short Term Artist Songs", y="# Top Medium Term Artist Songs",
size="# Top Long Term Artist Songs", hover_name='Playlist')
else:
fig = px.scatter(df, x="# Top Short Term Songs", y="# Top Medium Term Songs",
size="# Top Long Term Songs", hover_name='Playlist')
if artists:
title = 'Top Playlists by Number of Top ' + \
str(artists) + ' Artists\' Songs'
else:
title = 'Top Playlists by Number of Top 50 Songs In Them'
fig.update_layout(title_text=title)
if artists:
_dump(f'{self._path}about_playlists_by_artists.pkl',
Markup(fig.to_html(full_html=False)))
else:
_dump(f'{self._path}about_playlists_by_songs.pkl',
Markup(fig.to_html(full_html=False)))
def _graph_top_songs_by_num_playlists(self, top_n=10):
df = self._unique_songs_df.sort_values(
by='num_playlists', ascending=False)
df = df.head(top_n)
series = pd.Series(dict(zip(df['name'], df['num_playlists'])))
title = 'Top ' + str(top_n) + ' Most Common Songs Across ' + \
str(len(self._all_songs_df['playlist'].unique())) + ' Playlists'
final = _h_bar(series, title=title, xaxis='Number of Playlists Song is In', yaxis='Song',
long_names=True, hovertext=[', '.join(i) for i in df['playlist']])
_dump(f'{self._path}about_overall_songs.pkl', final)
def _graph_top_artists_and_albums_by_num_playlists(self, top_n=10, albums=False):
ALL_SONGS_DF = self._all_songs_df
dicty = dict()
if albums:
title = 'Top ' + str(top_n) + ' Most Common Albums Across ' + \
str(len(ALL_SONGS_DF['playlist'].unique())) + ' Playlists'
yaxis = 'Album Name'
for a in ALL_SONGS_DF['album'].unique():
a_df = ALL_SONGS_DF[ALL_SONGS_DF['album'] == a]
dicty[a] = len(a_df.index)
else:
title = 'Top ' + str(top_n) + ' Most Common Artists Across ' + \