awacke1 commited on
Commit
e3c3257
·
1 Parent(s): 32ab369

Create new file

Browse files
Files changed (1) hide show
  1. download.py +160 -0
download.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pickle
3
+ import pandas as pd
4
+ import json
5
+ import base64
6
+ import uuid
7
+ import re
8
+
9
+ import importlib.util
10
+
11
+
12
+ def import_from_file(module_name: str, filepath: str):
13
+ """
14
+ Imports a module from file.
15
+ Args:
16
+ module_name (str): Assigned to the module's __name__ parameter (does not
17
+ influence how the module is named outside of this function)
18
+ filepath (str): Path to the .py file
19
+ Returns:
20
+ The module
21
+ """
22
+ spec = importlib.util.spec_from_file_location(module_name, filepath)
23
+ module = importlib.util.module_from_spec(spec)
24
+ spec.loader.exec_module(module)
25
+ return module
26
+
27
+
28
+ def notebook_header(text):
29
+ """
30
+ Insert section header into a jinja file, formatted as notebook cell.
31
+ Leave 2 blank lines before the header.
32
+ """
33
+ return f"""# # {text}
34
+ """
35
+
36
+
37
+ def code_header(text):
38
+ """
39
+ Insert section header into a jinja file, formatted as Python comment.
40
+ Leave 2 blank lines before the header.
41
+ """
42
+ seperator_len = (75 - len(text)) / 2
43
+ seperator_len_left = math.floor(seperator_len)
44
+ seperator_len_right = math.ceil(seperator_len)
45
+ return f"# {'-' * seperator_len_left} {text} {'-' * seperator_len_right}"
46
+
47
+
48
+ def to_notebook(code):
49
+ """Converts Python code to Jupyter notebook format."""
50
+ notebook = jupytext.reads(code, fmt="py")
51
+ return jupytext.writes(notebook, fmt="ipynb")
52
+
53
+
54
+ def open_link(url, new_tab=True):
55
+ """Dirty hack to open a new web page with a streamlit button."""
56
+ # From: https://discuss.streamlit.io/t/how-to-link-a-button-to-a-webpage/1661/3
57
+ if new_tab:
58
+ js = f"window.open('{url}')" # New tab or window
59
+ else:
60
+ js = f"window.location.href = '{url}'" # Current tab
61
+ html = '<img src onerror="{}">'.format(js)
62
+ div = Div(text=html)
63
+ st.bokeh_chart(div)
64
+
65
+
66
+ def download_button(object_to_download, download_filename, button_text):
67
+ """
68
+ Generates a link to download the given object_to_download.
69
+ From: https://discuss.streamlit.io/t/a-download-button-with-custom-css/4220
70
+ Params:
71
+ ------
72
+ object_to_download: The object to be downloaded.
73
+ download_filename (str): filename and extension of file. e.g. mydata.csv,
74
+ some_txt_output.txt download_link_text (str): Text to display for download
75
+ link.
76
+ button_text (str): Text to display on download button (e.g. 'click here to download file')
77
+ pickle_it (bool): If True, pickle file.
78
+ Returns:
79
+ -------
80
+ (str): the anchor tag to download object_to_download
81
+ Examples:
82
+ --------
83
+ download_link(your_df, 'YOUR_DF.csv', 'Click to download data!')
84
+ download_link(your_str, 'YOUR_STRING.txt', 'Click to download text!')
85
+ """
86
+ # if pickle_it:
87
+ # try:
88
+ # object_to_download = pickle.dumps(object_to_download)
89
+ # except pickle.PicklingError as e:
90
+ # st.write(e)
91
+ # return None
92
+
93
+ # if:
94
+ if isinstance(object_to_download, bytes):
95
+ pass
96
+
97
+ elif isinstance(object_to_download, pd.DataFrame):
98
+ object_to_download = object_to_download.to_csv(index=False)
99
+ # Try JSON encode for everything else
100
+ else:
101
+ object_to_download = json.dumps(object_to_download)
102
+
103
+ try:
104
+ # some strings <-> bytes conversions necessary here
105
+ b64 = base64.b64encode(object_to_download.encode()).decode()
106
+ except AttributeError as e:
107
+ b64 = base64.b64encode(object_to_download).decode()
108
+
109
+ button_uuid = str(uuid.uuid4()).replace("-", "")
110
+ button_id = re.sub("\d+", "", button_uuid)
111
+
112
+ custom_css = f"""
113
+ <style>
114
+ #{button_id} {{
115
+ display: inline-flex;
116
+ align-items: center;
117
+ justify-content: center;
118
+ background-color: rgb(255, 255, 255);
119
+ color: rgb(38, 39, 48);
120
+ padding: .25rem .75rem;
121
+ position: relative;
122
+ text-decoration: none;
123
+ border-radius: 4px;
124
+ border-width: 1px;
125
+ border-style: solid;
126
+ border-color: rgb(230, 234, 241);
127
+ border-image: initial;
128
+ }}
129
+ #{button_id}:hover {{
130
+ border-color: rgb(246, 51, 102);
131
+ color: rgb(246, 51, 102);
132
+ }}
133
+ #{button_id}:active {{
134
+ box-shadow: none;
135
+ background-color: rgb(246, 51, 102);
136
+ color: white;
137
+ }}
138
+ </style> """
139
+
140
+ dl_link = (
141
+ custom_css
142
+ + f'<a download="{download_filename}" id="{button_id}" href="data:file/txt;base64,{b64}">{button_text}</a><br><br>'
143
+ )
144
+ # dl_link = f'<a download="{download_filename}" id="{button_id}" href="data:file/txt;base64,{b64}"><input type="button" kind="primary" value="{button_text}"></a><br></br>'
145
+
146
+ st.markdown(dl_link, unsafe_allow_html=True)
147
+
148
+
149
+ # def download_link(
150
+ # content, label="Download", filename="file.txt", mimetype="text/plain"
151
+ # ):
152
+ # """Create a HTML link to download a string as a file."""
153
+ # # From: https://discuss.streamlit.io/t/how-to-download-file-in-streamlit/1806/9
154
+ # b64 = base64.b64encode(
155
+ # content.encode()
156
+ # ).decode() # some strings <-> bytes conversions necessary here
157
+ # href = (
158
+ # f'<a href="data:{mimetype};base64,{b64}" download="{filename}">{label}</a>'
159
+ # )
160
+ # return href