diff --git "a/src/Streamlit_Magic_Sheet/components/body.py" "b/src/Streamlit_Magic_Sheet/components/body.py" new file mode 100644--- /dev/null +++ "b/src/Streamlit_Magic_Sheet/components/body.py" @@ -0,0 +1,3671 @@ +#Authot github.com/tushar2704 +############################################################################################################## +#Importing required library +############################################################################################################## +import streamlit as st +import sys +from pathlib import Path +import pandas as pd +script_dir = Path(__file__).resolve().parent +project_root = script_dir.parent +sys.path.append(str(project_root)) +import plotly.express as px +import matplotlib.pyplot as plt +####################################################################################################### +#Importing from SRC +####################################################################################################### +# from src.Streamlit_Magic_Sheet.components.header import * +# from src.Streamlit_Magic_Sheet.components.navigation import * +# from src.Streamlit_Magic_Sheet.components.siderbar import * +# from src.Streamlit_Magic_Sheet.components.metrics import * +# from src.Streamlit_Magic_Sheet.components.charts import * +# from src.Streamlit_Magic_Sheet.components.test import * +from src.Streamlit_Magic_Sheet.components.elements import * +####################################################################################################### + + +############################################################################################################## +#Application Body functions +############################################################################################################## + +def main_body(title=None, header=None, subheader=None, markdown=None, write=None, code=None): + ''' + Displaying Main body conponents + ''' + if title: + st.title(title) + + if header: + st.header(header) + + if subheader: + st.subheader(subheader) + + if markdown: + st.markdown(markdown) + + if write: + st.write(write) + + if code: + st.code(code) + + + +############################################################################################################## +# UI main functions +############################################################################################################## +#Functions + +def magic_sheet_uk(): + #One page main and highlited codes + + first_col, second_col, third_col = st.columns(3, gap="small") + + ####################################### + # first_col + ####################################### + + # Display text + first_col.subheader('Import & Install') + first_col.code(''' + $ pip install streamlit''') + first_col.code(''' + # Import convention + import streamlit as st + ''') + first_col.markdown("`Add widgets to sidebar`") + first_col.code('''# After st.sidebar: + a = st.sidebar.radio(\'Choose:\',[1,2]) + ''') + first_col.markdown("`Magic commands`") + first_col.code(''' + # This_ is some __Markdown__' + a=3 + 'dataframe:', data + ''') + + first_col.markdown("`Command line`") + first_col.code(''' + $ streamlit --help + $ streamlit run your_script.py + $ streamlit hello + $ streamlit config show + $ streamlit cache clear + $ streamlit docs + $ streamlit --version + ''') + + + first_col.write('___________________________') + + # Display data + + first_col.subheader('Display data') + first_col.code(''' + st.dataframe(my_dataframe) + st.table(data.iloc[0:10]) + st.json({'foo':'bar','fu':'ba'}) + st.metric(label="Temp", value="273 K", delta="1.2 K") + ''') + first_col.write('___________________________') + + # Display media + + first_col.subheader('Display media') + first_col.code(''' + st.image('./header.png') + st.audio(data) + st.video(data) + ''') + first_col.write('___________________________') + # Columns + + first_col.subheader('Columns') + first_col.code(''' + col1, col2 = st.columns(2) + col1.write('Column 1') + col2.write('Column 2') + + # Three columns with different widths + col1, col2, col3 = st.columns([3,1,1]) + # col1 is wider + + # Using 'with' notation: + with col1: + st.write('This is column 1') + + ''') + first_col.write('___________________________') + # Tabs + + first_col.subheader('Tabs') + first_col.code(''' + # Insert containers separated into tabs: + tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) + tab1.write("this is tab 1") + tab2.write("this is tab 2") + + # You can also use "with" notation: + with tab1: + st.radio('Select one:', [1, 2]) + ''') + first_col.write('___________________________') + # Control flow + + first_col.subheader('Control flow') + first_col.code(''' + # Stop execution immediately: + st.stop() + # Rerun script immediately: + st.experimental_rerun() + + # Group multiple widgets: + with st.form(key='my_form'): + username = st.text_input('Username') + password = st.text_input('Password') + st.form_submit_button('Login') + ''') + first_col.write('___________________________') + # Personalize apps for users + + first_col.subheader('Personalize apps for users') + first_col.code(''' + # Show different content based on the user's email address. + if st.user.email == 'tushar.inseec@email.com': + display_jane_content() + elif st.user.email == 'tushar.27041994@gmail.com': + display_adam_content() + else: + st.write("Please contact us to get access!") + ''') + first_col.write('___________________________') + + ####################################### + # second_col + ####################################### + + # Display interactive widgets + second_col.subheader('Display text') + second_col.code(''' + st.text('Fixed width text') + st.markdown('_Markdown_') # see #* + st.caption('Balloons. Hundreds of them...') + st.latex(r\'\'\' e^{i\pi} + 1 = 0 \'\'\') + st.write('Most objects') # df, err, func, keras! + st.write(['st', 'is <', 3]) # see * + st.title('My title') + st.header('My header') + st.subheader('My sub') + st.code('for i in range(8): foo()') + + # * optional kwarg unsafe_allow_html = True + + ''') + + second_col.subheader('Display interactive widgets') + second_col.code(''' + st.button('Hit me') + st.data_editor('Edit data', data) + st.checkbox('Check me out') + st.radio('Pick one:', ['nose','ear']) + st.selectbox('Select', [1,2,3]) + st.multiselect('Multiselect', [1,2,3]) + st.slider('Slide me', min_value=0, max_value=10) + st.select_slider('Slide to select', options=[1,'2']) + st.text_input('Enter some text') + st.number_input('Enter a number') + st.text_area('Area for textual entry') + st.date_input('Date input') + st.time_input('Time entry') + st.file_uploader('File uploader') + st.download_button('On the dl', data) + st.camera_input("一二三,茄子!") + st.color_picker('Pick a color') + ''') + + second_col.code(''' + # Use widgets\' returned values in variables + for i in range(int(st.number_input('Num:'))): foo() + if st.sidebar.selectbox('I:',['f']) == 'f': b() + my_slider_val = st.slider('Quinn Mallory', 1, 88) + st.write(slider_val) + ''') + second_col.code(''' + # Disable widgets to remove interactivity: + st.slider('Pick a number', 0, 100, disabled=True) + ''') + second_col.write('___________________________') + # Build chat-based apps + + second_col.subheader('Build chat-based apps') + second_col.code(''' + # Insert a chat message container. + with st.chat_message("user"): + st.write("Hello 👋") + st.line_chart(np.random.randn(30, 3)) + + # Display a chat input widget. + st.chat_input("Say something") + ''') + + second_col.markdown('Learn how to [build chat-based apps](https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps)', unsafe_allow_html=True) + second_col.write('___________________________') + # Mutate data + + second_col.subheader('Mutate data') + second_col.code(''' + # Add rows to a dataframe after + # showing it. + element = st.dataframe(df1) + element.add_rows(df2) + + # Add rows to a chart after + # showing it. + element = st.line_chart(df1) + element.add_rows(df2) + ''') + second_col.write('___________________________') + # Display code + + second_col.subheader('Display code') + second_col.code(''' + st.echo() + with st.echo(): + st.write('Code will be executed and printed') + ''') + second_col.write('___________________________') + # Placeholders, help, and options + + second_col.subheader('Placeholders, help, and options') + second_col.code(''' + # Replace any single element. + element = st.empty() + element.line_chart(...) + element.text_input(...) # Replaces previous. + + # Insert out of order. + elements = st.container() + elements.line_chart(...) + st.write("Hello") + elements.text_input(...) # Appears above "Hello". + + st.help(pandas.DataFrame) + st.get_option(key) + st.set_option(key, value) + st.set_page_config(layout='wide') + st.experimental_show(objects) + st.experimental_get_query_params() + st.experimental_set_query_params(**params) + ''') + second_col.write('___________________________') + ####################################### + # third_col + ####################################### + + + # Connect to data sources + + third_col.subheader('Connect to data sources') + + third_col.code(''' + st.experimental_connection('pets_db', type='sql') + conn = st.experimental_connection('sql') + conn = st.experimental_connection('snowpark') + + class MyConnection(ExperimentalBaseConnection[myconn.MyConnection]): + def _connect(self, **kwargs) -> MyConnection: + return myconn.connect(**self._secrets, **kwargs) + def query(self, query): + return self._instance.query(query) + ''') + + third_col.write('___________________________') + # Optimize performance + + third_col.subheader('Optimize performance') + third_col.write('Cache data objects') + third_col.code(''' + # E.g. Dataframe computation, storing downloaded data, etc. + @st.cache_data + def foo(bar): + # Do something expensive and return data + return data + # Executes foo + d1 = foo(ref1) + # Does not execute foo + # Returns cached item by value, d1 == d2 + d2 = foo(ref1) + # Different arg, so function foo executes + d3 = foo(ref2) + # Clear all cached entries for this function + foo.clear() + # Clear values from *all* in-memory or on-disk cached functions + st.cache_data.clear() + ''') + third_col.write('Cache global resources') + third_col.code(''' + # E.g. TensorFlow session, database connection, etc. + @st.cache_resource + def foo(bar): + # Create and return a non-data object + return session + # Executes foo + s1 = foo(ref1) + # Does not execute foo + # Returns cached item by reference, s1 == s2 + s2 = foo(ref1) + # Different arg, so function foo executes + s3 = foo(ref2) + # Clear all cached entries for this function + foo.clear() + # Clear all global resources from cache + st.cache_resource.clear() + ''') + third_col.write('Deprecated caching') + third_col.code(''' + @st.cache + def foo(bar): + # Do something expensive in here... + return data + # Executes foo + d1 = foo(ref1) + # Does not execute foo + # Returns cached item by reference, d1 == d2 + d2 = foo(ref1) + # Different arg, so function foo executes + d3 = foo(ref2) + ''') + + third_col.write('___________________________') + # Display progress and status + + third_col.subheader('Display progress and status') + third_col.code(''' + # Show a spinner during a process + with st.spinner(text='In progress'): + time.sleep(3) + st.success('Done') + + # Show and update progress bar + bar = st.progress(50) + time.sleep(3) + bar.progress(100) + + st.balloons() + st.snow() + st.toast('Mr Stay-Puft') + st.error('Error message') + st.warning('Warning message') + st.info('Info message') + st.success('Success message') + st.exception(e) + ''') + + third_col.write('___________________________') + return None + + + + +def write_and_magic(): + st.header("Streamlit's `st.write` and Magic Commands") + + # Create a two-column layout + col1, col2 = st.columns([0.5, 0.5], gap="small") + + with col1: + st.subheader("Using st.write") + + st.markdown( + """ + **`st.write`** is a simple way to write content to your Streamlit app. It can be used to display text, DataFrames, or figures. + """ + ) + st.code( + """ + st.write("Did you know I have more then 101 Supreme apps like this?") + st.write(df) + st.write(fig) + """ + ) + + with st.expander("Show `st.write` sample output"): + st.write("Did you know I have more then 101 Supreme apps like this?") + + + with col2: + st.subheader("Magic Commands") + + st.markdown( + """ + **Magic Commands** allow you to display variables or literals in your app automatically. + """ + ) + st.code( + """ + "Hello, World!" # Writes Hello, World! + write="Did you know I have more then 101 Supreme apps like this?" + write + """ + ) + write="Did you know I have more then 101 Supreme apps like this?" + with st.expander("Show `Magic Commands` sample output"): + st.write(write) + + + +def text_elements(): + st.header("Text elements") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + + with col1: + st.subheader("st.markdown") + + st.markdown( + """ + **`st.markdown`** Display string formatted as Markdown. + """ + ) + st.code( + """ + st.markdown("*Streamlit* is **really** ***cool***.") + """ + ) + with st.expander("Show `st.markdown` sample output"): + st.markdown("*Streamlit* is **really** ***cool***.") + + + st.subheader("st.title") + + st.markdown( + """ + **`st.title`** allow you to display text in title formatting. + """ + ) + st.code( + """ + st.title('Streamlit Magic Cheat Sheet') + """ + ) + + with st.expander("Show `st.title` sample output"): + st.title('Streamlit Magic Cheat Sheet') + + st.subheader("st.header") + + st.markdown( + """ + **`st.header`** allow you to display text in header formatting. + """ + ) + st.code( + """ + st.header('www.Tushar-Aggarwal.com') + """ + ) + + with st.expander("Show `st.header`sample output"): + st.header('www.Tushar-Aggarwal.com') + + st.subheader("st.subheader") + + st.markdown( + """ + **`st.subheader`** allow you to display text in subheader formatting. + """ + ) + st.code( + """ + st.subheader('faisons la fête') + """ + ) + + with st.expander("Show `st.subheader`sample output"): + st.subheader('faisons la fête') + + + st.subheader("st.caption") + + st.markdown( + """ + **`st.caption`** allow you to display text in small tex formatting. + """ + ) + st.code( + """ + st.caption('faisons la fête') + """) + with st.expander("Show `st.caption`sample output"): + st.caption('faisons la fête') + + with col2: + st.subheader("st.code") + + st.markdown( + """ + **`st.code`** Display code block with optional syntax highlighting. + """ + ) + st.code( + """ + code = ''' + def hello(): + print("Hello, Streamlit!")''' + st.code(code, language='python') + """ + ) + + with st.expander("Show `st.code` sample output"): + st.write("Hello, Streamlit!") + + st.subheader("st.text") + + st.markdown( + """ + **`st.text`** Displays fixed-width and preformatted text. + """ + ) + st.code( + """ + st.text('I have more Supreme Apps') + """ + ) + + with st.expander("Show `st.text` sample output"): + st.text('I have more Supreme Apps') + + st.subheader("st.latex") + + st.markdown( + """ + **`st.latex`** Displays mathematical expressions formatted as LaTeX. + """ + ) + st.code( + """ + st.latex(r''' + a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} = + \sum_{k=0}^{n-1} ar^k = + a \left(\frac{1-r^{n}}{1-r}\right) + ''') + """ + ) + + with st.expander("Show `st.latex` sample output"): + st.latex(r''' + a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} = + \sum_{k=0}^{n-1} ar^k = + a \left(\frac{1-r^{n}}{1-r}\right) + ''') + + st.subheader("st.divider") + + st.markdown( + """ + **`st.divider`** Displays a horizontal rule(Divider line). + """ + ) + st.code( + """ + st.write("This is some text.") + st.divider() # 👈 Draws a horizontal rule + st.write("This is some other text.") + """ + ) + + with st.expander("Show `st.divider` sample output"): + st.write("This is some text.") + st.divider() # 👈 Draws a horizontal rule + st.write("This is some other text.") + + + +def data_elements(): + st.header("Data elements") + st.markdown( + """Streamlit applications can display data via Charts, DataFrames and Raw form. + + """ + ) + + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + + with col1: + st.subheader("st.dataframe") + + st.markdown( + """ + **`st.dataframe`** Displays interactive dataframe(Table form). + """ + ) + st.code( + """ + st.datafarme(df) + """ + ) + data = { + 'Name': ['Alice', 'Bob', 'Charlie', 'David'], + 'Age': [25, 30, 22, 28], + 'Salary': [50000, 60000, 45000, 55000], + 'Experience': [2, 5, 1, 4] + } + + df = pd.DataFrame(data) + with st.expander("Show `st.dataframe` sample output"): + st.dataframe(df) + + + st.subheader("st.data_editor") + + st.markdown( + """ + **`st.data_editor`** allow you to display data editor widget. + """ + ) + st.code( + """ + st.data_editor(df, num_rows="dynamic") + """ + ) + + + with st.expander("Show `st.data_editor` sample output"): + st.data_editor(df, num_rows="dynamic") + + st.subheader("st.column_config") + + st.markdown( + """ + **`st.column_config`** allow to configure the display and editing behavior of DataFrames and Data editors. + """ + ) + st.code( + """ + st.column_config.NumberColumn("Age", min_value=25) + st.column_config.NumberColumn("Salary", min_value=0, format="$%d") + st.column_config.NumberColumn("Experience", min_value=0) + """ + ) + + + with st.expander("Show `st.column_config` sample output"): + st.column_config.NumberColumn("Age", min_value=25) + st.column_config.NumberColumn("Salary", min_value=0, format="$%d") + st.column_config.NumberColumn("Experience", min_value=0) + st.write(df) + + st.subheader("st.table") + + st.markdown( + """ + **`st.table`** allow you to display a static table. + """ + ) + st.code( + """ + st.table(data) + """ + ) + with st.expander("Show `st.table` sample output"): + st.table(data) + + + with col2: + st.subheader("st.json") + + st.markdown( + """ + **`st.json`** Displays object or string as pretty-printed JSON string. + """ + ) + st.code( + """ + st.json(my_json) + """ + ) + + my_json = { + "name": "John Doe", + "age": 30, + "city": "New York", + "is_student": False, # Corrected to use Python boolean syntax + "grades": [85, 90, 78], + "address": { + "street": "123 Main St", + "city": "Anytown", + "zip_code": "12345" + } + } + + with st.expander("Show `st.json` sample output"): + st.json(my_json) + + st.subheader("Pandas_Profiling") + + st.markdown( + """ + **`st_profile_report`** Displays fixed-width and preformatted text. + """ + ) + st.code( + """ + import pandas_profiling + import streamlit as st + + from streamlit_pandas_profiling import st_profile_report + + df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") + pr = df.profile_report() + + st_profile_report(pr) + """ + ) + with st.expander("Show `Pandas_Profiling` sample output"): + st.markdown("`None`") + + st.subheader("st.metric") + + st.markdown( + """ + **`st.metric`** allow you to display a metric in big bold font, with an optional indicator of how the metric changed. + """ + ) + st.code( + """ + st.metric("Temps", 11:00, 2) + """) + + with st.expander("Show `st.metric` sample output"): + st.metric("Temps", 111, 2) + +def chart_elements(): + st.header("Chart elements") + st.markdown( + """Streamlit applications supports several different charting libraries. + """ + ) + st.markdown(""" + This include Matplotlib, Vega Lite & deck.gl. + """) + st.markdown("""Some native streamlit includes `st.line_chart` and `st.area_chart`.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + with col1: + st.subheader("st.area_chart") + + st.markdown( + """ + **`st.area_chart`** Displays an area chart. + """ + ) + st.code( + """ + st.area_chart(my_df) + """ + ) + data = { + 'Date': pd.date_range(start='2023-01-01', periods=10, freq='D'), + 'Value_A': np.random.randint(1, 100, size=(10,)), + 'Value_B': np.random.randint(1, 100, size=(10,)) + } + + my_df = pd.DataFrame(data) + + # Set the Date column as the index for better visualization in the area chart + my_df.set_index('Date', inplace=True) + + with st.expander("Show `st.area_chart` sample output"): + st.area_chart(my_df) + + + st.subheader("st.bar_chart") + + st.markdown( + """ + **`st.bar_chart`** Displays an bar chart. + """ + ) + st.code( + """ + st.bar_chart(my_df1) + """ + ) + data = { + 'Date': pd.date_range(start='2023-01-01', periods=10, freq='D'), + 'Value_A': np.random.randint(1, 100, size=(10,)), + 'Value_B': np.random.randint(1, 100, size=(10,)) + } + + my_df1 = pd.DataFrame(data) + + # Set the Date column as the index for better visualization in the area chart + my_df1.set_index('Date', inplace=True) + + + + with st.expander("Show `st.bar_chart` sample output"): + st.bar_chart(my_df1) + + st.subheader("st.line_chart") + + st.markdown( + """ + **`st.line_chart`** Displays a line chart. + """ + ) + st.code( + """ + st.line_chart(my_df2) + """ + ) + data = { + 'Date': pd.date_range(start='2023-01-01', periods=10, freq='D'), + 'Value_A': np.random.randint(1, 100, size=(10,)), + 'Value_B': np.random.randint(1, 100, size=(10,)) + } + + my_df2 = pd.DataFrame(data) + + # Set the Date column as the index for better visualization in the line chart + my_df2.set_index('Date', inplace=True) + + with st.expander("Show `st.line_chart` sample output"): + st.line_chart(my_df2) + + st.subheader("st.scatter_chart") + + st.markdown( + """ + **`st.scatter_chart`** Displays a scatter plot. + """ + ) + st.code( + """ + st.scatter_chart(my_df3) + """ + ) + data = { + 'Value_A': np.random.randint(1, 100, size=(100,)), + 'Value_B': np.random.randint(1, 100, size=(100,)) + } + + my_df3 = pd.DataFrame(data) + + # Display the scatter plot using st.plotly_chart + + + with st.expander("Show `st.scatter_chart` sample output"): + st.plotly_chart(px.scatter(my_df3, x='Value_A', y='Value_B')) + + + st.subheader("st.map") + + st.markdown( + """ + **`st.map`** Displays a map with scatter over it. + """ + ) + st.code( + """ + df = pd.DataFrame( + np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], + columns=['lat', 'lon']) + + st.map(df) + """ + ) + with st.expander('Show Map'): + map() + + + st.subheader("st.pyplot") + + st.markdown( + """ + **`st.pyplot`** Displays a matplotlib.pyplot figure. + """ + ) + st.code( + """ + st.pyplot(my_pyplot_figure) + """ + ) + # Create a sample Pyplot figure + x = np.linspace(0, 10, 100) + y = np.sin(x) + + fig, ax = plt.subplots() + ax.plot(x, y) + ax.set_xlabel('X-axis') + ax.set_ylabel('Y-axis') + ax.set_title('Sine Wave') + + + with st.expander("Show `st.pyplot` sample output"): + st.pyplot(fig) + + st.subheader("PyDeck Chart") + + st.markdown( + """ + **`st.pydeck_chart`** Displays a chart with PyDeck Library. + """ + ) + st.code( + """ + import pydeck as pdk + + chart_data = pd.DataFrame( + np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], + columns=['lat', 'lon']) + + st.pydeck_chart(pdk.Deck( + map_style=None, + initial_view_state=pdk.ViewState( + latitude=37.76, + longitude=-122.4, + zoom=11, + pitch=50, + ), + layers=[ + pdk.Layer( + 'HexagonLayer', + data=chart_data, + get_position='[lon, lat]', + radius=200, + elevation_scale=4, + elevation_range=[0, 1000], + pickable=True, + extruded=True, + ), + pdk.Layer( + 'ScatterplotLayer', + data=chart_data, + get_position='[lon, lat]', + get_color='[200, 30, 0, 160]', + get_radius=200, + ), + ], + )) + """ + ) + with st.expander('Show PyDeck chart'): + pydeck() + + + with col2: + + + st.subheader("Altair") + + st.markdown( + """ + **`st.altair_chart`** Displays a chart using the Altair library. + """ + ) + st.code( + """ + chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) + + c = ( + alt.Chart(chart_data) + .mark_circle() + .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"]) + ) + + st.altair_chart(c, use_container_width=True) + """ + ) + with st.expander('Show Altair Chart'): + altair() + + + st.subheader("st.vega_lite_chart") + + st.markdown( + """ + **`st.vega_lite_chart`** Displays a chart using the Vega Lite library. + """ + ) + st.code( + """ + chart_data = pd.DataFrame(np.random.randn(200, 3), columns=["a", "b", "c"]) + + st.vega_lite_chart( + chart_data, + { + "mark": {"type": "circle", "tooltip": True}, + "encoding": { + "x": {"field": "a", "type": "quantitative"}, + "y": {"field": "b", "type": "quantitative"}, + "size": {"field": "c", "type": "quantitative"}, + "color": {"field": "c", "type": "quantitative"}, + }, + }, + ) + """ + ) + with st.expander('Show Vega Lite Chart'): + vega_chart() + + + st.subheader("Plotly Chart") + + st.markdown( + """ + **`st.plotly_chart`** Displays a interactive Plotly Chart. + """ + ) + st.code( + """ + import plotly.figure_factory as ff + + # Add histogram data + x1 = np.random.randn(200) - 2 + x2 = np.random.randn(200) + x3 = np.random.randn(200) + 2 + + # Group data together + hist_data = [x1, x2, x3] + + group_labels = ['Group 1', 'Group 2', 'Group 3'] + + # Create distplot with custom bin_size + fig = ff.create_distplot( + hist_data, group_labels, bin_size=[.1, .25, .5]) + + # Plot! + st.plotly_chart(fig, use_container_width=True) + """ + ) + with st.expander('Show Ploty interactive chart'): + plotly() + + st.subheader("Bokeh Chart") + + st.markdown( + """ + **`st.bokeh_chart`** Displays a interactive Bokeh Chart. + """ + ) + st.code( + """ + from bokeh.plotting import figure + + x = [1, 2, 3, 4, 5] + y = [6, 7, 2, 4, 5] + + p = figure( + title='simple line example', + x_axis_label='x', + y_axis_label='y') + + p.line(x, y, legend_label='Trend', line_width=2) + + st.bokeh_chart(p, use_container_width=True) + """ + ) + with st.expander('Show Bokeh interactive chart'): + bokeh() + + + + + + st.subheader("Graphviz Chart") + + st.markdown( + """ + **`st.graphviz_chart`** Displays a graph using dagre-d3 library Library. + """ + ) + st.code( + """ + import graphviz + + # Create a graphlib graph object + graph = graphviz.Digraph() + graph.edge('run', 'intr') + graph.edge('intr', 'runbl') + graph.edge('runbl', 'run') + graph.edge('run', 'kernel') + graph.edge('kernel', 'zombie') + graph.edge('kernel', 'sleep') + graph.edge('kernel', 'runmem') + graph.edge('sleep', 'swap') + graph.edge('swap', 'runswap') + graph.edge('runswap', 'new') + graph.edge('runswap', 'runmem') + graph.edge('new', 'runmem') + graph.edge('sleep', 'runmem') + + st.graphviz_chart(graph) + """ + ) + with st.expander('Show Graphviz'): + graphviz1() + + + + + + +def input_widgtes(): + st.header("Input Widgets") + st.markdown( + """Streamlit applications allows you to bake interactivity directly with buttons, sliders, text inputs, and more.. + + """ + ) + + # Create a two-column layout + col5, col6 = st.columns(2, gap="small") + + with col5: + st.subheader("st.button") + + + st.markdown( + """ + **`st.button`** Displays a Button Widget. + """ + ) + st.code( + """ + st.button("Reset", type="primary") + if st.button('Say hello'): + st.write('Why hello there') + else: + st.write('Goodbye') + """ + ) + with st.expander('Show Button Example'): + button() + + + + st.subheader("st.download_button") + + + st.markdown( + """ + **`st.download_button`** Displays a download button. + """ + ) + st.code( + """ + text_contents = '''This is some text''' + st.download_button('Download some text', text_contents) + """ + ) + with st.expander('Show Download Text Button Example'): + download() + + st.subheader("st.toggle") + + + st.markdown( + """ + **`st.toggle`** Displays a toggle widget. + """ + ) + st.code( + """ + on = st.toggle('Activate feature') + + if on: + st.write('Feature activated!') + """ + ) + with st.expander('Show Toggle'): + toggle() + + + + st.subheader("st.multiselect") + + + st.markdown( + """ + **`st.multiselect`** Displays a multiselect widget. + """ + ) + st.code( + """ + options = st.multiselect( + 'What are your favorite colors', + ['Green', 'Yellow', 'Red', 'Blue'], + ['Yellow', 'Red']) + + st.write('You selected:', options) + """ + ) + with st.expander('Show Multiselect'): + multiselect() + + + st.subheader("st.slider") + + + st.markdown( + """ + **`st.slider`** Displays a slider widget. + """ + ) + st.code( + """ + values = st.slider( + 'Select a range of values', + 0.0, 100.0, (25.0, 75.0)) + st.write('Values:', values) + """ + ) + with st.expander('Show Slider'): + slider() + + + st.subheader("st.text_input") + + + st.markdown( + """ + **`st.text_input`** Displays a single-line text input widget. + """ + ) + st.code( + """ + title = st.text_input('Movie title', 'Life of Brian') + st.write('The current movie title is', title) + """ + ) + with st.expander('Show Text Input'): + text_input() + + + st.subheader("st.text_area") + + + st.markdown( + """ + **`st.text_area`** Displays a multi-line text input widget. + """ + ) + st.code( + """ + txt = st.text_area( + "Text to analyze", + "It was the best of times, it was the worst of times, it was the age of " + "wisdom, it was the age of foolishness, it was the epoch of belief, it " + "was the epoch of incredulity, it was the season of Light, it was the " + "season of Darkness, it was the spring of hope, it was the winter of " + "despair, (...)", + ) + + st.write(f'You wrote {len(txt)} characters.') + """ + ) + with st.expander('Show Text Area'): + text_area() + + + st.subheader("st.time_input") + + + st.markdown( + """ + **`st.time_input`** Displays a time input widget. + """ + ) + st.code( + """ + import datetime + + + t = st.time_input('Set an alarm for', datetime.time(8, 45)) + st.write('Alarm is set for', t) + + st.write(f'You wrote {len(txt)} characters.') + """ + ) + with st.expander('Show Time input'): + time_input() + + + st.subheader("st.camera_input") + + + st.markdown( + """ + **`st.camera_input`** Displays a widget that returns pictures from the user's webcam. + """ + ) + st.code( + """ + picture = st.camera_input("Take a picture") + + if picture: + st.image(picture) + """ + ) + with st.expander('Show Camer Input'): + camera_input() + + + with col6: + st.subheader("st.link_button") + + + st.markdown( + """ + **`st.link_button`** Displays a link button. + """ + ) + st.code( + """ + st.link_button("Go to Tushar-Aggarwal.com", "https://tushar-aggarwal.com") + """ + ) + with st.expander('Show Link Button Example'): + link() + + + st.subheader("st.checkbox") + + + st.markdown( + """ + **`st.checkbox`** Displays a checkbox widget. + """ + ) + st.code( + """ + agree = st.checkbox('Tushar is great') + + if agree: + st.write('Yes indeed!') + """ + ) + with st.expander('Show Checkbox'): + checkbox() + + st.subheader("st.radio") + + + st.markdown( + """ + **`st.radio`** Displays a radio button widget. + """ + ) + st.code( + """ + genre = st.radio( + "What's your favorite movie genre", + [":rainbow[Comedy]", "***Drama***", "Documentary :movie_camera:"], + captions = ["Laugh out loud.", "Get the popcorn.", "Never stop learning."]) + + if genre == ':rainbow[Comedy]': + st.write('You selected comedy.') + else: + st.write("You didn\'t select comedy.") + """ + ) + with st.expander('Show Radio widget'): + radio() + + st.subheader("st.selectbox") + + + st.markdown( + """ + **`st.selectbox`** Displays a select widget. + """ + ) + st.code( + """ + option = st.selectbox( + "How would you like to be contacted?", + ("Email", "Home phone", "Mobile phone"), + index=None, + placeholder="Select contact method...", + ) + + st.write('You selected:', option) + """ + ) + with st.expander('Show Selectbox widget'): + option() + + + st.subheader("st.select_slider") + + + st.markdown( + """ + **`st.select_slider`** Displays a slider widget to select items from a list. + """ + ) + st.code( + """ + start_color, end_color = st.select_slider( + 'Select a range of color wavelength', + options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'], + value=('red', 'blue')) + st.write('You selected wavelengths between', start_color, 'and', end_color) + """ + ) + with st.expander('Show Select Slider'): + select_slider() + + + + st.subheader("st.number_input") + + + st.markdown( + """ + **`st.number_input`** Displays a numeric input widget. + """ + ) + st.code( + """ + number = st.number_input('Insert a number') + st.write('The current number is ', number) + """ + ) + with st.expander('Show Number Input'): + number_input() + + + st.subheader("st.date_input") + + + st.markdown( + """ + **`st.date_input`** Displays a date input widget. + """ + ) + st.code( + """ + import datetime + + today = datetime.datetime.now() + next_year = today.year + 1 + jan_1 = datetime.date(next_year, 1, 1) + dec_31 = datetime.date(next_year, 12, 31) + + d = st.date_input( + "Select your vacation for next year", + (jan_1, datetime.date(next_year, 1, 7)), + jan_1, + dec_31, + format="MM.DD.YYYY", + ) + d + """ + ) + with st.expander('Show Date Input'): + date_input() + + + + st.subheader("st.file_uploader") + + + st.markdown( + """ + **`st.file_uploader`** Displays a file uploader widget(limited to 200MB). + """ + ) + st.code( + """ + uploaded_files = st.file_uploader("Choose a CSV file", accept_multiple_files=True) + for uploaded_file in uploaded_files: + bytes_data = uploaded_file.read() + st.write("filename:", uploaded_file.name) + st.write(bytes_data) + """ + ) + with st.expander('Show Upload Files'): + file_upload() + + + + st.subheader("st.color_picker") + + + st.markdown( + """ + **`st.color_picker`** Displays a color picker widget. + """ + ) + st.code( + """ + color = st.color_picker('Pick A Color', '#00f900') + st.write('The current color is', color) + """ + ) + with st.expander('Show Color Picker'): + color_picker() + + +def media_elements(): + st.header("Media elements") + st.markdown( + """Streamlit Applications allows easy embeding of images, videos, and audio files directly. + + """ + ) + + # Create a two-column layout + col7, col8 = st.columns(2, gap="small") + + with col7: + st.subheader("st.image") + + + st.markdown( + """ + **`st.image`** Displays an image or list of images. + """ + ) + st.code( + """ + image_url = "https://images.unsplash.com/photo-1561564723-570b270e7c36" + st.image(image_url, caption='Amazing Sunrise', use_column_width=True) + """ + ) + with st.expander('Show Image Example'): + image() + + + + st.subheader("st.video") + + + st.markdown( + """ + **`st.video`** Displays a video player. + """ + ) + st.code( + """ + video_urls = [ + "https://www.youtube.com/watch?v=VIDEO_ID_1", + "https://www.youtube.com/watch?v=VIDEO_ID_2", + "https://www.youtube.com/watch?v=VIDEO_ID_3", + # Add more YouTube video URLs here + ] + + # Select a random video URL + random_video_url = random.choice(video_urls) + + # Display the video + st.video(random_video_url) + """ + ) + with st.expander('Show Video Example'): + video() + + with col8: + st.subheader("st.audio") + + + st.markdown( + """ + **`st.audio`** Displays an audio player. + """ + ) + st.code( + """ + def get_random_fma_track(): + base_url = "https://files.freemusicarchive.org/" + endpoint = "random/track" + response = requests.get(f"{base_url}{endpoint}") + if response.status_code == 200: + track_url = response.url + return track_url + return None + + # Get a random FMA track URL + random_audio_url = get_random_fma_track() + + # Display the audio player + if random_audio_url: + st.audio(random_audio_url, format="audio/mp3") + else: + st.write("Failed to fetch a random audio track. Please try again later.") + """ + ) + with st.expander('Show Audio Example'): + audio() + +def layouts_and_containers(): + st.header("Layouts and Containers") + st.markdown( + """Streamlit Applications allows different layout built in and with Custom CSS, you can make yours too. + + """ + ) + + + # Create a two-column layout + col9, col10 = st.columns(2, gap="small") + + + + with col9: + st.subheader("st.sidebar") + + + st.markdown( + """ + **`st.sidebar`** Add widgets to sidebar(left panel). + """ + ) + st.markdown( + """ + Elements can be passed to **`st.sidebar`** using object notation and `with` notation. + """ + ) + st.code( + """ + import streamlit as st + + # Using object notation + add_selectbox = st.sidebar.selectbox( + "How would you like to be contacted?", + ("Email", "Home phone", "Mobile phone") + ) + + # Using "with" notation + with st.sidebar: + add_radio = st.radio( + "Choose a shipping method", + ("Standard (5-15 days)", "Express (2-5 days)") + ) + """ + ) + with st.expander('Show Sidebar Example'): + sidebar() + st.write("Scroll down on left panel to see effect of above `code`") + + + st.subheader("st.tabs") + + + st.markdown( + """ + **`st.tabs`** Inserts containers separated into tabs. + """ + ) + st.markdown( + """ + In other words **`st.tabs`** supports easy navigation with seprate areas of containers. + """ + ) + st.code( + """ + tab1, tab2, tab3 = st.tabs(["Cat", "Dog", "Owl"]) + + with tab1: + st.header("A cat") + st.image("https://static.streamlit.io/examples/cat.jpg", width=200) + + with tab2: + st.header("A dog") + st.image("https://static.streamlit.io/examples/dog.jpg", width=200) + + with tab3: + st.header("An owl") + st.image("https://static.streamlit.io/examples/owl.jpg", width=200) + """ + ) + with st.expander('Show Tab Example'): + tab() + + + st.subheader("st.empty") + + + st.markdown( + """ + **`st.empty`** Inserts a single-element container. + """ + ) + st.markdown( + """ + In other words **`st.tabs`** hold a single element, remove elements at any point, or replace several elements at once. + """ + ) + st.code( + """ + placeholder = st.empty() + + # Replace the placeholder with some text: + placeholder.text("Hello") + + # Replace the text with a chart: + placeholder.line_chart({"data": [1, 5, 2, 6]}) + + # Replace the chart with several elements: + with placeholder.container(): + st.write("This is one element") + st.write("This is another") + + # Clear all those elements: + placeholder.empty() + """ + ) + with st.expander('Show Empty Example'): + empty() + + + with col10: + st.subheader("st.columns") + + + st.markdown( + """ + **`st.columns`** Inserts a containers laid out as side-by-side columns. + """ + ) + + st.markdown("""Inserts a number of multi-element containers laid out side-by-side and returns a list of container objects. + """) + st.code( + """ + col1, col2, col3 = st.columns(3) + + with col1: + st.header("A cat") + st.image("https://static.streamlit.io/examples/cat.jpg") + + with col2: + st.header("A dog") + st.image("https://static.streamlit.io/examples/dog.jpg") + + with col3: + st.header("An owl") + st.image("https://static.streamlit.io/examples/owl.jpg") + """ + ) + with st.expander('Show Columns Example'): + columns() + + + + + st.subheader("st.expander") + + + st.markdown( + """ + **`st.expander`** Insertsa multi-element container that can be expanded/collapsed. + """ + ) + + st.markdown("""**`st.expander`** can hold functions, ojects and other components. + """) + st.code( + """ + chart = st.bar_chart({"data": [1, 5, 2, 6, 2, 1]}) + + with st.expander("Bar Chart"): + chart + st.write("The chart above shows some randon numbers. st.expander help to hide elements and show ony when expanded") + """ + ) + with st.expander('Show Expander Example'): + expander() + + + + st.subheader("st.container") + + + st.markdown( + """ + **`st.container`** Inserts a a multi-element container. + """ + ) + + st.markdown("""**`st.expander`** make invisable container to store some components together. + """) + st.code( + """ + with st.container(): + st.write("This is inside the container") + + # You can call any Streamlit command, including custom components: + st.bar_chart(np.random.randn(50, 3)) + + st.write("This is outside the container") + """ + ) + with st.expander('Show Container Example'): + container() + +def chat_elements(): + st.header("Chat elements") + st.markdown( + """Currently popular, Chat elements allows to buils conversations applications. + + """ + ) + st.markdown(""" + **`st.chat_message`** inserts a chat message container into the app so you can display messages from the user or the app.(Input container for Chats application) + """) + st.markdown("""Note **`st.chat_input`** allows to enter `message` that is (Input element for text for Chats application)""") + st.markdown("""Where as **`st.status`** display output from long-running processes and external API calls""") + + # Create a two-column layout + col11, col12 = st.columns(2, gap="small") + + with col11: + st.subheader("st.chat_message") + + + st.markdown( + """ + **`st.chat_message`** Inserts a chat message container. + """ + ) + + + st.code( + """ + with st.chat_message("user"): + st.write("🤖 Hello 👋") + st.write("How may I help you today?") + """ + ) + with st.expander('Show Chat_mesage container Example'): + chat_message() + + with col12: + st.subheader("st.chat_input") + + + st.markdown( + """ + **`st.chat_input`** Displays a chat input widget(input container for message/prompt). + """ + ) + + st.markdown("Currently, `st.chat_input()` can't be used inside an `st.expander`, `st.form`, `st.tabs`, `st.columns`, or `st.sidebar`") + st.code( + """ + prompt = st.chat_input("How may I help you today?") + if prompt: + st.write(f"User has sent the following prompt: {prompt}") + """ + ) + st.write("st.chat_input Example") + chat_input() + +def status_elements(): + st.header("Status elements") + st.markdown( + """Streamlit applications has status elements to display progress bars, status messages (like warnings), and celebratory balloons. + + """ + ) + # Create a two-column layout + col13, col14 = st.columns(2, gap="small") + + + with col13: + + st.subheader("st.progress") + + + st.markdown( + """ + **`st.progress`** Inserts a simple progress bar. + """ + ) + + + st.code( + """ + progress_text = "Operation in progress. Please wait." + my_bar = st.progress(0, text=progress_text) + + for percent_complete in range(100): + time.sleep(0.01) + my_bar.progress(percent_complete + 1, text=progress_text) + time.sleep(1) + my_bar.empty() + + st.button("Rerun") + """ + ) + with st.expander('Show Progress bar Example'): + progress() + + + + + st.subheader("st.status") + + + st.markdown( + """ + **`st.status`** Inserts a status container to display output from long-running tasks.(best for Data ingestion like tasks) + """ + ) + + + st.code( + """ + with st.status("Downloading data..."): + st.write("Searching for data...") + time.sleep(2) + st.write("Found URL.") + time.sleep(1) + st.write("Downloading data...") + time.sleep(1) + + st.button('Rerun') + """ + ) + + status() + + + st.subheader("st.success") + + + st.markdown( + """ + **`st.success`** Displays a success message. + """ + ) + + + st.code( + """ + st.success('Data processed!', icon="✅") + """ + ) + + with st.expander("Show Success Example"): + success() + + + + st.subheader("st.exception") + + + st.markdown( + """ + **`st.exception`** Displays a exception message. + """ + ) + + + st.code( + """ + e = RuntimeError('This is an exception of type RuntimeError') + st.exception(e) + """ + ) + + with st.expander("Show Exception Example"): + exception() + + + with col14: + + st.subheader("st.spinner") + + + st.markdown( + """ + **`st.spinner`** Displays a temporary message while executing a block of code. + """ + ) + + + st.code( + """ + with st.spinner('Wait for it...'): + time.sleep(5) + st.success('Done!') + """ + ) + with st.expander('Show Spinner Example'): + spinner() + + + + st.subheader("st.toast") + + + st.markdown( + """ + **`st.toast`** Displays a short message, known as a notification "toast" 🍞(Position is bottom-right). + """ + ) + + + st.code( + """ + st.toast('Your prompt was send for processing!', icon='😍') + """ + ) + with st.expander('Show Toast Example'): + st.write("Look out for toast at bottom right") + st.write(toast()) + + + + st.subheader("st.error") + + + st.markdown( + """ + **`st.error`** Inserts an error message. + """ + ) + + + st.code( + """ + st.error('There is an error', icon="🚨") + """ + ) + + with st.expander('Show Error Example'): + error() + + + + st.subheader("st.warning") + + + st.markdown( + """ + **`st.warning`** Inserts an warning message. + """ + ) + + + st.code( + """ + st.warning('This task will utilize multiple resources, expect time delay', icon="⚠️") + """ + ) + + with st.expander('Show Warning Example'): + warning() + + + + + st.subheader("st.info") + + + st.markdown( + """ + **`st.info`** Inserts an informational message. + """ + ) + + + st.code( + """ + st.info('This task will utilize paid API', icon="💵") + """ + ) + + with st.expander('Show Info Example'): + info() + + + st.subheader("st.balloons") + + + st.markdown( + """ + **`st.balloons`** Displays celebratory balloons. + """ + ) + + + st.code( + """ + st.balloons() + """ + ) + + st.subheader("st.snow") + + + st.markdown( + """ + **`st.snow`** Displays celebratory snowfall. + """ + ) + + + st.code( + """ + st.st.snow() + """ + ) + + + +def control_flow(): + st.header("Control Flow") + st.markdown( + """Change execution allows to handle control flow in your applications(By defaul). + + """ + ) + + st.markdown( + """Group multiple widgets - allows the widgets is filled before rerunning the script to provide better UI experience. + + """ + ) + # Create a two-column layout + col15, col16 = st.columns(2, gap="small") + + + + with col15: + st.subheader("st.stop") + + + st.markdown( + """ + **`st.stop`** Stops Streamlit py script execution immediately. + """ + ) + + + st.code( + """ + name = st.text_input('Name') + if not name: + st.warning('Please input a name.') + st.stop() + st.success('Thank you for inputting a name.') + """ + ) + + + + st.subheader("st.form") + + + st.markdown( + """ + **`st.form`** Creates a form that batches elements together with a "Submit" button. + """ + ) + + + st.code( + """ + form = st.form("Try Form") + form.slider("Inside the form") + + st.slider("Outside the form") + + # Now add a submit button to the form: + form.form_submit_button("Submit") + """ + ) + + with st.expander("Show Form submit Example"): + form() + + + + with col16: + st.subheader("st.rerun") + + + st.markdown( + """ + **`st.rerun`** Reruns Streamlit py script execution immediately. + """ + ) + + + st.code( + """ + pif "value" not in st.session_state: + st.session_state.value = "Title" + + ##### Option using st.rerun ##### + st.header(st.session_state.value) + + if st.button("Foo"): + st.session_state.value = "Foo" + st.rerun() + + """ + ) + + + st.subheader("st.form_submit_button") + + + st.markdown( + """ + **`st.form_submit_button`** Creates a form submit button. + """ + ) + + st.markdown("When this button is clicked, all widget values inside the form will be sent to Streamlit in a batch") + + + + +def utilities(): + st.header("Utilities") + st.markdown( + """Streamlit Applications can have utilites like Placeholders, help, and options. + + """ + ) + + + # Create a two-column layout + col17, col18 = st.columns(2, gap="small") + + with col17: + + + st.subheader("st.set_page_config") + + + st.markdown( + """ + **`st.set_page_config`** Helps to Configures the default settings of the page. + """ + ) + + + st.code( + """ + st.set_page_config( + page_title="Streamlit Magic Sheets", + page_icon="🧊", + layout="wide", + initial_sidebar_state="expanded", + menu_items={ + 'Get Help': 'https://www.tushar-aggarwal.com/', + 'Report a bug': "https://github.com/tushar2704/Streamlit-Magic-Sheet/issues", + 'About': "# This is a Streamlit Magic Sheets. This is an *extremely* cool application!" + } + ) + """ + ) + + + st.subheader("st.help") + + + st.markdown( + """ + **`st.help`** Displays help and other information for a given object. + """ + ) + + + st.code( + """ + st.help(st.write) + """ + ) + + with st.expander("Show Help example"): + help() + + + with col18: + + + st.subheader("st.echo") + + + st.markdown( + """ + **`st.echo`** Creates draws some code on the app, then execute it. + """ + ) + + + st.code( + """ + with st.echo(): + st.write('Tushar is the best') + """ + ) + + with st.expander("Show Echo Example"): + echo() + + + + + + + +def mutate_charts(): + st.header("Mutate Charts") + st.markdown( + """Allows to modify chart or dataframe as the app runs. + + """ + ) + st.markdown(""" + Using `st.empty` to replace a single element. + """) + st.markdown("""Using `st.container` or `st.columns` to replace multiple elements.""") + st.markdown("""Using `add_rows` to append data to specific types of elements""") + + + + + + + # Create a two-column layout + col19, col20 = st.columns(2, gap="small") + + + with col19: + st.subheader("element.add_rows") + + + st.markdown( + """ + **`element.add_rows`** Add to existing element live. + """ + ) + + + st.code( + """ + df1 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) + + my_table = st.table(df1) + + df2 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) + + my_table.add_rows(df2) + """ + ) + + + + + + + with col20: + + + + with st.expander("Show Add rows example"): + add_rows() + +def state_management(): + st.header("State Management") + st.markdown( + """With Session State, sharing variables between reruns, for each user session is possible. + + """ + ) + st.markdown(""" + Also has ability to manipulate state using Callbacks. + """) + + + # Create a two-column layout + col21, col22 = st.columns(2, gap="small") + + + with col21: + st.subheader("Initialize values in Session State") + st.markdown('The Session State API follows a field-based API, which is very similar to Python dictionaries:') + st.code( + """ + # Initialization + if 'key' not in st.session_state: + st.session_state['key'] = 'value' + + # Session State also supports attribute based syntax + if 'key' not in st.session_state: + st.session_state.key = 'value' + """ + ) + + + + + st.markdown('Update an item in Session State by assigning it a value:') + st.code( + """ + st.session_state.key = 'value2' # Attribute API + st.session_state['key'] = 'value2' # Dictionary like API + """ + ) + + + + st.subheader('Delete items') + st.markdown('Delete items in Session State using the syntax to delete items in any Python dictionary:') + st.code( + """ + # Delete a single key-value pair + del st.session_state[key] + + # Delete all the items in Session state + for key in st.session_state.keys(): + del st.session_state[key] + """ + ) + + + + st.subheader('Use Callbacks to update Session State') + st.markdown('A callback is a python function which gets called when an input widget changes.') + st.markdown('**Order of execution**: When updating Session state in response to events, a callback function gets executed first, and then the app is executed from top to bottom.') + st.markdown('Callbacks can be used with widgets using the parameters `on_change` (or `on_click`), `args`, and `kwargs`:') + st.markdown('**on_change** or **on_click** - The function name to be used as a callback') + st.markdown('**args** (tuple) - List of arguments to be passed to the callback function') + st.markdown('**kwargs** (dict) - Named arguments to be passed to the callback function') + st.code( + """ + # Delete a single key-value pair + del st.session_state[key] + + # Delete all the items in Session state + for key in st.session_state.keys(): + del st.session_state[key] + """ + ) + + + + st.subheader('Serializable Session State') + st.markdown('Serialization refers to the process of converting an object or data structure into a format that can be persisted and shared, and allowing you to recover the data’s original structure. Python’s built-in pickle module serializes Python objects to a byte stream ("pickling") and deserializes the stream into an object ("unpickling").') + st.markdown('By default, Streamlit’s Session State allows you to persist any Python object for the duration of the session, irrespective of the object’s pickle-serializability. This property lets you store Python primitives such as integers, floating-point numbers, complex numbers and booleans, dataframes, and even lambdas returned by functions. However, some execution environments may require serializing all data in Session State, so it may be useful to detect incompatibility during development, or when the execution environment will stop supporting it in the future.') + st.markdown('To that end, Streamlit provides a runner.enforceSerializableSessionState configuration option that, when set to true, only allows pickle-serializable objects in Session State. To enable the option, either create a global or project config file with the following or use it as a command-line flag:') + + st.code( + """ + # .streamlit/config.toml + [runner] + enforceSerializableSessionState = true + """ + ) + + st.markdown('By "pickle-serializable", we mean calling pickle.dumps(obj) should not raise a PicklingError exception. When the config option is enabled, adding unserializable data to session state should result in an exception. E.g.,') + st.code( + """ + import streamlit as st + + def unserializable_data(): + return lambda x: x + + #👇 results in an exception when enforceSerializableSessionState is on + st.session_state.unserializable = unserializable_data() + """ + ) + + with col22: + st.subheader("Reads and updates") + st.markdown('Read the value of an item in Session State and display it by passing to `st.write` ') + st.code( + """ # Read + st.write(st.session_state.key) + + # Outputs: value + """ + ) + + + st.markdown('Curious about what is in Session State? Use `st.write` or magic:') + st.code( + """ + st.write(st.session_state) + + # With magic: + st.session_state + """ + ) + + st.markdown('Streamlit throws a handy exception if an uninitialized variable is accessed:') + st.code( + """ + st.write(st.session_state['value']) + """ + ) + + + + + + st.subheader('Session State and Widget State association') + st.markdown('Every widget with a key is automatically added to Session State:') + st.code( + """ + st.text_input("Your name", key="name") + + # This exists now: + st.session_state.name + """ + ) + + + st.subheader('Forms and Callbacks') + st.markdown('Widgets inside a form can have their values be accessed and set via the Session State API. `st.form_submit_button` can have a callback associated with it. The callback gets executed upon clicking on the submit button. For example:') + st.code( + """ + def form_callback(): + st.write(st.session_state.my_slider) + st.write(st.session_state.my_checkbox) + + with st.form(key='my_form'): + slider_input = st.slider('My slider', 0, 10, 5, key='my_slider') + checkbox_input = st.checkbox('Yes or No', key='my_checkbox') + submit_button = st.form_submit_button(label='Submit', on_click=form_callback) + """ + ) + + + st.subheader('Caveats and limitations') + st.markdown('Only the st.form_submit_button has a callback in forms. Other widgets inside a form are not allowed to have callbacks.') + st.markdown('on_change and on_click events are only supported on input type widgets.') + st.markdown('Modifying the value of a widget via the Session state API, after instantiating it, is not allowed and will raise a StreamlitAPIException. For example:') + st.code( + """ + slider = st.slider( + label='My Slider', min_value=1, + max_value=10, value=5, key='my_slider') + + st.session_state.my_slider = 7 + + # Throws an exception! + """ + ) + + st.markdown('Setting the widget state via the Session State API and using the value parameter in the widget declaration is not recommended, and will throw a warning on the first run. For example:') + st.code( + """ + st.session_state.my_slider = 7 + + slider = st.slider( + label='Choose a Value', min_value=1, + max_value=10, value=5, key='my_slider') + + """) + + + st.markdown('Setting the state of button-like widgets: st.button, st.download_button, and st.file_uploader via the Session State API is not allowed. Such type of widgets are by default False and have ephemeral True states which are only valid for a single run. For example:') + st.code( + """ + if 'my_button' not in st.session_state: + st.session_state.my_button = True + + st.button('My button', key='my_button') + + # Throws an exception! + + """) + +def performance(): + st.header("Performance") + st.markdown( + """Streamlit provides cache primitives for data and global resources. They allow your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. + + """ + ) + + + # Create a two-column layout + col23, col24 = st.columns(2, gap="small") + + + with col23: + st.subheader("st.cache_data") + + + st.markdown( + """ + **`st.cache_data`** Decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).. + """ + ) + st.markdown('Cached objects are stored in "pickled" form, which means that the return value of a cached function must be pickleable. Each caller of the cached function gets its own copy of the cached data') + st.markdown('''You can clear a function's cache with `func.clear()` or clear the entire cache with `st.cache_data.clear()`.''') + st.code( + """ + @st.cache_data + def fetch_and_clean_data(url): + # Fetch data from URL here, and then clean it up. + return data + + d1 = fetch_and_clean_data(DATA_URL_1) + # Actually executes the function, since this is the first time it was + # encountered. + + d2 = fetch_and_clean_data(DATA_URL_1) + # Does not execute the function. Instead, returns its previously computed + # value. This means that now the data in d1 is the same as in d2. + + d3 = fetch_and_clean_data(DATA_URL_2) + # This is a different URL, so the function executes. + """ + ) + + + st.markdown('''To set the `persist` parameter, use this command as follows:''') + st.code( + """ + import streamlit as st + + @st.cache_data(persist="disk") + def fetch_and_clean_data(url): + # Fetch data from URL here, and then clean it up. + return data + """ + ) + + st.markdown('''By default, all parameters to a cached function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable:''') + st.code( + """ + import streamlit as st + + @st.cache_data + def fetch_and_clean_data(_db_connection, num_rows): + # Fetch data from _db_connection here, and then clean it up. + return data + + connection = make_database_connection() + d1 = fetch_and_clean_data(connection, num_rows=10) + # Actually executes the function, since this is the first time it was + # encountered. + + another_connection = make_database_connection() + d2 = fetch_and_clean_data(another_connection, num_rows=10) + # Does not execute the function. Instead, returns its previously computed + # value - even though the _database_connection parameter was different + # in both calls. + """ + ) + + + st.markdown('''A cached function's cache can be procedurally cleared:''') + st.code( + """ + import streamlit as st + + @st.cache_data + def fetch_and_clean_data(_db_connection, num_rows): + # Fetch data from _db_connection here, and then clean it up. + return data + + fetch_and_clean_data.clear() + # Clear all cached entries for this function. + """ + ) + + + + st.markdown('''To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. datetime.datetime) to a hash function (lambda dt: dt.isoformat()) like this:''') + st.code( + """ + import streamlit as st + import datetime + + @st.cache_data(hash_funcs={datetime.datetime: lambda dt: dt.isoformat()}) + def convert_to_utc(dt: datetime.datetime): + return dt.astimezone(datetime.timezone.utc) + """ + ) + + + + + st.markdown('''Alternatively, you can map the type's fully-qualified name (e.g. "datetime.datetime") to the hash function instead:''') + st.code( + """ + import streamlit as st + import datetime + + @st.cache_data(hash_funcs={"datetime.datetime": lambda dt: dt.isoformat()}) + def convert_to_utc(dt: datetime.datetime): + return dt.astimezone(datetime.timezone.utc) + """ + ) + + + st.subheader("st.cache_data.clear") + + + st.markdown( + """ + Clear all in-memory and on-disk data caches. + """ + ) + + st.code( + """ + import streamlit as st + + @st.cache_data + def square(x): + return x**2 + + @st.cache_data + def cube(x): + return x**3 + + if st.button("Clear All"): + # Clear values from *all* all in-memory and on-disk data caches: + # i.e. clear values from both square and cube + st.cache_data.clear() + """ + ) + + + st.subheader("Using Streamlit commands in cached functions") + + + st.markdown( + """ + Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: + """ + ) + + st.code( + """ + @st.cache_data + def get_api_data(): + data = api.get(...) + st.success("Fetched data from API!") # 👈 Show a success message + return data + """ + ) + + + st.subheader("Input widgets") + + + st.markdown( + """ + You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: + """ + ) + + st.code( + """ + @st.cache_data(experimental_allow_widgets=True) # 👈 Set the parameter + def get_data(): + num_rows = st.slider("Number of rows to get") # 👈 Add a slider + data = api.get(..., num_rows) + return data + """ + ) + + + with col24: + st.subheader("st.cache_resource") + + + st.markdown( + """ + You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: + """ + ) + st.markdown('''Decorator to cache functions that return global resources (e.g. database connections, ML models). ''') + st.markdown('''Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead.''') + st.markdown('''You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). ''') + + st.code( + """ + import streamlit as st + + @st.cache_resource + def get_database_session(url): + # Create a database session object that points to the URL. + return session + + s1 = get_database_session(SESSION_URL_1) + # Actually executes the function, since this is the first time it was + # encountered. + + s2 = get_database_session(SESSION_URL_1) + # Does not execute the function. Instead, returns its previously computed + # value. This means that now the connection object in s1 is the same as in s2. + + s3 = get_database_session(SESSION_URL_2) + # This is a different URL, so the function executes. + """ + ) + + st.markdown("""By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable:""") + + st.code( + """ + import streamlit as st + + @st.cache_resource + def get_database_session(_sessionmaker, url): + # Create a database connection object that points to the URL. + return connection + + s1 = get_database_session(create_sessionmaker(), DATA_URL_1) + # Actually executes the function, since this is the first time it was + # encountered. + + s2 = get_database_session(create_sessionmaker(), DATA_URL_1) + # Does not execute the function. Instead, returns its previously computed + # value - even though the _sessionmaker parameter was different + # in both calls. + """ + ) + + + st.markdown("""A cache_resource function's cache can be procedurally cleared:""") + + st.code( + """ + import streamlit as st + + @st.cache_resource + def get_database_session(_sessionmaker, url): + # Create a database connection object that points to the URL. + return connection + + get_database_session.clear() + # Clear all cached entries for this function. + """ + ) + + + + + st.markdown("""To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this:""") + + st.code( + """ + import streamlit as st + from pydantic import BaseModel + + class Person(BaseModel): + name: str + + @st.cache_resource(hash_funcs={Person: str}) + def get_person_name(person: Person): + return person.name + """ + ) + + + + st.markdown("""Alternatively, you can map the type's fully-qualified name (e.g. "__main__.Person") to the hash function instead:""") + + st.code( + """ + import streamlit as st + from pydantic import BaseModel + + class Person(BaseModel): + name: str + + @st.cache_resource(hash_funcs={"__main__.Person": str}) + def get_person_name(person: Person): + return person.name + """ + ) + + + + + st.subheader('st.cache_resource.clear') + st.markdown("""In the example below, pressing the "Clear All" button will clear all cache_resource caches. i.e. Clears cached global resources from all functions decorated with @st.cache_resource.""") + + st.code( + """ + import streamlit as st + from transformers import BertModel + + @st.cache_resource + def get_database_session(url): + # Create a database session object that points to the URL. + return session + + @st.cache_resource + def get_model(model_type): + # Create a model of the specified type. + return BertModel.from_pretrained(model_type) + + if st.button("Clear All"): + # Clears all st.cache_resource caches: + st.cache_resource.clear() + """ + ) + + + st.subheader('Using Streamlit commands in cached functions') + st.markdown("""Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this:""") + + st.code( + """ + from transformers import pipeline + + @st.cache_resource + def load_model(): + model = pipeline("sentiment-analysis") + st.success("Loaded NLP model from Hugging Face!") # 👈 Show a success message + return model + """ + ) + + + st.markdown("""As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators.""") + + st.code( + """ + @st.cache_resource + def load_model(): + st.header("Data analysis") + model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) + st.success("Loaded model!") + st.write("Turning on evaluation mode...") + model.eval() + st.write("Here's the model:") + return model + """ + ) + + st.subheader('Input widgets') + st.markdown("""You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter:""") + + st.code( + """ + @st.cache_data(experimental_allow_widgets=True) # 👈 Set the parameter + def load_model(): + pretrained = st.checkbox("Use pre-trained model:") # 👈 Add a checkbox + model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT, pretrained=pretrained) + return model + """ + ) + + + + + + + + +def personalization(): + st.header("Personalization") + st.subheader( + """st.experimental_user. + + """ + ) + st.markdown(""" + `st.experimental_user` is a Streamlit command that returns information about the logged-in user on Streamlit Community Cloud. It allows developers to personalize apps for the user viewing the app. In a private Streamlit Community Cloud app, it returns a dictionary with the viewer's email. This value of this field is empty in a public Streamlit Community Cloud app to prevent leaking user emails to developers. + """) + + + + + st.subheader( + """Allowed fields. + + """ + ) + st.markdown(""" + The st.experimental_user command returns a dictionary with only one field: email. + """) + + + st.code( + """ + # Display the contents of the dictionary + st.write(st.experimental_user) + """ + ) + + + st.markdown(""" + The above displays a dict with one field and value. The field is always email: + """) + + + st.code( + """ + { + "email": "value" + } + """ + ) + + st.markdown(""" + You can check if a field exists in st.experimental_user: + """) + + + st.code( + """ + # Returns True if the field exists + "email" in st.experimental_user + + # Returns False if the field does not exist + "name" in st.experimental_user + """ + ) + + + + st.subheader( + """Updates and modifications + + """ + ) + st.markdown(""" + + Keys and values for st.experimental_user cannot be updated or modified. Streamlit throws a handy StreamlitAPIException exception if you try to update them: + """) + + + st.code( + """ + st.experimental_user.name = None + # Throws an exception! + + st.experimental_user.email = "hello" + # Throws an exception! + """ + ) + + + + st.subheader( + """Context-dependent behavior + + """ + ) + st.markdown(""" + + The value of st.experimental_user.email is context-dependent. It returns a value depending on where the app is running. The private or public app can be running on Streamlit Community Cloud, locally, or on a 3rd party cloud provider. Let's look at the different scenarios. + """) + + + + + + st.subheader( + """Public app on Streamlit Community Cloud + + """ + ) + st.markdown(""" + + Currently, st.experimental_user.email returns information about the logged-in user of private apps on Streamlit Community Cloud. If used in a public app, it returns None. For example: + """) + + + st.code( + """ + st.experimental_user.email + # Returns: None + """ + ) + + + st.subheader( + """Local development + + """ + ) + st.markdown(""" + + When developing locally, st.experimental_user.email returns test@example.com. We don't return None to make it easier to locally test this functionality. For example: + """) + + + st.code( + """ + st.experimental_user.email + # Returns: test@example.com + """ + ) + + + st.subheader( + """App deployed on a 3rd party cloud provider + + """ + ) + st.markdown(""" + + When deploying an app on a 3rd party cloud provider (e.g. Amazon EC2, Heroku, etc), st.experimental_user.email behaves the same as during local development. For example: + """) + + + st.code( + """ + st.experimental_user.email # On a 3rd party cloud provider + # Returns: test@example.com + """ + ) + + +def connections_and_databases(): + st.header("Connection and Databases") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def app_menu(): + st.header("App Menu") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def button_behavior_and_examples(): + st.header("Button Behavior and Examples") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def caching(): + st.header("Caching") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def command_line_options(): + st.header("Command Line Options") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def configuration(): + st.header("Configuration") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def theming(): + st.header("Theming") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def connecting_to_data(): + st.header("Connecting to Data") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def dataframes(): + st.header("DataFrames") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def forms(): + st.header("Forms") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def add_statefulness_to_apps(): + st.header("Add Statefulness To Apps") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def widget_behavior(): + st.header("Widget Behavior") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def working_with_timezones(): + st.header("Working with Timezones") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def static_file_serving(): + st.header("Static File Serving") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def https_support(): + st.header("HTTPS Support") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def secrects_management(): + st.header("Secrects Management") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def security_reminders(): + st.header("Security Reminders") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + +def connect_to_data_sources(): + st.header("Connect To Data Sources") + st.markdown( + """You can start streamlit applications with `st.title` to set the app's title(Text larger than Header size text). After that, there are 2 heading levels(lower sizes) you can use: `st.header` and `st.subheader`. + + """ + ) + st.markdown(""" + Any text can be entered with `st.text`, and Markdown with `st.markdown`(Uses Markdown language for text output). + """) + st.markdown("""Note `st.write` is versatile , it can accepts multiple arguments, and multiple data types.""") + + # Create a two-column layout + col1, col2 = st.columns(2, gap="small") + + +func_list=[write_and_magic,text_elements, data_elements, chart_elements, + input_widgtes, media_elements, layouts_and_containers, + chat_elements, status_elements, control_flow, + utilities, mutate_charts, state_management, + performance, personalization, connections_and_databases, + app_menu, button_behavior_and_examples, caching, + command_line_options, configuration, theming, connecting_to_data, + dataframes, forms, add_statefulness_to_apps, widget_behavior, + working_with_timezones, static_file_serving, + https_support, secrects_management, security_reminders, + connect_to_data_sources] + +func_list=['write_and_magic','text_elements', 'data_elements', 'chart_elements', + 'input_widgtes', 'media_elements', 'layouts_and_containers', + 'chat_elements', 'status_elements', 'control_flow', + 'utilities', 'mutate_charts', 'state_management', + 'performance', 'personalization', 'connections_and_databases', + 'app_menu', 'button_behaviot_and_examples', 'caching', + 'command_line_options', 'configuration', 'theming', 'connecting_to_data', + 'dataframes', 'forms', 'add_statefulness_to_apps', 'widget_behavior', + 'working_with_timezones', 'static_file_serving', + 'https_support', 'secrects_management', 'security_reminders', + 'connect_to_data_sources'] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +