Streamlit

Streamlit Introduction

  • Open-source Python library for building interactive web apps.
  • Use Cases: Data Dashboard, Model demo, Data Exploration etc.
  • Installed as: pip install streamlit
  • Run app as: streamlit run app_name.py
  • Key Features:
    1. Simple API: Build apps with pure Python code.
    2. Interactivity: Widgets and state management for dynamic interactions.
    3. Media Support: Easily display images, videos, audio, etc.
    4. Easy Deployment: Deploy on Streamlit Cloud or other platforms.

Text Element

  • Streamlit provides functions to display text in various formats.
  • Example:
    1. import streamlit as st st.title("My Streamlit App") st.header("This is a header") st.subheader("This is a subheader") st.text("This is a text element.") st.write("This is a write element.") st.markdown("This is a **markdown** example.") st.code("def hello():\n\tprint('Hello, Streamlit!')")

Input Widgets: Text, Number, Date

  • Streamlit provides various widgets for text, number, date inputs.
  • Explore more widgets at Streamlit Documentation.
  • Examples:
    1. name = st.text_input("Enter your name") feedback = st.text_area("Enter your feedback") age = st.number_input("Enter your age", min_value=0, max_value=120) dob = st.date_input("Select your date of birth") st.write(f"Name: {name}, Feedback: {feedback}, Age: {age}, DOB: {dob}")

Input Widget: Selection

  • Selection widgets allow users to choose from predefined options.
  • Examples:
    1. color = st.selectbox("Choose a color", ["Red", "Green", "Blue"]) options = st.multiselect("Select options", ["Option 1", "Option 2"]) agree_to_terms = st.checkbox("Check this box to agree the terms.") gender = st.radio("Select your gender", ["Male", "Female", "Other"]) if st.button("Submit"): st.write(f"You selected {color} and options: {options}")

File Input

  • Streamlit provides a file uploader widget to allow users to upload files.
  • Example:
    1. uploaded_file = st.file_uploader("Choose a csv file", type="csv") if uploaded_file is not None: st.write(f"File name: {uploaded_file.name}") st.write(f"File type: {uploaded_file.type}") st.write(f"File size: {uploaded_file.size} bytes") df = pd.read_csv(uploaded_file) st.write(df.head())

Interactive Charts

  • Supports interactive charts using libraries like Matplotlib, Seaborn, Plotly.
  • We can display interactive dataframe as well
  • Example:
    1. import seaborn as sns fig, ax = plt.subplots() sns.barplot(x="category", y="value", data=df, ax=ax) st.dataframe(df) st.pyplot(fig)

Layout

  • Used for creating multi-column layouts and organizing content.
  • Example:
    1. col1, col2 = st.columns(2) with col1: st.header("Column 1") st.write("This is the first column.") with col2: st.header("Column 2") st.write("This is the second column.")

Deploying Streamlit App

  • Deploying: Making app accessible to others via the web URL.
  • We can create and share ML Dashboard, Visualization, Model Demo etc.
  • Deployment Options: - Streamlit Cloud: Free hosting with easy GitHub integration. - Heroku: General-purpose cloud platform. - AWS/GCP/Azure: Scalable cloud services for production apps.
  • Streamlit Cloud Deployment Steps: 1. Push your Streamlit app code to a GitHub repository. 2. Go to Streamlit Cloud and sign in with GitHub. 3. Click on New app and select your repository and branch. 4. Specify the main Python file (e.g., app.py) and click Deploy. 5. Our app will be live at a unique URL. 6. Note: Must add requirements.txt with dependencies.

Practice QuestionsNot started

  1. Bank Account Opening Form

    Question 1 of 5

    • Create app to simulate bank account opening form. The app should have: - Appropriate Title and Header. - Text input for First Name, Middle Name, Last Name , Address, Email. - Date input for date of birth. - Number input for phone number. - Selection input for account type (savings, current, fixed deposit). - Checkbox for I agree to the terms and conditions. - Submit button that shows summary of the entered data on click. - You should also send a confirmation email to user's email address.
  2. Electricity Price Calculator

    Question 2 of 5

    • Create app to calculate electricity price based on units consumed. The app should have: - Appropriate Title and Header. - Text input for user name. - Number input for electricity consumption in kWh (unit). - A button called Calculate that shows total price on clicking.
    Electricity Price Slabs:
    Units ConsumedPrice per UnitExample Calculation
    0 - 204.00 per unitEg: 15 units = 15 * 4 = 60
    21 - 306.5 per unitEg: 25 units = 20 * 4 + (25 - 20) * 6.5 = 112.5
    30 - 5010 per unitEg: 40 units = 20 * 4 + 10 * 6.5 + (40 - 30) * 10 = 245
    Above 5012 per unitEg: 60 units = 20 * 4 + 10 * 6.5 + 20 * 10 + (60 - 50) * 12 = 465
    Electricity price slabs based on units consumed.
  3. Salary In-hand Calculator

    Question 3 of 5

    • Create an app to calculate in-hand salary based on gross salary and deductions. The app should have: - Appropriate Title and Header. - Number input for yearly gross salary. - Number input for deductions (insurance, CIT, provident fund, etc.). - Boolean input for marital status. - Calculate button that shows in-hand salary (monthly, yearly) on click. - Note: Tax rate is applied after ssf & CIT deduction. - salary_in_hand = gross_salary - ssf - cit - tax_calculated_below
    Tax Slabs for Salary Calculation:
    UnmarriedMarriedRate
    Upto 5 LakhUpto 6 Lakh0 if ssf deduction else 1%
    5 Lakh - 7 Lakh6 Lakh - 8 Lakh10%
    7 Lakh - 10 Lakh8 Lakh - 11 Lakh)20%
    10 Lakh - 20 Lakh11 Lakh - 20 Lakh30%
    20 Lakh - 50 Lakh20 Lakh - 50 Lakh36%
    Above 50 LakhAbove 50 Lakh39%
    Tax slabs for calculating in-hand salary based on gross salary and marital status.
  4. Interactive Data Visualization

    Question 4 of 5

    • Create app to visualize data interactively. The app should have: - Appropriate Title and Header. - Read file heart_disease.csv to create dataframe [static]. - Drop down filter to select Gender. - Range slider to filter Age. - You can add other filters as well based on instinction. - Create Histogram to show age distribution. - Create Bar chart to show count of heart_stroke by gender. - Create Scatter plot of sysBP vs diaBP colored by heart_stroke. - Create Box plot of BMI per education_level. - You can add other interactive visuals based on your instinction.
  5. EDA Report Generator

    Question 5 of 5

    • Create an app to generate EDA report dynamically. The app should have: - Appropriate Title and Header. - File uploader to upload csv and file. - Drop Down to select pre-defined separator. - A button called Generate Report that displays EDA report on click.
    • EDA Report Requirement: - Display shape, column names, data types, duplicate counts. - Chart to display missing values per column. - Show summary statistics for numeric columns. - Show correlation heatmap for numeric columns. - Download Report button to save the pandas profiling report.