Guest User

Download_Button

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