danielhn commited on
Commit
d6661a1
1 Parent(s): a028319

Add helper functions

Browse files
Files changed (1) hide show
  1. streamlit_helpers.py +150 -0
streamlit_helpers.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import Counter
2
+ from typing import List
3
+ import numpy as np
4
+ import streamlit as st # pylint: disable=import-error
5
+ import pandas as pd
6
+
7
+
8
+ class Collapsable:
9
+ """
10
+ Creates a collapsable text composed of a preamble (clickable section of text)
11
+ and epilogue (collapsable text).
12
+ """
13
+
14
+ def __init__(self, preamble="", epilogue=""):
15
+ self.preamble = preamble
16
+ self.epilogue = epilogue
17
+ self.small_font = 18
18
+ self.large_font = 18
19
+ self.sections = []
20
+
21
+ def add_section(self, heading, text):
22
+ # Convert text to bullet points if it is a list
23
+ if isinstance(text, list):
24
+ text = (
25
+ "<ul>"
26
+ + "".join(
27
+ [
28
+ f'<li style="font-size:{self.small_font}px;" align="justify">{x}</li>'
29
+ for x in text
30
+ ]
31
+ )
32
+ + "</ul>"
33
+ )
34
+
35
+ # Append section
36
+ self.sections.append((heading, text))
37
+
38
+ def deploy(self):
39
+
40
+ secs = "".join(
41
+ [
42
+ (
43
+ "<details>"
44
+ f"<summary style='font-size:{self.large_font}px;'>{heading}</summary>"
45
+ f"<blockquote style='font-size:{self.small_font}px;max-width: 80%;'"
46
+ f"align='justify'>{text}</details>"
47
+ )
48
+ for heading, text in self.sections
49
+ ]
50
+ )
51
+ collapsable_sec = f"""
52
+ <ol>
53
+ {self.preamble}
54
+ {secs}
55
+ {self.epilogue}
56
+ </ol>
57
+ """
58
+ st.markdown(collapsable_sec, unsafe_allow_html=True)
59
+
60
+
61
+ def add_filter(
62
+ data_frame_list: List[pd.DataFrame],
63
+ name: str,
64
+ label: str,
65
+ options: List[str] = None,
66
+ num_cols: int = 1,
67
+ last_is_others: bool = True,
68
+ ):
69
+ """
70
+ Creates a filter on the side bar using checkboxes
71
+ """
72
+
73
+ # Get list of all options and return if no options are available
74
+ all_options = set(data_frame_list[-1][label])
75
+ if "-" in all_options:
76
+ all_options.remove("-")
77
+ if len(all_options) == 0:
78
+ return data_frame_list
79
+
80
+ st.markdown(f"#### {name}")
81
+
82
+ # Create list of options if selectable options are not provided
83
+ if options is None:
84
+ options_dict = Counter(data_frame_list[-1][label])
85
+ sorted_options = sorted(options_dict, key=options_dict.get, reverse=True)
86
+ if "-" in sorted_options:
87
+ sorted_options.remove("-")
88
+ if len(sorted_options) > 8:
89
+ options = list(sorted_options[:7]) + ["others"]
90
+ last_is_others = True
91
+ else:
92
+ options = list(sorted_options)
93
+ last_is_others = False
94
+
95
+ cols = st.columns(num_cols)
96
+ instantiated_checkbox = []
97
+ for idx in range(len(options)):
98
+ with cols[idx % num_cols]:
99
+ instantiated_checkbox.append(
100
+ st.checkbox(options[idx], False, key=f"{label}_{options[idx]}")
101
+ )
102
+
103
+ selected_options = [
104
+ options[idx] for idx, checked in enumerate(instantiated_checkbox) if checked
105
+ ]
106
+
107
+ # The last checkbox will always correspond to "other"
108
+ if instantiated_checkbox[-1] and last_is_others:
109
+ selected_options = selected_options[:-1]
110
+ other_options = [x for x in all_options if x not in options]
111
+ selected_options = set(selected_options + other_options)
112
+
113
+ if len(selected_options) > 0:
114
+ for idx, _ in enumerate(data_frame_list):
115
+ data_frame_list[idx] = data_frame_list[idx][
116
+ [
117
+ any([x == model_entry for x in selected_options])
118
+ for model_entry in data_frame_list[idx][label]
119
+ ]
120
+ ]
121
+ return data_frame_list
122
+
123
+
124
+ def slider_filter(
125
+ data_frame_list: List[pd.DataFrame],
126
+ title: str,
127
+ filter_by: str,
128
+ max_val: int = 1000,
129
+ ):
130
+ """
131
+ Creates slider to filter dataframes according to a given label.
132
+ label must be numeric. Values are in millions.
133
+ """
134
+
135
+ start_val, end_val = st.select_slider(
136
+ title,
137
+ options=[str(x) for x in np.arange(0, max_val + 1, 10, dtype=int)],
138
+ value=("0", str(max_val)),
139
+ )
140
+
141
+ for idx in range(len(data_frame_list)):
142
+ data_frame_list[idx] = data_frame_list[idx][
143
+ [
144
+ int(model_entry) >= int(start_val) * 1000000
145
+ and int(model_entry) <= int(end_val) * 1000000
146
+ for model_entry in data_frame_list[idx][filter_by]
147
+ ]
148
+ ]
149
+
150
+ return data_frame_list