CoolFace
Apppublic

awacke1/Streamlit-Cookbook-Code-Examples

sourceHugging Facemitupdated 2y agoView on Hugging Face
2likes
app.py161 linesDownload Raw Back to root
1import streamlit as st2import pandas as pd3import numpy as np4import altair as alt5import plotly.express as px6import plotly.graph_objects as go7import pydeck as pdk8from PIL import Image9import cv210import io11 12st.set_page_config(page_title="Streamlit Comprehensive Demo ๐Ÿš€", page_icon="๐Ÿ“", layout="wide")13 14def main():15    st.title("๐ŸŽจ Streamlit Comprehensive Showcase")16    st.markdown("Explore the various features of Streamlit in this interactive demo!")17 18    # Sidebar for navigation19    demo_type = st.sidebar.selectbox(20        "Choose a Demo",21        ["Basic Elements", "Data Visualization", "Interactive Widgets", "Advanced Features"]22    )23 24    if demo_type == "Basic Elements":25        show_basic_elements()26    elif demo_type == "Data Visualization":27        show_data_visualization()28    elif demo_type == "Interactive Widgets":29        show_interactive_widgets()30    elif demo_type == "Advanced Features":31        show_advanced_features()32 33def show_basic_elements():34    st.header("1. Basic Elements")35 36    st.subheader("1.1 Text Elements")37    st.text("This is simple text")38    st.markdown("This is **markdown** with _styling_")39    st.latex(r"\begin{pmatrix}a & b \\ c & d\end{pmatrix}")40 41    st.subheader("1.2 Data Display")42    df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})43    st.dataframe(df)44    st.table(df)45    st.json({"foo": "bar", "baz": "boz"})46 47    st.subheader("1.3 Media Elements")48    st.image("https://streamlit.io/images/brand/streamlit-mark-color.png", width=200)49    st.audio("https://upload.wikimedia.org/wikipedia/commons/c/c4/Muriel-Nguyen-Xuan-Chopin-valse-opus64-1.ogg")50    st.video("https://youtu.be/B2iAodr0fOo")51 52def show_data_visualization():53    st.header("2. Data Visualization")54 55    @st.cache_data56    def load_data():57        return pd.DataFrame(np.random.randn(20, 3), columns=["A", "B", "C"])58 59    data = load_data()60 61    st.subheader("2.1 Streamlit Charts")62    st.line_chart(data)63    st.area_chart(data)64    st.bar_chart(data)65 66    st.subheader("2.2 Altair Chart")67    chart = alt.Chart(data).mark_circle().encode(68        x='A', y='B', size='C', color='C', tooltip=['A', 'B', 'C'])69    st.altair_chart(chart, use_container_width=True)70 71    st.subheader("2.3 Plotly Chart")72    fig = px.scatter(data, x="A", y="B", size="C", color="C")73    st.plotly_chart(fig, use_container_width=True)74 75    st.subheader("2.4 PyDeck Chart")76    chart_data = pd.DataFrame(np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon'])77    st.pydeck_chart(pdk.Deck(78        map_style=None,79        initial_view_state=pdk.ViewState(latitude=37.76, longitude=-122.4, zoom=11, pitch=50),80        layers=[pdk.Layer('HexagonLayer', data=chart_data, get_position='[lon, lat]', radius=200, elevation_scale=4, elevation_range=[0, 1000], pickable=True, extruded=True)]81    ))82 83def show_interactive_widgets():84    st.header("3. Interactive Widgets")85 86    st.subheader("3.1 Input Widgets")87    text_input = st.text_input("Enter some text")88    number = st.number_input("Enter a number", min_value=0, max_value=100)89    date = st.date_input("Pick a date")90 91    st.subheader("3.2 Selection Widgets")92    option = st.selectbox("Choose an option", ["Option 1", "Option 2", "Option 3"])93    options = st.multiselect("Choose multiple options", ["A", "B", "C", "D"])94    slider_val = st.slider("Pick a number", 0, 100)95 96    st.subheader("3.3 Button and Download")97    if st.button("Click me!"):98        st.write("Button clicked!")99 100    @st.cache_data101    def get_sample_data():102        return pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})103 104    csv = get_sample_data().to_csv(index=False)105    st.download_button("Download CSV", csv, "sample_data.csv", "text/csv")106 107def show_advanced_features():108    st.header("4. Advanced Features")109 110    st.subheader("4.1 Layouts")111    col1, col2 = st.columns(2)112    with col1:113        st.write("This is column 1")114    with col2:115        st.write("This is column 2")116 117    with st.expander("Click to expand"):118        st.write("This content is hidden by default")119 120    st.subheader("4.2 Progress and Status")121    progress_bar = st.progress(0)122    for i in range(100):123        progress_bar.progress(i + 1)124    st.success("This is a success message!")125    st.error("This is an error message!")126    st.warning("This is a warning message!")127    st.info("This is an info message!")128 129    st.subheader("4.3 Cache and Performance")130    @st.cache_data131    def expensive_computation(a, b):132        return a * b133 134    result = expensive_computation(2, 21)135    st.write(f"2 * 21 is {result}")136 137    st.subheader("4.4 Session State")138    if 'count' not in st.session_state:139        st.session_state.count = 0140 141    if st.button('Increment'):142        st.session_state.count += 1143 144    st.write('Count = ', st.session_state.count)145 146    st.subheader("4.5 Forms")147    with st.form("my_form"):148        st.write("Inside the form")149        slider_val = st.slider("Form slider")150        checkbox_val = st.checkbox("Form checkbox")151        submitted = st.form_submit_button("Submit")152    if submitted:153        st.write("Slider", slider_val, "Checkbox", checkbox_val)154 155    st.subheader("4.6 Popover")156    with st.popover("Click for Popover"):157        st.write("This is a popover")158        st.image("https://streamlit.io/images/brand/streamlit-mark-color.png", width=100)159 160if __name__ == "__main__":161    main()