import streamlit as st
from urllib.parse import quote, urlencode
import base64
import json
import gzip
code = """import streamlit as st
import pandas as pd
chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
st.area_chart(chart_data)
"""
requirements = """streamlit==1.27.2 # currently pinned to this version
altair
pandas
"""
files = [
{
"name": "some_file_loaded_from_a_url.py",
# this file will be downloaded on the fly, this will keep the generated url short, and the content always up to date
"url": "https://github.com/projectmesa/mesa-examples/raw/main/examples/virus_on_network/virus_on_network/model.py",
},
{
"name": "other_file_from_data.py",
# if content is provided, it's assumed to be text (utf8 encoded)
"content": "plain text",
},
{
"name": "binary_data.dat",
# encode binary data in base64, but make sure to include the encoding
"content": base64.b64encode(b"binary data").decode("utf8"),
"encoding": "base64"
}
]
json_object = {
"code": code,
"requirements": requirements,
"files": files
}
json_text = json.dumps(json_object)
# compress using gzip to make the url shorter
compressed_json_text = gzip.compress(json_text.encode("utf8"))
# but encode in base64
base64_text = base64.b64encode(compressed_json_text).decode("utf8")
c = quote(base64_text)
# use the c= argument, c stands for compressed
url = f"https://py.cafe/snippet/streamlit/v1#c={c}"
st.link_button("Open snippet in new tab", url)
st.markdown(f"```\n{url}\n```")