Thursday, 28 December 2023

Fundamental and key aspects of building Streamlit App

Streamlit is an open source python library which is use to create and develop custom web applications for data science and machine learning.

Following are the steps one can follow to build streamlit app

  • Package installation

To use streamlit app, once has to install streamlit python package.Following command using pip can be use to install

pip install streamlit

  • Sample program - Hello World

Create a python script app.py and start with simple "Hello World" streamlit app 

import streamlit as st 

def main():

    st.title("Hello Streamlit!")

    st.write("This is a simple Streamlit app.") 

if __name__ == "__main__":

    main()

 Following are the essential python components 

1) Creating Widgets

Widgets are interactive components allowing user input.

  • Slider

import streamlit as st

value = st.slider('Select a value', min_value=0, max_value=100)

  • Text Input

text = st.text_input('Enter text')

  • Checkbox

option = st.checkbox('Show/hide')

2) Displaying Data

 Presenting data in various formats 

  • Display Dataframe

import pandas as pd

df = pd.DataFrame(data) # Your DataFrame st.dataframe(df)

  • Display Charts

import matplotlib.pyplot as plt

plt.plot(data)

st.pyplot() 

3) Layouts and Styling

 Providing structure to app and styling

  • Columns

col1, col2 = st.columns(2)

with col1:

st.write("Column 1")

 with col2:

 st.write("Column 2") 


  • Markdown and HTML

st.markdown('**Bold** text')

st.write("This is a regular text")

st.write("<p style='color:red'>This is HTML</p>", unsafe_allow_html=True)

 4) Handling User Inputs and Events

  • Button Click

if st.button('Click me'):

    st.write('Button clicked!')

  • Event Handling

selection = st.selectbox('Choose an option', options)

if selection == 'Option 1':

    st.write('Option 1 selected!')

 5) File Upload and Download

 Managing file uploads/downloads

  • File Upload

uploaded_file = st.file_uploader("Upload file", type=['csv', 'txt'])

  • File Download

download_button = st.download_button('Download', data=your_data, file_name='data.csv')

 6) Deployment Configuration

 Configuration settings for deployment

  • Page Title

st.set_page_config(page_title='My Streamlit App', layout='wide')

  • Caching

@st.cache

def expensive_computation(input):

    # Perform costly computation

    return result

result = expensive_computation(input_value)