Python

Streamlit is a powerful Python library

Streamlit is a powerful Python library that allows you to quickly create and deploy web applications for data science and machine learning projects. It provides an easy-to-use interface where you can build apps by simply writing Python code, without requiring HTML, CSS, or JavaScript knowledge. The interface is designed to be simple and intuitive for data scientists and engineers to turn their scripts into interactive web apps.

Here's a basic outline of how to create a simple Streamlit web interface:

1. Install Streamlit

First, you'll need to install Streamlit. If you don't have it installed yet, run the following command in your terminal:

pip install streamlit

2. Create a Python Script

Create a Python script (e.g., app.py) in which you'll write your Streamlit code.

3. Write Streamlit Code

Here is an example of a simple Streamlit app:

import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import time

# Set page configurations
st.set_page_config(
    page_title="Lean Streamlit",
    page_icon="????",
    layout="centered",  # Use 'centered' or 'wide'
    initial_sidebar_state="collapsed",  # Collapsed by default
)

# Title of the app
st.title('Advanced Streamlit Web Interface')

# Introduction Section with Markdown
st.markdown(
    """
    ## Welcome to the Streamlit Learning Experience

    Streamlit is a powerful and fast framework for building **data applications** in Python. It's ideal for showcasing machine learning models, data analysis, and interactive visualizations. Here, we will explore some of Streamlit's best features to help you get started quickly.

    ### Why Learn Streamlit?
    Streamlit allows you to:
    - **Build interactive data apps** with ease.
    - **Visualize data dynamically**.
    - **Deploy applications** quickly with minimal effort.
    - **Customize the UI** to suit your needs.

    ### What You'll Learn:
    - Streamlit's essential features.
    - Building **interactive applications**.
    - Using **widgets** like buttons, sliders, and text inputs.
    - Displaying data and **visualizations**.
    - Customizing the UI using **CSS**.
    - Creating **sidebars**, **columns**, and **expanders** for a rich user experience.
    """
)

# Custom styled Markdown box for additional content
st.markdown(
    f"""<div style="background-color: #f0f2f6; margin:20px; padding: 20px; border-radius: 10px; color: #333333; font-size: 16px;">
             **Advanced Streamlit Web Interface**: In this example, we’ll explore Streamlit’s core features like interactivity, layouts, data display, and more.
            </div>""",
    unsafe_allow_html=True,
)

# Adding some space after the markdown
st.markdown('<br><br>', unsafe_allow_html=True)

# Displaying Success, Error, and Warning messages
st.success(f"Success! You've started your Streamlit journey!")
st.error(f"Warning: Don't forget to check the sidebar for interactive widgets!")
st.warning(f"Streamlit makes data app building fast, but be mindful of excessive loops.")

# Section with Header and Subheader
st.header('Interactive Data Application Example')
st.subheader('Visualize and Analyze Data Interactively')

# Collecting user input for their name
name = st.text_input('Enter your name:', '')
if name:
    st.write(f'Hello, {name}! Welcome to the **Streamlit App** where data becomes interactive.')

# Displaying the current date and time
st.caption(f"Current Date and Time: {datetime.now()}")

# Simulating a long-running task using a button
def fetch_data():
    time.sleep(3)  # Simulate an API call or long-running computation
    return "Data fetched successfully from the source!"

# Button that triggers a long-running task
if st.button('Fetch Data'):
    with st.spinner('Fetching data...'):
        result = fetch_data()
    st.write(result)
    st.success('Task completed! You can now interact with the data.')

# Query Text Area
query = st.text_area(
    "Type your query here:",
    placeholder="E.g., Explore machine learning with Streamlit?",
    height=100,
)
if not query:
    st.warning("Please enter your query for analysis!")

# Adding a slider for selecting a range of numbers
slider_value = st.slider('Select a range of values for the X-axis:', 1, 20, (5, 15))

# Creating a DataFrame based on the slider values
x = np.arange(slider_value[0], slider_value[1] + 1)
y = np.random.rand(len(x))

data = pd.DataFrame({'X Value': x, 'Y Value': y})

# Display the DataFrame
st.write("### DataFrame Based on Your Selected Range:")
st.dataframe(data)

# Display the data as a table
st.write("### Data as a Table:")
st.table(data)

# Plotting a graph with interactive elements
st.write("### Sample Plot Based on Your Selection:")
fig, ax = plt.subplots()
ax.plot(data['X Value'], data['Y Value'], label='Random Data')
ax.set_title('Sample Plot')
ax.set_xlabel('X')
ax.set_ylabel('Y')
st.pyplot(fig)

# Add a selectbox to choose a plot type
plot_type = st.selectbox(
    'Choose a plot type:',
    ['Line Plot', 'Bar Plot', 'Scatter Plot'],
    help="Select the type of plot you want to visualize"
)

# Conditional plotting based on selected plot type
if plot_type == 'Line Plot':
    st.write("### Line Plot")
    st.line_chart(data.set_index('X Value')['Y Value'])
elif plot_type == 'Bar Plot':
    st.write("### Bar Plot")
    st.bar_chart(data.set_index('X Value')['Y Value'])
elif plot_type == 'Scatter Plot':
    st.write("### Scatter Plot")
    st.scatter_chart(data.set_index('X Value')['Y Value'])

# Adding a button to generate a random number
if st.button('Generate Random Number'):
    random_number = np.random.randint(1, 100)
    st.write(f'Generated Random Number: {random_number}')

# Displaying a checkbox with tips
if st.checkbox('Show Advanced Tips'):
    st.write("### Advanced Tips for Streamlit:")
    st.write("""
        - **Session State**: Maintain state across reruns of the app. This is useful for maintaining data during interactions.
        - **Caching**: Use `st.cache` to speed up computations by caching expensive functions.
        - **Custom Components**: Add custom HTML, CSS, or JavaScript components to enhance your app's functionality.
    """)

# Footer message
st.write("Streamlit allows you to quickly create **beautiful**, **interactive**, and **data-driven** apps.")

# Layout Management Section
st.subheader("Layout Management")
# Create two columns
col1, col2 = st.columns(2)

with col1:
    st.write("This is the **first column** of the layout")
    st.button("Button 1")

with col2:
    st.write("This is the **second column** of the layout")
    st.button("Button 2")

# Expander Section for additional content
with st.expander("More details"):
    st.write("This section provides additional content that can be expanded or collapsed for a cleaner interface.")

# Sidebar Layout
st.sidebar.header("Sidebar Section")
username = st.sidebar.text_input("Enter your username:")
age = st.sidebar.slider("Select your age", 18, 100, 25)

# Displaying the user input from the sidebar
st.write(f"Username: {username}")
st.write(f"Age: {age}")

# Displaying images
try:
    st.image("sunrise.jpg", caption="Nature's Beauty")  # Load image from local
except Exception as e:
    st.error(f"Error loading image: {str(e)}")

# Display image from a URL
st.image("https://t3.ftcdn.net/jpg/08/85/53/72/240_F_885537216_BOhcNIYKccDRrK0NGjO3uCWBPVvHN22o.jpg", caption="Earth Logo", use_container_width=True)

# Custom CSS for specific button styling using the key
st.markdown(
    """
    <style>
        /* Custom CSS for a specific button with ID */
        .custom_button>button {
            background-color: #4CAF50; /* Green */
            color: white;
            border: none;
            padding: 10px 24px;
            font-size: 16px;
            cursor: pointer;
            border-radius: 8px;
        }
        .custom-button>button:hover {
            background-color: #45a049;
        }
    </style>
    """,
    unsafe_allow_html=True
)

# Use Streamlit's button and add the custom class using 'key'
if st.button('Custom Styled Button', key="custom_button"):
    st.write('You clicked the custom-styled button!')

# Regular button without custom styling
if st.button('Regular Button'):
    st.write('You clicked the regular button!')

# File uploader for image
uploaded_image = st.file_uploader("Choose an image...", type=["png", "jpg", "jpeg"])

if uploaded_image is not None:
    st.image(uploaded_image, caption="Uploaded Image")

# Conclusion with Footer message
st.write("Streamlit allows you to rapidly create interactive apps for **data exploration**, **visualization**, and **prototyping**.")



This app gives you a complete experience of how Streamlit can handle user inputs, data displays, interactive widgets, and plots all in one clean and engaging interface.

 

4. Run the Streamlit App

Once you have the script written, run the following command in your terminal:

streamlit run app.py

This command will start a local development server, and you can view your Streamlit app in your web browser (usually at http://localhost:8501).

Key Streamlit Functions:

  • st.title(), st.header(), st.subheader(): For displaying titles, headers, and subheaders.
  • st.text_input(), st.slider(), st.selectbox(): For user inputs (e.g., text fields, sliders, dropdowns).
  • st.write(): Used to display text, data, and other content.
  • st.dataframe(), st.table(): Display DataFrames or tables.
  • st.plotly_chart(), st.pyplot(), st.line_chart(): For plotting visualizations (supports various libraries like matplotlib, plotly, etc.).
  • st.button(), st.radio(), st.checkbox(): For user-interaction elements like buttons, radio buttons, and checkboxes.

5. Deploy the App

After creating your Streamlit app, you can deploy it to the cloud using Streamlit's hosting platform, Streamlit Community Cloud or other services like Heroku or AWS.

To deploy it on Streamlit Community Cloud, you can:

  • Push your app to GitHub.
  • Connect the GitHub repo to Streamlit Community Cloud.
  • Streamlit will automatically deploy your app.
  • Learn more about : https://share.streamlit.io/

 

Advanced Streamlit Concepts

Streamlit is a dynamic tool for quickly building web applications for data science projects. Beyond the basics of creating apps with text inputs, buttons, and simple plots, there are many advanced features that you can leverage to make your apps more interactive and robust.

Here are some advanced concepts you can explore in Streamlit:

 

1. State Management

Session State: One of the most powerful features of Streamlit is the ability to manage and store state across reruns. This allows users to interact with the app without losing previous inputs or results.

import streamlit as st

if 'counter' not in st.session_state:
    st.session_state.counter = 0

st.button("Increment", on_click=lambda: st.session_state.update(counter=st.session_state.counter + 1))
st.write(f"Counter: {st.session_state.counter}")

Persistence: This allows you to remember user interactions, which is useful for multi-step workflows or applications where users need to input several values over time.

 

2. Custom Components

Streamlit allows you to build custom components using JavaScript, React, or other web technologies. This is useful when you need more control over the user interface or want to integrate other libraries.

  • You can create a custom input component, or integrate third-party visualizations that are not natively supported by Streamlit.
  • st.components.v1.html(): Allows you to render custom HTML, which can be useful for advanced customizations.

3. Deploying Streamlit Apps

  • Streamlit Cloud: You can deploy your app directly to Streamlit’s cloud platform (streamlit.io), which is easy and fast.
  • Docker: For more complex apps or specific environments, you can containerize your Streamlit app with Docker.
  • Other cloud services: Streamlit apps can also be deployed to other cloud services such as AWS, Heroku, or Google Cloud.

4. Dynamic Layouts

  • Streamlit provides various ways to customize the layout of your app:
    • st.columns(): Create a layout with multiple columns.
    • st.expander(): Add collapsible sections to organize content better.
    • st.container(): Group elements together to create more structured layouts.

Example:

col1, col2 = st.columns(2)
col1.write("This is the first column")
col2.write("This is the second column")

5. Interactive Widgets

  • Sliders, Text Boxes, Buttons, and More: Advanced interactivity can be achieved with a variety of widgets like sliders, multi-selects, and date pickers. You can use these to gather more complex input from users.

Example of interactive plotting:

import numpy as np
import matplotlib.pyplot as plt

st.sidebar.title("Adjust Plot Parameters")
freq = st.sidebar.slider("Frequency", 1, 10, 1)
phase = st.sidebar.slider("Phase", 0, 2 * np.pi, 0)

t = np.linspace(0, 1, 500)
y = np.sin(2 * np.pi * freq * t + phase)

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set_title("Sine Wave")
st.pyplot(fig)

6. File Uploads

  • st.file_uploader(): Streamlit allows users to upload files like CSVs, images, or models, which you can then use within your app for processing.

Example:

uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)
    st.write(df)

7. Data Visualizations

  • Streamlit supports a variety of data visualization libraries like matplotlib, plotly, altair, and bokeh. You can render interactive visualizations and integrate them seamlessly into your app.
  • For example, Plotly charts can be directly integrated using st.plotly_chart() for more dynamic and interactive plots.

8. Integrating with Machine Learning Models

  • Streamlit allows you to quickly showcase ML models. You can integrate trained models (e.g., from sklearn, TensorFlow, or PyTorch) and make predictions based on user inputs.

Example of prediction with a model:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit([[1], [2], [3]], [1, 2, 3])

user_input = st.number_input("Enter a value to predict", min_value=0)
prediction = model.predict([[user_input]])
st.write(f"Predicted value: {prediction[0]}")

9. Integrating with APIs

  • Streamlit apps can make API calls using Python libraries like requests or httpx and display the responses dynamically in your app.

Example:

import requests

response = requests.get('https://api.exapmle.com/data')
data = response.json()
st.write(data)

These advanced concepts will allow you to unlock the full potential of Streamlit and make your applications more interactive, feature-rich, and useful.

 

You can learn more about the streamlit  from official documentations well https://docs.streamlit.io/

 


About author

author image

Amrit panta

Fullstack developer, content creator



Scroll to Top