Streamlit
✕Streamlit Introduction
- Open-source Python library for building interactive web apps.
- Use Cases:
Data Dashboard,Model demo,Data Explorationetc. - Installed as:
pip install streamlit - Run app as:
streamlit run app_name.py - Simple API: Build apps with pure Python code.
- Interactivity: Widgets and state management for dynamic interactions.
- Media Support: Easily display images, videos, audio, etc.
- Easy Deployment: Deploy on Streamlit Cloud or other platforms.
Key Features:
Text Element
- Streamlit provides functions to display text in various formats.
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!')")
Example:
Input Widgets: Text, Number, Date
- Streamlit provides various widgets for text, number, date inputs.
- Explore more widgets at Streamlit Documentation.
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}")
Examples:
Input Widget: Selection
- Selection widgets allow users to choose from predefined options.
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}")
Examples:
File Input
- Streamlit provides a file uploader widget to allow users to upload files.
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())
Example:
Interactive Charts
- Supports interactive charts using libraries like
Matplotlib,Seaborn,Plotly. - We can display interactive dataframe as well
import seaborn as sns fig, ax = plt.subplots() sns.barplot(x="category", y="value", data=df, ax=ax) st.dataframe(df) st.pyplot(fig)
Example:
Layout
- Used for creating multi-column layouts and organizing content.
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.")
Example:
Deploying Streamlit App
- Deploying: Making app accessible to others via the web URL.
- We can create and share
ML Dashboard,Visualization,Model Demoetc. - 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 appand select your repository and branch. 4. Specify the main Python file (e.g.,app.py) and clickDeploy. 5. Our app will be live at a unique URL. 6. Note: Must addrequirements.txtwith dependencies.
Practice QuestionsNot started
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. -Submitbutton that shows summary of the entered data on click. - You should also send a confirmation email to user's email address.
- Create app to simulate bank account opening form. The app should have:
- Appropriate Title and Header.
- Text input for
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
Calculatethat shows total price on clicking.
Electricity Price Slabs:Units Consumed Price per Unit Example Calculation 0 - 20 4.00 per unit Eg: 15 units = 15 * 4 = 60 21 - 30 6.5 per unit Eg: 25 units = 20 * 4 + (25 - 20) * 6.5 = 112.5 30 - 50 10 per unit Eg: 40 units = 20 * 4 + 10 * 6.5 + (40 - 30) * 10 = 245 Above 50 12 per unit Eg: 60 units = 20 * 4 + 10 * 6.5 + 20 * 10 + (60 - 50) * 12 = 465 Electricity price slabs based on units consumed.- 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
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. -Calculatebutton 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:Unmarried Married Rate Upto 5 Lakh Upto 6 Lakh 0 if ssf deduction else 1% 5 Lakh - 7 Lakh 6 Lakh - 8 Lakh 10% 7 Lakh - 10 Lakh 8 Lakh - 11 Lakh) 20% 10 Lakh - 20 Lakh 11 Lakh - 20 Lakh 30% 20 Lakh - 50 Lakh 20 Lakh - 50 Lakh 36% Above 50 Lakh Above 50 Lakh 39% Tax slabs for calculating in-hand salary based on gross salary and marital status.- 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 (
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.csvto create dataframe [static]. - Drop down filter to selectGender. - Range slider to filterAge. - You can add other filters as well based on instinction. - CreateHistogramto showagedistribution. - CreateBar chartto showcount of heart_stroke by gender. - CreateScatter plotofsysBPvsdiaBPcolored by heart_stroke. - CreateBox plotofBMIpereducation_level. - You can add other interactive visuals based on your instinction.
- Create app to visualize data interactively. The app should have:
- Appropriate Title and Header.
- Read file
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 Reportthat displays EDA report on click. - EDA Report Requirement:
- Display
shape,column names,data types,duplicate counts. - Chart to display missing values per column. - Showsummary statisticsfor numeric columns. - Show correlation heatmap for numeric columns. -Download Reportbutton to save thepandas profilingreport.
- 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
