def select_slider(): st.write(""" # Introducing st.select_slider With `st.select_slider`, you can now display a slider using values from a list or object. This functions similarly to **[st.slider](https://docs.streamlit.io/en/stable/api.html#streamlit.slider)** but for discrete and/or non-numerical data. Please note that values are not sorted and will be listed in the order they are provided. For more details, please see our [documentation](https://docs.streamlit.io/en/stable/api.html#streamlit.select_slider) """) with st.echo("below"): st.write("### Example 1: ###") w1 = st.select_slider("Label 1", options=[ 'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet' ]) st.write("Selected value:", w1) with st.echo("below"): st.write("### Example 2:###") w2 = st.select_slider("Label 1", options=[10, 40, 50, 90, 121, 800, 1000], value=(40, 121)) st.write("Selected value:", w2)
def show_media_widgets() -> None: DATA = Path('data/external') st.write(""" ### Display images """) st.write("#### Reference images") with st.echo(): st.image( "https://www.dogalize.com/wp-content/uploads/2018/03/ceiling-cat.jpg", caption="Ceiling cat", use_column_width=True) st.write("#### Embed image") with st.echo(): st.image( """data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAQEBAPEBAPEBAPFRAVDw8PDxAVFw8PFRUWFhURFxUYHSggGB0lHhUVITEhJSkrLi4uFx8zODMsNygtLisBCgoKDg0OFxAQGy0fHyUrLS0tLS0tLS0tLS0tLS0tLSsrLS0tKy0tLS0tLS0rLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAJQBVAMBIgACEQEDEQH/xAAbAAACAgMBAAAAAAAAAAAAAAAAAQIFAwQGB//EADoQAAEEAAUCBAQEBQQBBQAAAAEAAgMRBAUSITFBURMiYXEGgZGxMkJSoRRigsHwFSPR4fEHQ1OSov/EABgBAAMBAQAAAAAAAAAAAAAAAAABAgME/8QAIxEBAQACAgMAAgIDAAAAAAAAAAECEQMhEjFBE1FhcSIyQv/aAAwDAQACEQMRAD8A9TcoFZCoFURJoCaRhNJNANNJNIGE0gmkYSTQkEUlJJI0UJpIATCEwgEmhCZBMIUZDQJ7IDahW0xcxl+fefRNG6Nt+WSwW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FzC8gcsI6d6/MPstrLXR/hILSfQ0VfSYBoNgJxx10H0WP5Zv008P5abcS5vlALT7WCs7c3f+Esd78hbrB3CzAN7D6K5yp/GrWvLjYFH1/wCVmfjJG7USOxW8A3ssgjBT/KX41FKNe4Ba702/ZVOPy4v/ABWd744XaDDN7BD8ID0+yrzpeEcIMkutlmgyctN0uyOAHr+yYwHqUbo1FPBG4NA0pK8GCPdCCb5UUIQAmkhJRpoQkDQhCRmmhCAEIQkBSVIQkCpFIQgCkIQmGN60p0ITpxXzBYAE0LCtoYalpTQpNINUgkhKmk1Z2BCEQieskQQhaRNZkghCpDHIFja0WhCX00iFPShCYAaszAhCuIrIE7SQtEJtKytQhMkwhCEB/9k=""", caption="embedded image", width=500) # audio st.write("------") st.subheader("Embed audio") with st.echo(): audio_file = open(DATA / 'applause7.mp3', 'rb') st.audio(audio_file, format='audio/mp3') st.write("_Note: seems to have trouble in Firefox_") # video st.write("------") st.subheader("Embed video") with st.echo(): st.video("https://www.youtube.com/watch?v=B2iAodr0fOo", start_time=2)
def run(): with st.echo(): @st.cache def get_histo(): print('get_histo called') df = pd.DataFrame( np.random.randn(200, 1), columns=['a'] ) return np.histogram( df.a, bins=25)[0] hist_values = get_histo() st.bar_chart(hist_values) with st.echo(): @st.cache def get_bar_chart_data(): print('get_bar_chart_data called') return pd.DataFrame( np.random.randn(50, 3), columns=["a", "b", "c"] ) chart_data = get_bar_chart_data() st.bar_chart(chart_data)
def show_basic_caching() -> None: st.header("Improve performance by caching") # TODO: load big file # max size # cache complex object -> custom hash function # st.write( """Caching is the core mechanic of streamlit to allow for an acceptable UX: Simply decorate a function with `st.cache`""") use_cache = st.checkbox("Use caching?") st.write("Used function for loading the data:") load_data = _with_cache() if use_cache else _without_caching() st.write("Load and inspect the downloaded dataset") # simple caching with st.echo(): base_url = "https://raw.githubusercontent.com/vega/vega-datasets/master/data/" src = st.selectbox("Vega Dataset:", ["gapminder.json", "jobs.json", "flights-20k.json"]) df = load_data(base_url + src) # n = st.slider("Show first n entries:", min_value=0, max_value=len(df), value=10, step=1000) st.dataframe(df.head(100)) st.subheader("Not just dataframes can be cached") with st.echo(): create_chart = st.cache( _create_chart, allow_output_mutation=True) if use_cache else _create_chart chart = create_chart(df) st.altair_chart(chart, use_container_width=True) st.info("**Hint**: Data is cached across sessions!")
def caption_demo(): st.image( "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/apple/279/ant_1f41c.png", width=100, ) st.write(""" # Try out `st.caption`! Ever wanted to add some small text to your streamlit app? Now you can, with `st.caption`: """) with st.echo(): st.write("This is normal text") st.caption("This is small text 🐜") st.write("---") st.write("And `st.caption` also supports markdown:") with st.echo(): st.caption( "Make it *italic* or **bold** or add [a link](https://streamlit.io/)" ) st.write("---") st.write("It's also great to add a caption to a plot:") with st.echo(): st.line_chart([2, 4, 3]) st.caption("Just an example plot")
def DA(): st.header('I - Data analyst') st.markdown('**_1.1 Edge checking_**') book1 = pd.read_csv('data/asoiaf-book1-edges.csv') book1.drop(['Type', 'book'], axis=1, inplace=True) st.dataframe(book1) r, c = book1.shape st.write(' - Number of edges: ', r) st.markdown('**1.2 Duplicate edges checking**') with st.echo(): duplicate = book1.duplicated().sum() st.write('- Duplicate rows of diamonds DataFrame: ', duplicate) st.write('=> NO DUPLICATE. Let\'s check how many NODES in our network?') st.markdown('_**1.3 Nodes checking**_') nodeSource = book1['Source'] nodeSource = nodeSource.rename({'Source': 'Node'}) nodeTarget = book1['Target'] nodeTarget = nodeTarget.rename({'Target': 'Node'}) nodeChecking = nodeSource.append(nodeTarget) nodeChecking = nodeChecking.drop_duplicates() nodeChecking.reset_index(drop=True, inplace=True) r, = nodeChecking.shape st.write('NUMBER OF NODES: ', r) st.write( 'There are ', r, ' **NODES** in total of our networks. But any _**NULL VALUES**_ in our dataframe?' ) st.markdown('_**1.4 Checking null values**_') with st.echo(): pd.isnull(book1).sum() > 0 st.write( '=> NO NULL in our dataframe. PERFECT!!!. Let\'s move to next part')
def run(): st.write('## Default rendering') with st.echo(): @st.cache def get_dataframe_data(): print('get_dataframe_data called') return pd.DataFrame(np.random.randn(10, 5), columns=('col %d' % i for i in range(5))) df = get_dataframe_data() st.write(df.head()) st.write('## Hiding index') with st.echo(): hdf = df.assign(hack='').set_index('hack') st.write(hdf.head()) st.write('## Using a table') with st.echo(): st.table(df.head()) st.write('## Using pandas styler') with st.echo(): st.dataframe(df.head().style.highlight_max(axis=0))
def show_numeric_widgets() -> None: st.header("Numeric widgets") st.subheader("Slider") with st.echo(): score = st.slider("How awesome is streamlit?", min_value=0., max_value=10., value=5., step=0.5, format="%.1f") st.write( f"_Note: the type of the (min/max/.) value and step must be of the same type, i.e. mixing float and int leads to an error_" ) st.write("-" * 6) st.subheader("Number input") with st.echo(): st.number_input("How awesome is streamlit?", min_value=0., max_value=10., value=5., step=0.5, format="%.1f") st.write( f"_Note: the type of the (min/max/.) value and step must be of the same type, i.e. mixing float and int leads to an error_" )
def show_misc_widgets() -> None: st.header("Misc widgets") st.subheader("Date input") with st.echo(): date = st.date_input("What day is today?") st.write(f"Today is {date}") st.markdown("------") st.subheader("Time input") with st.echo(): time = st.time_input("What time is it?") st.write(f"Currently it is {time}") st.markdown("------") st.subheader("File Uploader") st.write( "This widget is useful for deployed ML apps hosted on a remote server. " "Default limit of uploaded file is 200MB, but the limit can be adjusted using `server.maxUploadSize`" ) with st.echo(): csv = st.file_uploader("Please choose a CSV file", type="csv", encoding="utf-8") if csv is not None: df = pd.read_csv(csv) st.write(df)
def bokeh_plot(chart_type: str, df): """ return bokeh plots """ if chart_type == "Scatter": with st.echo(): df["color"] = df["species"].replace({ "Adelie": "blue", "Chinstrap": "orange", "Gentoo": "green" }) fig = figure(title="Bill Depth by Bill Length") fig.circle(source=df, x="bill_depth_mm", y="bill_length_mm", color="color") elif chart_type == "Histogram": with st.echo(): hist, edges = np.histogram(df["bill_depth_mm"].dropna(), bins=10) fig = figure(title="Count of Bill Depth Observations") fig.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], line_color="white") elif chart_type == "Bar": with st.echo(): fig = figure( title="Mean Bill Depth by Species", x_range=["Gentoo", "Chinstrap", "Adelie"], ) fig.vbar( source=df.groupby("species", dropna=False).mean(), x="species", top="bill_depth_mm", width=0.8, ) elif chart_type == "Line": with st.echo(): fig = figure(title="Bill Length Over Time", x_axis_type="datetime") fig.line(source=df.reset_index(), x="index", y="bill_length_mm") elif chart_type == "3D Scatter": st.write("Bokeh doesn't do 3D ☹️. Here's 2D.") df["color"] = df["species"].replace({ "Adelie": "blue", "Chinstrap": "orange", "Gentoo": "green" }) fig = figure(title="Bill Depth by Bill Length") fig.circle(source=df, x="bill_depth_mm", y="bill_length_mm", color="color") return fig
def menu_ex_listes_1(): st.title("TP - Listes : Exercices I") ### EXERCICE 1 ### st.subheader("Exercice 1 :") st.write(''' 1. Créer une liste _L1_ contenant les valeurs 3, 4, 5. 3. Modifier le premier élément de cette liste en lui donnant la valeur 1 puis afficher cette liste pour vérifier. 4. Créer une liste _L2_ avec 3 éléments de type différents. 5. Afficher le deuxième élément de cette liste ainsi que son type. 6. Créer une liste _L3_ avec 6 éléments avec au moins 2 types différents. 7. Afficher la longueur de cette liste. 8. Parcourir cette liste, et pour chaque élément, afficher son indice, sa valeur et son type. ''') cols = st.beta_columns([1, 1]) with cols[0]: with st.beta_expander("Aide"): st.write( "Remplacer les '...' en enlevant les mot clefs _try :_ , _except :_ et _pass_ :" ) with st.echo(): try: L1 = [..., ..., ...] L1[...] = 1 ... L2 = [1, 'a', True] # Un entier, un charactère et un booléen print(..., ...) L3 = [1, 'a', 'b', 3, 4, 5] print(...(L3)) for index in ...: print(..., ..., ...) except: pass with cols[1]: with st.beta_expander("Solution"): st.write( "Recopie quand même dans EduPython pour t'assurer que tu comprends" ) with st.echo(): L1 = [3, 4, 5] L1[0] = 1 # Le premier élément à pour indice 0 print(L1) L2 = [1, 'a', True] # Un entier, un charactère et un booléen print( L2[1], type(L2[1]) ) # On donne le type d'un élément en utilisant la fonction type() L3 = [1, 'a', 'b', 3, 4, 5] print( len(L3) ) # on peut avoir la longueur d'une liste en utilisant la fonction len() for index in range(len(L3)): print(index, L3[index], type(L3[index]))
def columns(): st.write(""" # Go horizontal with columns `st.beta_columns` acts similarly to `st.sidebar`, except now you can put the columns anywhere in your app. Just declare each column as a new variable, and then you can add in ANY element or component available from the Streamlit library. --- ## Compare things side-by-side! """) with st.echo("below"): svg = """ <svg xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="black" /> </svg> """ col1, col2 = st.beta_columns(2) col1.write("### Original") col1.code(svg) col2.write("### Encoded") col2.code(html.escape(svg)) st.write("### Code") st.write(""" --- ## Or create a grid layout! """) with st.echo("below"): colors = ['red', 'pink', 'orange', 'green', 'blue', 'purple'] svg = """ <svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet" width="100%" height="100%" > <rect width="100%" height="100%" fill="{0}"/> </svg> """ for i in range(1, 3): cols = st.beta_columns((2, 1, 3, 4)) for col in cols: col.image(svg.format(random.choice(colors)), use_column_width=True) st.write("### Code")
def matplotlib_plot(chart_type: str, df): """ return matplotlib plots """ fig, ax = plt.subplots() if chart_type == "Scatter": with st.echo(): df["color"] = df["species"].replace({ "Adelie": 1, "Chinstrap": 2, "Gentoo": 3 }) ax.scatter(x=df["bill_depth_mm"], y=df["bill_length_mm"], c=df["color"]) plt.title("Bill Depth by Bill Length") plt.xlabel("Bill Depth (mm)") plt.ylabel("Bill Length (mm)") elif chart_type == "Histogram": with st.echo(): plt.title("Count of Bill Depth Observations") ax.hist(df["bill_depth_mm"]) plt.xlabel("Bill Depth (mm)") plt.ylabel("Count") elif chart_type == "Bar": with st.echo(): df_plt = df.groupby("species", dropna=False).mean().reset_index() ax.bar(x=df_plt["species"], height=df_plt["bill_depth_mm"]) plt.title("Mean Bill Depth by Species") plt.xlabel("Species") plt.ylabel("Mean Bill Depth (mm)") elif chart_type == "Line": with st.echo(): ax.plot(df.index, df["bill_length_mm"]) plt.title("Bill Length Over Time") plt.ylabel("Bill Length (mm)") elif chart_type == "3D Scatter": ax = fig.add_subplot(projection="3d") with st.echo(): df["color"] = df["species"].replace({ "Adelie": 1, "Chinstrap": 2, "Gentoo": 3 }) ax.scatter3D( xs=df["bill_depth_mm"], ys=df["bill_length_mm"], zs=df["body_mass_g"], c=df["color"], ) ax.set_xlabel("bill_depth_mm") ax.set_ylabel("bill_length_mm") ax.set_zlabel("body_mass_g") plt.title("3D Scatterplot") return fig
def run(): st.write('## Displaying local images') st.write( 'Please refer to the [streamlit API reference](https://docs.streamlit.io/en/stable/api.html#display-media) for more audio or video code samples' ) with st.echo(): from PIL import Image image = Image.open('images/wagon.png') st.image(image, caption='Le Wagon', use_column_width=False) st.write('## Using local images for links or background') with st.echo(): import base64 @st.cache def load_image(path): with open(path, 'rb') as f: data = f.read() encoded = base64.b64encode(data).decode() return encoded def image_tag(path): encoded = load_image(path) tag = f'<img src="data:image/png;base64,{encoded}">' return tag def background_image_style(path): encoded = load_image(path) style = f''' <style> body {{ background-image: url("data:image/png;base64,{encoded}"); background-size: cover; }} </style> ''' return style image_path = 'images/python.png' image_link = 'https://docs.python.org/3/' st.write('*Hey*, click me I\'m a button!') st.write(f'<a href="{image_link}">{image_tag(image_path)}</a>', unsafe_allow_html=True) if st.checkbox('Show background image', False): st.write(background_image_style(image_path), unsafe_allow_html=True)
def content(): st.title("Data Access and Visualize") st.markdown(""" * [CSSEGISandData COVID-19 Github Repository](https://github.com/CSSEGISandData/COVID-19) """) d = load_proxy() st.dataframe(d.head()) st.header("Top 10 Countries by Peak **Active** Cases") with st.echo(): top10 = d.groupby(['Country']).Active.max().reset_index() \ .sort_values('Active', ascending=False) \ .head(10) st.dataframe(top10) st.header("A Few Important Country/Province to Note") st.markdown(""" Note that some provinces in China already had a bell shape curve for number of **Active** cases, whereas many European countries are in the growing phase, including Turkey. """) with st.echo(): ch = alt.Chart(d) \ .transform_fold(['Active', 'Deaths', 'Recovered'], as_=['type', 'count']) \ .mark_point(size=30, opacity=0.6) \ .encode(x='Day:T', y='count:Q', tooltip=['Day', 'count:Q', 'type:N'], color='type:N') \ .interactive() st.subheader("Hubei Stats") illustrate(d.query("Province == 'Hubei' ")) st.subheader("Hunan Stats") illustrate(d.query("Province == 'Hunan' ")) st.subheader("Italy Stats") illustrate(d.query("Country == 'Italy' ")) st.subheader("Spain Stats") illustrate(d.query("Country == 'Spain' ")) st.subheader("Germany Stats") illustrate(d.query("Country == 'Germany' ")) st.subheader("New York Stats") illustrate(d.query("Province == 'New York' "), with_data=True) st.subheader("Turkey Stats") illustrate(d.query("Country == 'Turkey' "))
def test_echo(self): for echo, echo_index, output_index in [ (lambda: st.echo(), 0, 1), (lambda: st.echo("above"), 0, 1), (lambda: st.echo("below"), 1, 0), ]: # The empty lines below are part of the test. Do not remove them. with echo(): st.write("Hello") "hi" def foo(x): y = x + 10 print(y) class MyClass(object): def do_x(self): pass def do_y(self): pass echo_str = """```python st.write("Hello") "hi" def foo(x): y = x + 10 print(y) class MyClass(object): def do_x(self): pass def do_y(self): pass ```""" element = self.get_delta_from_queue(echo_index).new_element self.assertEqual(echo_str, element.markdown.body) element = self.get_delta_from_queue(output_index).new_element self.assertEqual("Hello", element.markdown.body) self.clear_queue()
def pd_plot(chart_type: str, df): """ return pd matplotlib plots """ fig, ax = plt.subplots() if chart_type == "Scatter": with st.echo(): df["color"] = df["species"].replace({ "Adelie": "blue", "Chinstrap": "orange", "Gentoo": "green" }) ax_save = df.plot( kind="scatter", x="bill_depth_mm", y="bill_length_mm", c="color", ax=ax, title="Bill Depth by Bill Length", ) elif chart_type == "Histogram": with st.echo(): ax_save = df["bill_depth_mm"].plot( kind="hist", ax=ax, title="Count of Bill Depth Observations") plt.xlabel("Bill Depth (mm)") elif chart_type == "Bar": with st.echo(): ax_save = (df.groupby("species", dropna=False).mean().plot( kind="bar", y="bill_depth_mm", title="Mean Bill Depth by Species", ax=ax, )) plt.ylabel("Bill Depth (mm)") elif chart_type == "Boxplot": with st.echo(): ax_save = df.plot(kind="box", ax=ax) elif chart_type == "Line": with st.echo(): ax_save = df.plot(kind="line", use_index=True, y="bill_length_mm", ax=ax) plt.title("Bill Length Over Time") plt.ylabel("Bill Length (mm)") elif chart_type == "3D Scatter": st.write("Pandas doesn't do 3D ☹️. Here's 2D.") ax_save = df.plot(kind="scatter", x="bill_depth_mm", y="bill_length_mm", ax=ax) plt.title("Just a 2D Scatterplot") return fig
def run(): st.write(''' Streamlit is going to reinterpret the whole code generating the page \ from scratch each time the user interacts with a control element \ (slider, input, etc). This will cause the page to feel unresponsive \ as its content grows For example, we do not want to load our whole dataset everytime the user switches the position of a slider. How to deal with that? The `@st.cache` decorator allows the functions on which it is placed \ to be executed only once ''') st.write(''' Let's take an example. The following dataframe gets constructed \ on every user interaction of the user with any control element \ in the page. The location of the element in the page does not matter Because the dataframe is not cached, its random data changes \ on every user interaction, for example with this totally unrelated slider ''') with st.echo(): df = pd.DataFrame(np.random.randn(3, 3), columns=['a', 'b', 'c']) st.write(df) st.slider('Hi, I am a totally unrelated slider', 1, 10, 1) st.write(''' Try changing the radio buttons at the top of the sidebar... \ They also change the content of dataframe because the code gets \ reinterpreted each time the user interacts with a control element On the contrary, this second dataframe is returned by a function \ decorated by `@st.cache`. Its content does not change \ as the user slides. If the dataframe has a few million lines, \ the difference will have a real impact on the responsiveness \ of the page ''') with st.echo(): @st.cache def get_cached_data(): return pd.DataFrame(np.random.randn(3, 3), columns=['a', 'b', 'c']) cached_df = get_cached_data() st.write(cached_df)
def show_general_widgets() -> None: st.header("General widgets") st.subheader("Checkbox") with st.echo(): feature_flag = st.checkbox("Enable feature flag?") st.write(f"Feature is `{'enabled' if feature_flag else 'disabled'}`") st.markdown("------") st.subheader("Button") with st.echo(): if st.button("celebrate"): st.balloons()
def show_messages() -> None: st.header("Message types") with st.echo(): st.info("This is just some information") with st.echo(): st.success("This is a **success** message") with st.echo(): st.warning("This is a _warning_ message") with st.echo(): st.error("This is an __error__ message") with st.echo(): st.exception("This is an error message") st.exception(RuntimeError("This is a runtime error"))
def file_uploader(): st.write(""" ## File Uploader: Consolidating Reruns for Multiple Files In prior versions of Streamlit, each time a file was uploaded a re-run occurred. If multiple files were selected as a batch to upload, it would trigger multiple re-runs for each file in the batch. With this release of Streamlit, we are consolidating re-runs for files uploaded in a batch. """) st.write(""" ### Case #1 Select multiple files for upload and note that the dataframe shown below changes after all the files have finished uploading. The change in the dataframe indicates a re-run """) with st.echo("below"): # Code for above snippet a = st.file_uploader(label='Multiple Reruns', accept_multiple_files=True, key='test1') st.write(a) st.write('Here is a randomly generated dataframe. With every re-run the numbers in the dataframe should change') with st.echo('above'): df = pd.DataFrame(np.random.randint(0, 10, size=(5, 2)), columns=list('AB')) st.write(df) st.write(""" --- ### Case #2 Select a large file for upload and while the large file is uploading hit the 'Browse Files' button again and select some additional files to upload. The dataframe values should change only after all the files have finished uploading. The change in the dataframe indicates a re-run """) with st.echo("below"): # Code for above snippet a = st.file_uploader(label='Multiple Reruns', accept_multiple_files=True, key='test2') st.write(a) st.write('Here is a randomly generated dataframe. With every re-run the numbers in the dataframe should change') with st.echo('above'): df = pd.DataFrame(np.random.randint(0, 10, size=(5, 2)), columns=list('AB')) st.write(df)
def show_utilities() -> None: st.header("Utility functions") st.subheader("Show help for an object") with st.echo(): if st.button("Show help"): st.help(pd.DataFrame) st.markdown('-' * 6) st.subheader("Placeholder") with st.echo(): placeholder = st.empty() st.info("This message was created **after** the placeholder!") choice = st.radio("Option", [None, 'markdown', 'dataframe']) if choice == "markdown": placeholder.markdown("This was written at a later point in time :wave:") elif choice == "dataframe": placeholder.dataframe(pd.DataFrame(np.random.randint(0, 100, size=(5, 4)), columns=list('ABCD'))) st.markdown('-' * 6) st.subheader("Get and set options") st.write("""Show and change options for streamlit. Available options can be viewed by entering `streamlit config show` in the terminal. Option key has structure `section.optionName`. """) st.code(""" ... [server] ... # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 ... """) with st.echo(): up_size = st.get_option("server.maxUploadSize") st.write(f"Maximum upload size upload size is `{up_size} MB`") st.write(""" #### Updating client settings Changing config options currently works ony for client options, i.e.: * client.caching * client.displayEnabled """)
def render_datazoom(): with st.echo("below"): data = [ ["14.616", "7.241", "0.896"], ["3.958", "5.701", "0.955"], ["2.768", "8.971", "0.669"], ["9.051", "9.710", "0.171"], ["14.046", "4.182", "0.536"], ["12.295", "1.429", "0.962"], ["4.417", "8.167", "0.113"], ["0.492", "4.771", "0.785"], ["7.632", "2.605", "0.645"], ["14.242", "5.042", "0.368"], ] option_js = { "xAxis": {"type": "value"}, "yAxis": {"type": "value"}, "dataZoom": [{"type": "slider", "start": 10, "end": 60}], "series": [ { "type": "scatter", "itemStyle": {"opacity": 0.8}, "symbolSize": JsCode( """function (val) { return val[2] * 40; }""" ).js_code, "data": data, } ], } st_echarts(options=option_js)
def render_treemap(): with st.echo("below"): options = { "series": [ { "type": "treemap", "data": [ { "name": "nodeA", "value": 10, "children": [ {"name": "nodeAa", "value": 4}, {"name": "nodeAb", "value": 6}, ], }, { "name": "nodeB", "value": 20, "children": [ { "name": "nodeBa", "value": 20, "children": [{"name": "nodeBa1", "value": 20}], } ], }, ], } ] } st_echarts(options)
def run(): st.write( 'If you are seriously considering clicking these boxes (the second one first, for maximum efficiency), you are probably better off reading the [official documentation](https://docs.streamlit.io/en/stable/). It not, [here is the code](https://github.com/gmanchon/streamlit/blob/master/elements/advanced/scraping.py)' ) if st.checkbox('2. Inject the CSS for the privacy policy 😋'): st.write( '<link href="https://www.iubenda.com/assets/privacy_policy-4925cabc28812855d7c0a24b1f0c961c.css" media="screen" rel="stylesheet" type="text/css" />', unsafe_allow_html=True) if st.checkbox('1. Inject the privacy policy 😋'): with st.echo(): import requests from bs4 import BeautifulSoup @st.cache def get_scraping_data(): print('get_scraping_data called') url = 'https://www.iubenda.com/privacy-policy/7967062/legal' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') content = str(soup.select('#wbars_all')) return content content = get_scraping_data() st.write( f'<div id="iubenda_policy" class="iubenda_fixed_policy">{content}</div>', unsafe_allow_html=True)
def run(): with st.echo(): st.code(''' def function sum(a, b): return a + b ''')
def run(): st.write('You\'re welcome 🙌') with st.echo(): if st.button('More 🎈🎈🎈 please!'): st.balloons()
def dataCleanAddFeatures(dat): #Data Cleansing X = dat.loc[(dat.type == 'TRANSFER') | (dat.type == 'CASH_OUT')] #Fraud only occurs in these two cases Y = X['isFraud'] del X['isFraud'] # Eliminate columns shown to be irrelevant for analysis in the EDA X = X.drop(['nameOrig', 'nameDest', 'isFlaggedFraud'], axis=1) with st.echo(): # Binary-encoding of labelled data in 'type' X.loc[X.type == 'TRANSFER', 'type'] = 0 X.loc[X.type == 'CASH_OUT', 'type'] = 1 X.type = X.type.astype(int) # convert dtype('O') to dtype(int) X.loc[(X.oldBalanceDest == 0) & (X.newBalanceDest == 0) & (X.amount != 0), \ ['oldBalanceDest', 'newBalanceDest']] = - 1 X.loc[(X.oldBalanceOrig == 0) & (X.newBalanceOrig == 0) & (X.amount != 0), \ ['oldBalanceOrig', 'newBalanceOrig']] = np.nan #Feature Engineering X['errorBalanceOrig'] = X.newBalanceOrig + X.amount - X.oldBalanceOrig X['errorBalanceDest'] = X.oldBalanceDest + X.amount - X.newBalanceDest return X, Y
def ode(S0, I0, R0): st.subheader("System of ODE") st.markdown(r""" Each susceptible member of population (there are $S$ of them) can be infected by one of $I$ infected member with probability $\beta$ at time $t$ $\frac{dS}{dt} = -\beta \frac{S(t)I(t)}{N}$ The number of new infected members will be determined by above equations, where existing members will be cured or will die with probabilty $\gamma$ $\frac{dI}{dt} = \beta \frac{S(t)I(t)}{N} - \gamma I(t)$ Any intected member (there are $I$ of them) will be cured or will die with probabilty $\gamma$ $\frac{dR}{dt} = \gamma I(t)$ """) st.subheader("Python") with st.echo(): def sir_ode(SIR, t, beta, gamma, N): S, I, R = SIR dS = -beta * ((S * I) / N) dI = beta * ((S * I) / N) - gamma * I dR = gamma * I dydt = [dS, dI, dR] return dydt y0 = [S0, I0, R0] st.markdown(r""" Given * derivatives * initial conditions $S(t)$, $I(t)$ and $R(t)$ can numerically be solved by `odeint` function in `scipy.integrate` module for a given $\beta$ and $\gamma$. Try different $\beta$ and $\gamma$ values using sliders """) _beta = st.slider("Beta", 0., 10., 0.5, 0.01) _gamma = st.slider("Gamma", 0., 1.0, 0.1, 0.01) # st.write(y0) t = np.arange(100) sol = odeint(sir_ode, y0, t, args=(_beta, _gamma, S0 + I0 + R0)) d = pd.DataFrame(sol) d.columns = ['S', 'I', 'R'] d['t'] = t ch = alt.Chart(d).transform_fold(['S', 'I', 'R'], as_=['state', 'population']).mark_line(opacity=0.6, size=3).encode( x='t:Q', y='population:Q', color=alt.Color('state:N', scale=alt.Scale( domain=['S', 'I', 'R'], range=['blue', 'red', 'green'])), tooltip=['state:N', 'population:Q', 't:Q']).interactive() st.altair_chart(ch, use_container_width=True)
def cc_bytes(): st.write( """ # Create a Streamlit Component that uses bytes! Your custom Streamlit Components can now send and receive bytes and byte arrays. As an example, below is the [react-dropzone](https://react-dropzone.js.org/) wrapped into a [Component](https://github.com/streamlit/release-demos/tree/master/0.67/demos/image_uploader). This is just a quick demo, of course, since Streamlit already comes with a file uploader that takes care of all of this for you. Streamlit's uploader is getting a lot of improvements very soon so stay tuned! ----- """ ) parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "image_uploader/build") with st.echo("below"): image_uploader = st.components.v1.components.declare_component("image_uploader", path=build_dir) file = image_uploader() if file: st.image(file, width=300)