-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintervals_streamlit2.py
1628 lines (1552 loc) · 79.5 KB
/
intervals_streamlit2.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
import streamlit as st
st. set_page_config(layout="wide")
from pathlib import Path
import requests
from requests.sessions import DEFAULT_REDIRECT_LIMIT
import requests
import crim_intervals
from crim_intervals import *
from crim_intervals import main_objs
import crim_intervals.visualizations as viz
import pandas as pd
import altair as alt
import glob as glob
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.figure_factory as ff
import streamlit.components.v1 as components
from os import listdir
import json
from tempfile import NamedTemporaryFile
import random
from pandas.api.types import (
is_categorical_dtype,
is_datetime64_any_dtype,
is_numeric_dtype,
is_object_dtype,
)
# list of piece ids from json
def make_piece_list(json_objects):
piece_list = []
for piece in json_objects:
file_name = piece['piece_id']
piece_list.append(file_name)
return piece_list
# list of composer_title ids from json
def make_composer_title_list(json_objects):
composer_title_list = []
for piece in json_objects:
composer_title = piece['composer']['name'] + ', ' + piece['full_title']
composer_title_list.append(composer_title)
return composer_title_list
# get mei link for given piece
def find_mei_link(piece_id, json_objects):
key_value_pair = ('piece_id', piece_id)
for json_object in json_objects:
if key_value_pair in json_object.items():
return json_object['mei_links'][0]
return None
# Title and Introduction
st.title("CRIM Intervals Search Tools")
st.subheader("A web application for analysis of musical patterns using the CRIM Intervals library.")
st.markdown("[Watch a video guide to this application.](https://haverford.box.com/s/tn35aynw0ogpih43ux923tbd2kma1idg)")
st.markdown("[Learn more about CRIM Intervals](https://github.com/HCDigitalScholarship/intervals)", unsafe_allow_html=True)
st.markdown("Follow detailed explanations of various CRIM Intervals methods via the [Tutorials](https://github.com/HCDigitalScholarship/intervals/blob/main/tutorial/01_Introduction_and_Corpus.md)", unsafe_allow_html=True)
st.markdown("Learn more about this web application (and how to contribute or adapt it via the [Github Repository for CRIM Intervals on Streamlit](https://github.com/RichardFreedman/intervals-streamlit/blob/main/README.md)")
# importing files
crim_url = 'https://crimproject.org/data/pieces/'
all_pieces_json = requests.get(crim_url).json()
json_str = json.dumps(all_pieces_json)
json_objects = json.loads(json_str)
# function to make list of pieces
all_piece_list = make_piece_list(json_objects)
crim_piece_selections= st.multiselect('**Select Pieces To View from CRIM Django**',
all_piece_list)
# st.write("Upload MEI or XML files")
uploaded_files_list = st.file_uploader("**Upload MEI or XML files**", type=['mei', 'xml'], accept_multiple_files=True)
crim_view_url = ''
if len(crim_piece_selections) == 0 and len(uploaded_files_list)== 0:
st.write("**No Files Selected! Please Select or Upload One or More Pieces.**")
# for one piece in CRIM
elif len(crim_piece_selections) == 1 and len(uploaded_files_list)== 0:
piece_name = crim_piece_selections[0]
crim_view_url = 'https://crimproject.org/pieces/' + piece_name
# url_for_verovio = "https://raw.githubusercontent.com/CRIM-Project/CRIM-online/master/crim/static/mei/MEI_4.0/" + piece_name + ".mei"
# based on selected piece, get the mei file link and import it
filepath = find_mei_link(piece_name, json_objects)
keys = ['piece', 'metadata']
for key in keys:
if key in st.session_state.keys():
del st.session_state[key]
# import
piece = importScore(filepath)
if "piece" not in st.session_state:
st.session_state.piece = piece
if "metadata" not in st.session_state:
st.session_state.metadata = piece.metadata
st.session_state.metadata['CRIM View'] = crim_view_url
st.dataframe(st.session_state.metadata)
# One upload
elif len(crim_piece_selections) == 0 and len(uploaded_files_list) == 1:
f = ''
crim_view_url = "Direct Upload; Not from CRIM"
keys = ['piece', 'metadata']
for key in keys:
if key in st.session_state.keys():
del st.session_state[key]
for file in uploaded_files_list:
# KEEP THIS
# with NamedTemporaryFile(dir='.', suffix = '.mei') as f:
# f.write(file.getbuffer())
# # f.name is in fact the TEMP PATH!
# piece = importScore(f.name)
byte_str = file.read()
text_obj = byte_str.decode('UTF-8')
piece = importScore(text_obj)
if "piece" not in st.session_state:
st.session_state.piece = piece
if "metadata" not in st.session_state:
st.session_state.metadata = piece.metadata
st.session_state.metadata['CRIM View'] = "Direct upload; not available on CRIM"
st.dataframe(st.session_state.metadata)
# now combine the CRIM and Uploaded Files
elif (len(crim_piece_selections) > 0 and len(uploaded_files_list) > 0) or len(crim_piece_selections) > 1 or len(uploaded_files_list) > 1:
# set empty corpus list, so we can add files to it
corpus_list = []
metadata_list= []
if len(crim_piece_selections) > 0:
for crim_piece in crim_piece_selections:
filepath = find_mei_link(crim_piece, json_objects)
corpus_list.append(filepath)
if len(uploaded_files_list) > 0:
for file in uploaded_files_list:
# KEEP THIS FOR TEMP WRITE METHOD
# if file is not None:
# file_details = {"FileName":file.name,"FileType":file.type}
# local_dir = '/tempDir/'
# # this one for use on computer:
# # local_dir = '/Users/rfreedma/Documents/CRIM_Python/intervals-streamlit/'
# file_path = os.path.join(local_dir, file.name)
# with open(file_path,"wb") as f:
# f.write(file.getbuffer())
# corpus_list.append(file_path)
byte_str = file.read()
text_obj = byte_str.decode('UTF-8')
corpus_list.append(text_obj)
# make corpus and session state version
if 'corpus' in st.session_state:
del st.session_state.corpus
corpus = CorpusBase(corpus_list)
if 'corpus' not in st.session_state:
st.session_state.corpus = corpus
if 'corpus_metadata' in st.session_state:
del st.session_state.corpus_metadata
for i in range(len(corpus.scores)):
metadata_list.append(corpus.scores[i].metadata)
if 'corpus_metadata' not in st.session_state:
st.session_state.corpus_metadata = metadata_list
st.dataframe(st.session_state.corpus_metadata)
# get metadata for corpus
if "corpus_metadata" not in st.session_state:
pass
else:
corpus_metadata_df = pd.DataFrame.from_dict(st.session_state.corpus_metadata)
titles = corpus_metadata_df['title']
# flags for lengths of selected corpus:
if len(crim_piece_selections) == 0 and len(uploaded_files_list) == 0:
corpus_length = 0
elif len(crim_piece_selections) == 1 and len(uploaded_files_list) == 0:
corpus_length = 1
elif len(crim_piece_selections) == 0 and len(uploaded_files_list) == 1:
corpus_length = 1
elif len(crim_piece_selections) + len(uploaded_files_list) >= 2:
corpus_length = 2
# CRIM at GIT
# piece_list = []
# crim_git_prefix = "https://raw.githubusercontent.com/CRIM-Project/CRIM-online/master/crim/static/mei/MEI_4.0/"
# crim_git_url = "https://api.github.com/repos/CRIM-Project/CRIM-online/git/trees/990f5eb3ff1e9623711514d6609da4076257816c"
# piece_json = requests.get(crim_git_url).json()
# # pattern to filter out empty header Mass files
# pattern = 'CRIM_Mass_([0-9]{4}).mei'
# # # and now the request for all the files
# for p in piece_json["tree"]:
# name = p["path"]
# if re.search(pattern, name):
# pass
# else:
# piece_list.append(name)
# # st.write(piece_list)
# piece_list = sorted(piece_list)
# piece_name = st.selectbox('Select Piece To View from CRIM@GIT',
# piece_list)
# # based on selected piece, get the mei file link and import it
# if piece_name is not None:
# filepath = crim_git_prefix + piece_name
# piece = importScore(filepath)
# st.subheader("Selected Piece")
# if piece_name is not None:
# st.write(piece_name)
# st.write(piece.metadata['composer'] + ': ' + piece.metadata['title'])
# show_score_checkbox = st.checkbox('Show/Hide Score with Verovio')
# menu dictionaries
interval_kinds = {'diatonic' : 'd',
'chromatic' : 'c',
'with quality' : 'q',
'zero-based diatonic' : 'z'}
unison_status = {'Separate Unisons' : False,
'Combine Unisons' : True}
rest_status = {'Combine Rests' : True,
' Separate Rests' : False}
interval_order_quality = ["-P8", "-M7", "-m7", "-M6", "-m6", "-P5", "-P4", "-M3",
"-m3", "-M2", "-m2", "P1", "m2", "M2", "m3", "M3",
"P4", "P5", "m6", "M6", "m7", "M7", "P8"]
# interval_order_quality = ["-P8", "m2", "-m2", "M2", "-M2", "m3", "-m3", "M3", "-M3", "P4", "-P4", "P5", "-P5",
# "m6", "-m6", "M6", "-M6", "m7", "-m7", "M7", "-M7", "P8", "-P8"]
pitch_order = ['E-2', 'E2', 'F2', 'F#2', 'G2', 'A2', 'B-2', 'B2',
'C3', 'C#3', 'D3', 'E-3','E3', 'F3', 'F#3', 'G3', 'G#3','A3', 'B-3','B3',
'C4', 'C#4','D4', 'E-4', 'E4', 'F4', 'F#4','G4', 'A4', 'B-4', 'B4',
'C5', 'C#5','D5', 'E-5','E5', 'F5', 'F#5', 'G5', 'A5', 'B-5', 'B5', 'Rest']
# filter and download functions
def convertTuple(tup):
out = ""
if isinstance(tup, tuple):
out = ', '.join(tup)
return out
# for NR
# st.cache_data(experimental_allow_widgets=True)
@st.fragment()
def filter_dataframe_nr(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
df = df.copy()
random_id = random.randrange(1,1000)
modification_container = st.container()
with modification_container:
# random_id = random.randrange(1,1000)
to_filter_columns = st.multiselect("Filter Notes by Various Fields", df.columns)
st.write("Remember that initial choices will constrain subsequent filters!")
if to_filter_columns:
# here we are filtering by column
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("↳")
# Treat columns with < 10 unique values as categorical
# here
if is_categorical_dtype(df[column]) or df[column].nunique() < 50:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
# gets values for highlighted filters
df_no_meta = df.loc[:, ~df.columns.isin(['Composer', "Title", 'Date', "Measure", "Beat"])]
df_no_meta_col_names = df_no_meta.columns.tolist()
df_voices_only = df[df_no_meta_col_names]
melted = pd.melt(df_voices_only)
values_list = melted['value'].unique()
values_list = [i for i in values_list if i]
values_list = [element for element in values_list if not pd.isnull(element)]
values_list = [x for x in values_list if x != "-"]
user_text_input = st.multiselect("Filter on Notes", values_list)
if user_text_input:
def highlight_matching_strings(val):
match_strings = user_text_input
for match_string in match_strings:
if match_string == val:
return 'background-color: #ccebc4'
return ''
df = df.reset_index().fillna('')
df = df[df[df_no_meta_col_names].apply(lambda x: x.isin(user_text_input)).any(axis=1)]
df = df.style.map(highlight_matching_strings)
else:
df = df.reset_index().fillna('')
df = df.style
return df
# for MEL
# st.cache_data(experimental_allow_widgets=True)
@st.fragment()
def filter_dataframe_mel(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
df = df.copy()
random_id = random.randrange(1,1000)
modification_container = st.container()
with modification_container:
# random_id = random.randrange(1,1000)
to_filter_columns = st.multiselect("Filter Melodic Intervals by Various Fields", df.columns)
st.write("Remember that initial choices will constrain subsequent filters!")
if to_filter_columns:
# here we are filtering by column
# to_filter_columns = st.multiselect("Limit by Composer, Title, Date, or Voice", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("↳")
# Treat columns with < 10 unique values as categorical
# here
if is_categorical_dtype(df[column]) or df[column].nunique() < 50:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
# gets values for highlighted filters
df_no_meta = df.loc[:, ~df.columns.isin(['Composer', "Title", 'Date'])]
df_no_meta_col_names = df_no_meta.columns.tolist()
df_voices_only = df[df_no_meta_col_names]
melted = pd.melt(df_voices_only)
values_list = melted['value'].unique()
values_list = [i for i in values_list if i]
values_list = [element for element in values_list if not pd.isnull(element)]
values_list = [x for x in values_list if x != "-"]
user_text_input = st.multiselect("Filter on Intervals", values_list)
if user_text_input:
def highlight_matching_strings(val):
match_strings = user_text_input
for match_string in match_strings:
if match_string == val:
return 'background-color: #ccebc4'
return ''
df = df.reset_index().fillna('')
df = df[df[df_no_meta_col_names].apply(lambda x: x.isin(user_text_input)).any(axis=1)]
df = df.style.map(highlight_matching_strings)
else:
df = df.reset_index().fillna('')
df = df.style
return df
#for har
# st.cache_data(experimental_allow_widgets=True)
@st.fragment()
def filter_dataframe_har(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
df = df.copy()
random_id = random.randrange(1,1000)
modification_container = st.container()
with modification_container:
# random_id = random.randrange(1,1000)
to_filter_columns = st.multiselect("Filter Harmonic Intervals by Various Fields", df.columns)
st.write("Remember that initial choices will constrain subsequent filters!")
if to_filter_columns:
# here we are filtering by column
# to_filter_columns = st.multiselect("Limit by Composer, Title, Date, or Voice", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("↳")
# Treat columns with < 10 unique values as categorical
# here
if is_categorical_dtype(df[column]) or df[column].nunique() < 50:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
# gets values for highlighted filters
df_no_meta = df.loc[:, ~df.columns.isin(['Composer', "Title", 'Date'])]
df_no_meta_col_names = df_no_meta.columns.tolist()
df_voices_only = df[df_no_meta_col_names]
melted = pd.melt(df_voices_only)
values_list = melted['value'].unique()
values_list = [i for i in values_list if i]
values_list = [element for element in values_list if not pd.isnull(element)]
user_text_input = st.multiselect("Filter on Intervals", values_list)
if user_text_input:
def highlight_matching_strings(val):
match_strings = user_text_input
for match_string in match_strings:
if match_string == val:
return 'background-color: #ccebc4'
return ''
df = df.reset_index().fillna('')
df = df[df[df_no_meta_col_names].apply(lambda x: x.isin(user_text_input)).any(axis=1)]
df = df.style.map(highlight_matching_strings)
else:
df = df.reset_index().fillna('')
df = df.style
return df
# for NG
# st.cache_data(experimental_allow_widgets=True)
@st.fragment()
def filter_dataframe_ng(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
df = df.copy()
random_id = random.randrange(1,1000)
modification_container = st.container()
with modification_container:
# random_id = random.randrange(1,1000)
to_filter_columns = st.multiselect("Filter Ngrams by Various Fields", df.columns)
st.write("Remember that initial choices will constrain subsequent filters!")
if to_filter_columns:
# here we are filtering by column
# to_filter_columns = st.multiselect("Limit by Composer, Title, Date, or Voice", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("↳")
# Treat columns with < 10 unique values as categorical
# here
if is_categorical_dtype(df[column]) or df[column].nunique() < 50:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
# gets values for highlighted filters
df_no_meta = df.loc[:, ~df.columns.isin(['Composer', "Title", 'Date'])]
df_no_meta_col_names = df_no_meta.columns.tolist()
df_voices_only = df[df_no_meta_col_names]
melted = pd.melt(df_voices_only)
values_list = melted['value'].unique()
values_list = [i for i in values_list if i]
values_list = [element for element in values_list if not pd.isnull(element)]
user_text_input = st.multiselect("Filter on Ngrams", values_list)
if user_text_input:
def highlight_matching_strings(val):
match_strings = user_text_input
for match_string in match_strings:
if match_string == val:
return 'background-color: #ccebc4'
return ''
df = df.reset_index().fillna('')
df = df[df[df_no_meta_col_names].apply(lambda x: x.isin(user_text_input)).any(axis=1)]
df = df.style.map(highlight_matching_strings)
else:
df = df.reset_index().fillna('')
df = df.style
return df
#for hr
# st.cache_data(experimental_allow_widgets=True)
@st.fragment()
def filter_dataframe_hr(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
df = df.copy()
random_id = random.randrange(1,1000)
modification_container = st.container()
with modification_container:
to_filter_columns = st.multiselect("Filter the Homorhythm Results", df.columns)
st.write("Remember that initial choices will constrain subsequent filters!")
# here we are filtering by column
# to_filter_columns = st.multiselect("Limit by Composer, Title, Date, or Voice", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("↳")
# Treat columns with < 10 unique values as categorical
# here
if is_categorical_dtype(df[column]) or df[column].nunique() < 50:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
elif is_numeric_dtype(df[column]):
_min = int(df[column].min())
_max = int(df[column].max())
user_num_input = right.slider(
f"Values for {column}",
_min,
_max,
(_min, _max)
)
df = df[df[column].between(*user_num_input)]
else:
user_text_input = right.text_input(
f"Substring or regex in {column}",
)
if user_text_input:
df = df[df[column].str.contains(user_text_input)]
return df
#for ptypes
# st.cache_data(experimental_allow_widgets=True)
@st.fragment()
def filter_dataframe_ptypes(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
if df is not None:
df = df.copy()
random_id = random.randrange(1,1000)
modification_container = st.container()
with modification_container:
to_filter_columns = st.multiselect("Filter the Presentation Type Results", df.columns)
st.write("Remember that initial choices will constrain subsequent filters!")
# here we are filtering by column
# to_filter_columns = st.multiselect("Limit by Composer, Title, Date, or Voice", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("↳")
# Treat columns with < 10 unique values as categorical
# here
if is_categorical_dtype(df[column]) or df[column].nunique() < 50:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
elif is_numeric_dtype(df[column]):
_min = int(df[column].min())
_max = int(df[column].max())
user_num_input = right.slider(
f"Values for {column}",
_min,
_max,
(_min, _max)
)
df = df[df[column].between(*user_num_input)]
else:
user_text_input = right.text_input(
f"Substring or regex in {column}",
)
if user_text_input:
df = df[df[column].str.contains(user_text_input)]
return df
#for cads
# st.cache_data(experimental_allow_widgets=True)
@st.fragment()
def filter_dataframe_cads(df: pd.DataFrame) -> pd.DataFrame:
"""
Adds a UI on top of a dataframe to let viewers filter columns
Args:
df (pd.DataFrame): Original dataframe
Returns:
pd.DataFrame: Filtered dataframe
"""
df = df.copy()
random_id = random.randrange(1,1000)
modification_container = st.container()
with modification_container:
to_filter_columns = st.multiselect("Filter the Cadence Results", df.columns)
st.write("Remember that initial choices will constrain subsequent filters!")
# here we are filtering by column
# to_filter_columns = st.multiselect("Limit by Composer, Title, Date, or Voice", df.columns)
for column in to_filter_columns:
left, right = st.columns((1, 20))
left.write("↳")
# Treat columns with < 10 unique values as categorical
# here
if is_categorical_dtype(df[column]) or df[column].nunique() < 50:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
elif is_numeric_dtype(df[column]):
_min = int(df[column].min())
_max = int(df[column].max())
user_num_input = right.slider(
f"Values for {column}",
_min,
_max,
(_min, _max)
)
df = df[df[column].between(*user_num_input)]
else:
user_text_input = right.text_input(
f"Substring or regex in {column}",
)
if user_text_input:
df = df[df[column].str.contains(user_text_input)]
return df
# download function for filtered results
# @st.cache_data
# def convert_df(_filtered):
# # IMPORTANT: Cache the conversion to prevent computation on every rerun
# if _filtered is not None:
# return _filtered.to_csv().encode('utf-8')
# intervals functions and forms
# notes piece
# @st.cache_data
def piece_notes(piece, combine_unisons_choice, combine_rests_choice):
nr = piece.notes(combineUnisons = combine_unisons_choice,
combineRests = combine_rests_choice)
nr = piece.detailIndex(nr)
nr = nr.reset_index()
# nr = nr.reset_index()
nr = nr.assign(Composer=piece.metadata['composer'], Title=piece.metadata['title'], Date=piece.metadata['date'])
cols_to_move = ['Composer', 'Title', 'Measure', 'Beat', 'Date']
nr = nr[cols_to_move + [col for col in nr.columns if col not in cols_to_move]]
return nr
# @st.cache_data
def corpus_notes(corpus, combine_unisons_choice, combine_rests_choice):
func = ImportedPiece.notes # <- NB there are no parentheses here
list_of_dfs = corpus.batch(func = func,
kwargs = {'combineUnisons': combine_unisons_choice, 'combineRests': combine_rests_choice},
metadata=False)
func2 = ImportedPiece.detailIndex
list_of_dfs = corpus.batch(func = func2,
kwargs = {'df': list_of_dfs},
metadata = True)
rev_list_of_dfs = [df.reset_index() for df in list_of_dfs]
nr = pd.concat(rev_list_of_dfs)
cols_to_move = ['Composer', 'Title', 'Measure', 'Beat', 'Date']
nr = nr[cols_to_move + [col for col in nr.columns if col not in cols_to_move]]
return nr
# notes form
if st.sidebar.checkbox("Explore Notes"):
# search_type = "ngram"
st.subheader("Explore Notes")
st.write("[Know the code! Read more about CRIM Intervals notes and rests methods](https://github.com/HCDigitalScholarship/intervals/blob/main/tutorial/02_Notes_Rests.md)", unsafe_allow_html=True)
if len(crim_piece_selections) == 0 and len(uploaded_files_list)== 0:
st.write("**No Files Selected! Please Select or Upload One or More Pieces.**")
else:
st.write("Did you **change the piece list**? If so, please **Update and Submit form**")
with st.form("Note Settings"):
combine_unisons_choice = st.selectbox(
"Combine Unisons", [False, True])
combine_rests_choice = st.selectbox(
"Combine Rests", [True, False])
# form submission button
submitted = st.form_submit_button("Update and Run Search")
if submitted:
# for one piece
if 'nr' in st.session_state:
del st.session_state.nr
if corpus_length == 1:
nr = piece_notes(piece,
combine_unisons_choice,
combine_rests_choice)
# # for corpus
elif corpus_length > 1:
nr = corpus_notes(st.session_state.corpus,
combine_unisons_choice,
combine_rests_choice)
if "nr" not in st.session_state:
st.session_state.nr = nr
# and use the session state variables for display
if 'nr' not in st.session_state:
pass
else:
# filter the nr results
st.write("Did you **change the piece list**? If so, please **Update and Submit form**")
st.write("Filter Results by Contents of Each Column")
if len(st.session_state.nr.fillna('')) > 100000:
print("Results are too large to display; please filter again")
else:
filtered_nr = filter_dataframe_nr(st.session_state.nr.fillna(''))
# for one piece
if corpus_length == 1:
nr_no_mdata = filtered_nr.data.drop(['Composer', 'Title', "Date", "Measure", "Beat"], axis=1)
nr_no_mdata = nr_no_mdata.map(str)
nr_counts = nr_no_mdata.apply(lambda x: x.value_counts(), axis=0).fillna('0').astype(int)
nr_counts.index = pd.CategoricalIndex(nr_counts.index, categories=pitch_order, ordered=True)
nr_counts = nr_counts.sort_index()
nr_counts = nr_counts.drop(index='Rest', errors='ignore')
nr_counts = nr_counts[nr_counts.index.notnull()]
nr_counts.drop('index', axis=1, inplace=True)
# Show results
nr_chart = px.bar(nr_counts, x=nr_counts.index.astype(str).tolist(), y=list(nr_counts.columns),
title="Distribution of Pitches in " + piece.metadata['title'])
nr_chart.update_layout(xaxis_title="Pitch",
yaxis_title="Count",
legend_title='Voices')
st.plotly_chart(nr_chart, use_container_width = True)
st.dataframe(filtered_nr, use_container_width = True)
# download option
# csv = convert_df(filtered_nr.data)
# filtered_nr = filtered_nr.to_csv().encode('utf-8')
st.download_button(
label="Download Filtered Notes Data as CSV",
data=filtered_nr.data.to_csv(),
file_name = piece.metadata['title'] + '_notes_results.csv',
mime='text/csv',
key=1,
)
# for corpus:
if corpus_length > 1:
st.write("Did you **change the piece list**? If so, please **Update and Submit form**")
nr_no_mdata = filtered_nr.data.drop(['Composer', 'Title', "Date", "Measure", "Beat"], axis=1)
nr_no_mdata = nr_no_mdata.map(str)
nr_counts = nr_no_mdata.apply(lambda x: x.value_counts(), axis=0).fillna('0').astype(int)
nr_counts.index = pd.CategoricalIndex(nr_counts.index, categories=pitch_order, ordered=True)
nr_counts = nr_counts.sort_index()
nr_counts = nr_counts.drop(index='Rest', errors='ignore')
nr_counts = nr_counts[nr_counts.index.notnull()]
nr_counts.drop('index', axis=1, inplace=True)
# Show results
nr_chart = px.bar(nr_counts, x=nr_counts.index.astype(str).tolist(), y=list(nr_counts.columns),
title="Distribution of Pitches in " + ', '.join(titles))
nr_chart.update_layout(xaxis_title="Pitch",
yaxis_title="Count",
legend_title='Voices')
st.plotly_chart(nr_chart, use_container_width = True)
st.dataframe(filtered_nr, use_container_width = True)
# download option
# csv = convert_df(filtered_nr.data)
# filtered_nr_for_csv = filtered_nr.to_csv().encode('utf-8')
st.download_button(
label="Download Filtered Corpus Notes Data as CSV",
data=filtered_nr.data.to_csv(),
file_name = 'corpus_notes_results.csv',
mime='text/csv',
key=2,
)
# melodic functions
# @st.cache_data
def piece_mel(piece, combine_unisons_choice, combine_rests_choice, kind_choice, directed, compound):
nr = piece.notes(combineUnisons = combine_unisons_choice,
combineRests = combine_rests_choice)
mel = piece.melodic(df = nr,
kind = kind_choice,
directed = directed,
compound = compound)
mel = piece.detailIndex(mel)
# mel = mel.reset_index()
mel = mel.assign(Composer=piece.metadata['composer'], Title=piece.metadata['title'], Date=piece.metadata['date'])
cols_to_move = ['Composer', 'Title', 'Date']
mel = mel[cols_to_move + [col for col in mel.columns if col not in cols_to_move]]
return mel
# @st.cache_data
def corpus_mel(corpus, combine_unisons_choice, combine_rests_choice, kind_choice, directed, compound):
func = ImportedPiece.notes # <- NB there are no parentheses here
list_of_dfs = corpus.batch(func = func,
kwargs = {'combineUnisons': combine_unisons_choice, 'combineRests': combine_rests_choice},
metadata=False)
func2 = ImportedPiece.melodic
list_of_dfs = corpus.batch(func = func2,
kwargs = {'df' : list_of_dfs, 'kind' : kind_choice, 'directed' : directed, 'compound' : compound},
metadata = False)
func3 = ImportedPiece.detailIndex
list_of_dfs = corpus.batch(func = func3,
kwargs = {'df': list_of_dfs},
metadata = True)
mel = pd.concat(list_of_dfs)
cols_to_move = ['Composer', 'Title', 'Date']
mel = mel[cols_to_move + [col for col in mel.columns if col not in cols_to_move]]
return mel
# melodic form
if st.sidebar.checkbox("Explore Melodic Intervals"):
search_type = "mel"
st.subheader("Explore Melodic Intervals")
st.write("[Know the code! Read more about CRIM Intervals melodic interval methods](https://github.com/HCDigitalScholarship/intervals/blob/main/tutorial/06_Melodic_Intervals.md)", unsafe_allow_html=True)
if len(crim_piece_selections) == 0 and len(uploaded_files_list)== 0:
st.write("**No Files Selected! Please Select or Upload One or More Pieces.**")
else:
st.write("Did you **change the piece list**? If so, please **Update and Submit form**")
with st.form("Melodic Interval Settings"):
combine_unisons_choice = st.selectbox(
"Combine Unisons", [False, True])
combine_rests_choice = st.selectbox(
"Combine Rests", [True, False])
select_kind = st.selectbox(
"Select Interval Kind",
["diatonic", "chromatic", "with quality", "zero-based diatonic"])
kind_choice = interval_kinds[select_kind]
directed = st.selectbox(
"Select Directed Interval Status",
[True, False])
compound = st.selectbox(
"Select Compound Interval Status",
[True, False])
# form submission button
submitted = st.form_submit_button("Update and Submit")
if submitted:
# run the function here, passing in settings from the form above
if 'mel' in st.session_state:
del st.session_state.mel
# run the function here, passing in settings from the form above
if corpus_length == 1:
mel = piece_mel(piece,
combine_unisons_choice,
combine_rests_choice,
kind_choice,
directed,
compound)
elif corpus_length > 1:
mel = corpus_mel(st.session_state.corpus,
combine_unisons_choice,
combine_rests_choice,
kind_choice,
directed,
compound)
if "mel" not in st.session_state:
st.session_state.mel = mel
# and use the session state variables for display
if 'mel' not in st.session_state:
pass
else:
# show corpus data for mel with filter options
st.write("Did you **change the piece list**? If so, please **Update and Submit form**")
st.write("Filter Results by Contents of Each Column")
# st.dataframe(st.session_state.mel)
if len(st.session_state.mel.fillna('')) > 100000:
print("Results are too large to display; please filter again")
else:
filtered_mel = filter_dataframe_mel(st.session_state.mel.fillna(''))
# for one piece
if corpus_length == 1:
mel_no_mdata = filtered_mel.data.drop(['Composer', 'Title', "Date", "Measure", "Beat"], axis=1)
mel_no_mdata = mel_no_mdata.map(str)
mel_counts = mel_no_mdata.apply(lambda x: x.value_counts(), axis=0).fillna('0').astype(int)
# apply the categorical list and sort.
if interval_kinds[select_kind] == 'q':
mel_counts = mel_counts.drop(index='')
mel_counts.index = pd.CategoricalIndex(mel_counts.index, categories=interval_order_quality, ordered=True)
mel_counts.sort_index(inplace=True)
else:
mel_counts = mel_counts.sort_index()
mel_counts = mel_counts.drop(index='')
mel_counts.index.rename('interval', inplace=True)
voices = mel_counts.columns.to_list()
mel_chart = px.bar(mel_counts, x=mel_counts.index, y=list(mel_counts.columns),
title="Distribution of Melodic Intervals in " + piece.metadata['title'])
mel_chart.update_layout(xaxis_title="Interval",
yaxis_title="Count",
legend_title='Voices')
# and show results
st.plotly_chart(mel_chart, use_container_width = True)
st.dataframe(filtered_mel, use_container_width = True)
#csv = convert_df(filtered_mel.data)
# filtered_mel = filtered_mel.to_csv().encode('utf-8')
st.download_button(
label="Download Filtered Melodic Data as CSV",
data=filtered_mel.data.to_csv(),
file_name = piece.metadata['title'] + '_melodic_results.csv',
mime='text/csv',
key=3,
)
# # for corpus
elif corpus_length > 1:
mel_no_mdata = filtered_mel.data.drop(['Composer', 'Title', "Date", "Measure", "Beat"], axis=1)
mel_no_mdata = mel_no_mdata.map(str)
mel_counts = mel_no_mdata.apply(lambda x: x.value_counts(), axis=0).fillna('0').astype(int)
# apply the categorical list and sort.
if interval_kinds[select_kind] == 'q':
mel_counts = mel_counts.drop(index='')
mel_counts.index = pd.CategoricalIndex(mel_counts.index, categories=interval_order_quality, ordered=True)
mel_counts.sort_index(inplace=True)
else:
mel_counts = mel_counts.sort_index()
mel_counts = mel_counts.drop(index='')
mel_counts.index.rename('interval', inplace=True)
voices = mel_counts.columns.to_list()
mel_chart = px.bar(mel_counts, x=mel_counts.index, y=list(mel_counts.columns),
title="Distribution of Melodic Intervals in " + ', '.join(titles))
mel_chart.update_layout(xaxis_title="Interval",
yaxis_title="Count",
legend_title='Voices')
# and show results
st.plotly_chart(mel_chart, use_container_width = True)
st.dataframe(filtered_mel, use_container_width = True)
#csv = convert_df(filtered_mel.data)
# filtered_mel = filtered_mel.to_csv().encode('utf-8')
st.download_button(
label="Download Filtered Corpus Melodic Data as CSV",
data=filtered_mel.data.to_csv(),
file_name = 'corpus_melodic_results.csv',
mime='text/csv',
key=4,
)
# harmonic functions
# @st.cache_data
def piece_har(piece, kind_choice, directed, compound, against_low):
har = piece.harmonic(kind = kind_choice,
directed = directed,
compound = compound,
againstLow = against_low).fillna('')
har = piece.detailIndex(har)
# har = har.reset_index()
har = har.assign(Composer=piece.metadata['composer'], Title=piece.metadata['title'], Date=piece.metadata['date'])
cols_to_move = ['Composer', 'Title', 'Date']
har = har[cols_to_move + [col for col in har.columns if col not in cols_to_move]]
return har
# @st.cache_data
def corpus_har(corpus, kind_choice, directed, compound, against_low):
func = ImportedPiece.harmonic
list_of_dfs = corpus.batch(func = func,
kwargs = {'kind' : kind_choice, 'directed' : directed, 'compound' : compound, 'againstLow' : against_low},
metadata = False)
func2 = ImportedPiece.detailIndex
list_of_dfs = corpus.batch(func = func2,
kwargs = {'df': list_of_dfs},
metadata = True)
har = pd.concat(list_of_dfs)
cols_to_move = ['Composer', 'Title', 'Date']
har = har[cols_to_move + [col for col in har.columns if col not in cols_to_move]]
return har
# harmonic form
if st.sidebar.checkbox("Explore Harmonic Intervals"):
search_type = "har"
st.subheader("Explore Harmonic Intervals")
st.write("[Know the code! Read more about CRIM Intervals harmonic interval methods](https://github.com/HCDigitalScholarship/intervals/blob/main/tutorial/07_Harmonic_Intervals.md)", unsafe_allow_html=True)
if len(crim_piece_selections) == 0 and len(uploaded_files_list)== 0:
st.write("**No Files Selected! Please Select or Upload One or More Pieces.**")
else:
st.write("Did you **change the piece list**? If so, please **Update and Submit form**")
with st.form("Harmonic Interval Settings"):
directed = st.selectbox(
"Select Directed Interval Status",
[True, False])
compound = st.selectbox(
"Select Compound Interval Status",
[True, False])
select_kind = st.selectbox(
"Select Interval Kind",
["diatonic", "chromatic", "with quality", "zero-based diatonic"])
kind_choice = interval_kinds[select_kind]
against_low = st.selectbox("Calculate Intervals Only Against Lowest Voice",
[False, True])
# form submission button
submitted = st.form_submit_button("Update and Submit")
if submitted:
# run the function here, passing in settings from the form above
if 'har' in st.session_state:
del st.session_state.har
# run the function here, passing in settings from the form above
if corpus_length == 1:
har = piece_har(piece,
kind_choice,
directed,
compound,
against_low)
elif corpus_length > 1:
har = corpus_har(st.session_state.corpus,
kind_choice,
directed,
compound,
against_low)