!pip install -q streamlit
%%writefile app.py
import streamlit as st
st.title('Hello *World!* :sunglasses:')
Overwriting app.py
How to run the project? 🏃¶
The following command retrieves and displays your public IPv4 address. We need it to access the public URL.
!wget -q -O - ipv4.icanhazip.com
The following command runs a Streamlit web app locally and creates a public internet-accessible link for it
! streamlit run app.py & npx localtunnel --port 8501
!wget -q -O - ipv4.icanhazip.com
! streamlit run app.py & npx localtunnel --port 8501
34.86.89.52 [..................] \ fetchMetadata: sill resolveWithNewModule yargs@17.1.1 ch Collecting usage statistics. To deactivate, set browser.gatherUsageStats to False. You can now view your Streamlit app in your browser. Network URL: http://172.28.0.12:8501 External URL: http://34.86.89.52:8501 npx: installed 22 in 3.678s your url is: https://eight-lions-give.loca.lt 2023-09-26 08:09:45.286 Uncaught app exception Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script exec(code, module.__dict__) File "/content/app.py", line 12, in <module> result = float(num1) + float(num2) ValueError: could not convert string to float: ''
Official Streamlit Documentaion 📖¶
Let's take a look at some basic widgets 👀¶
In this section of the workshop, we will dive into the world of Streamlit widgets. Widgets are essential components that allow you to collect user input, making your Streamlit apps interactive and user-friendly. We'll explore various widgets such as text inputs, sliders, buttons, and more. To demonstrate their usage, we'll build a basic interactive app—a simple calculator.¶
1. Text Inputs: ⌨¶
Streamlit provides a straightforward way to collect text input from users. The primary widget for this purpose is 'st.text_input'. Let's see how it works:
user_input = st.text_input("Enter your name:")
st.write("Hello,", user_input)
In this example, we create a text input widget with a label, "Enter your name." The user's input is then displayed using st.write.
2. Sliders: ◀ ▶¶
Sliders are useful for selecting numerical values within a specified range. Streamlit's 'st.slider' widget makes it easy to incorporate them into your apps:
age = st.slider("Select your age:", 0, 100, 25) # (Min, Max, Start)
st.write("You are", age, "years old.")
Here, we create a slider for selecting the user's age, with a range from 0 to 100.
3. Buttons: ⏯¶
Buttons allow users to trigger actions. Streamlit's 'st.button' widget enables us to add buttons to our apps:
if st.button("Click me 🐣"):
st.write("Peeka-Boo 👻") # '+ user_input'
This code displays a button labeled "Click me." When clicked, it writes text to the app.
A Simple Calculator: 🔢¶
Now, let's put these widgets together to create a basic interactive app—a simple calculator. We'll use text inputs for numbers, radio buttons for selecting an operation, and a button to calculate the result.
# Take user input
num1 = st.text_input("Enter the first number:")
num2 = st.text_input("Enter the second number:")
operation = st.radio("Select an operation:", ("Add", "Subtract", "Multiply", "Divide"))
# if (num1!="" and num2!=""):
# Perform the calculation
if st.button("Calculate"):
if operation == "Add":
result = float(num1) + float(num2)
elif operation == "Subtract":
result = float(num1) - float(num2)
elif operation == "Multiply":
result = float(num1) * float(num2)
elif operation == "Divide":
result = float(num1) / float(num2)
st.write("Result:", result)
With this code, users can input two numbers, choose an operation, and then calculate the result by clicking the "Calculate" button.
Data Visualisation: 📊¶
In this section of the workshop, we'll explore how to integrate data visualization libraries, such as Plotly, with Streamlit. Visualizing data is a crucial aspect of data science and analysis, and Streamlit makes it easy to create interactive charts and graphs in your web apps.¶
Installing Plotly: ⭐¶
!pip install -q plotly
Streamlit seamlessly integrates with popular data visualization libraries like Plotly, Matplotlib, and Altair. These libraries allow you to create various types of charts, graphs, and plots. For this section, we'll focus on using Plotly, a powerful and interactive plotting library.
!pip install -q plotly
Creating Intractive Chart: 📈¶
Let's build a Streamlit app that displays an interactive Plotly chart. In this example, we'll create a simple line chart:
import streamlit as st
import plotly.express as px
# Sample data
data = {
'Time': [1, 2, 3, 4, 5], # 'Month': ['Jan', 'Feb', ...]
'Value': [10, 16, 5, 11, 8] # 'Sales': [12000, 15000, ...]
}
# Create a Plotly figure
fig = px.line(data, x='Time', y='Value', title='Sample Line Chart') # x='Month', y='Sales', title='Monthly Sales Trend'
# Display the chart in Streamlit
st.plotly_chart(fig)
In this code, we import Streamlit and Plotly Express, define sample data as a dictionary, then create a Plotly line chart using Plotly Express and finally use 'st.plotly_chart' to display the chart in our Streamlit app.
Customizing the Layout: 🧠¶
In this section of the workshop, we'll explore how to customize the layout of your Streamlit apps. You can use Markdown and HTML to format text and create structured content. Additionally, Streamlit provides tools like columns and widgets for organizing your app's interface effectively.¶
Using Markdown and HTML:¶
Streamlit allows you to use Markdown and even HTML to format text and create structured content within your app.¶
Markdown Example:¶
import streamlit as st
# Markdown
st.markdown("# This is a Heading")
st.markdown("## This is a Subheading")
st.markdown("This is a paragraph of text with **bold** and *italic* formatting.")
HTML Example:¶
import streamlit as st
# HTML
st.write("<h1>This is an HTML Heading</h1>", unsafe_allow_html=True)
st.write("<p>This is a paragraph of text with <strong>bold</strong> and <em>italic</em> formatting.</p>", unsafe_allow_html=True)
You can use Markdown for basic formatting and HTML for more advanced customization when needed. Just remember to set 'unsafe_allow_html=True' to allow rendering HTML in Streamlit.
Organising with Columns:¶
Columns are a powerful way to organize your app's layout. You can use 'st.columns()' to create multiple columns and distribute content accordingly. Here's an example:¶
import streamlit as st
# Create two columns
col1, col2 = st.columns(2)
# Add content to each column
with col1:
st.header("Column 1")
st.write("This is the left column.")
with col2:
st.header("Column 2")
st.write("This is the right column.")
Widgets for Better Organization:¶
Widgets can be used for interactive elements and better organization. You can group related widgets together and use them to collect user input effectively.¶
(ex: Registration Form)¶
import streamlit as st
# Create a widget group
with st.expander("Click to expand"):
st.write("This content is hidden by default.")
name = st.text_input("Enter your name:")
age = st.slider("Select your age:", 0, 100, 25)
submit_button = st.button("Submit")
# Perform actions based on user input
if submit_button:
st.write(f"Hello, {name}! You are {age} years old.")
In this example:¶
We use 'st.expander' to create an expandable widget group. Inside the group, we add text input, slider, and button widgets. The content is hidden until the user clicks to expand it.
Deploying Streamlit Apps: ☁¶
In this section of the workshop, we'll discuss the essential topic of deploying your Streamlit apps so that they can be accessed by others. Deploying your app makes it accessible over the internet, allowing you to share your work with a broader audience or colleagues. We'll briefly explore deployment options, focusing on one of the popular methods—Streamlit Sharing Cloud.¶
1. Make an account if you dont already have one:¶
GitHub Website¶
2. Create a new Public Repository.¶
3. Create an 'app.py' containing the main code for the website.¶
4. Create a 'requirements.txt' containing all the dependencies.¶
Use the following command to get the version of the installed package:¶
!pip show streamlit
Add the package to the 'requirements.txt' in the following format:¶
streamlit==1.27.0
5. Connect Streamlit Cloud and your GitHub:¶
Streamlit Cloud¶
6. Select your Public Repo to Host, and Select the appropriate branch and the Main Code file.¶
7. Press 'DEPLOY' and watch the Magic happen 🌟¶
!pip show streamlit
Do it Yourself 💪¶
In this optional part of the workshop, we'll provide you with a hands-on exercise to apply what you've learned about Streamlit. This exercise will give you the opportunity to create a small Streamlit app from scratch. If you have any questions or need assistance during the exercise, please feel free to ask for help.
Hints: 🔎¶
Use st.text_input to collect task input from the user.¶
Create a button using st.button to add tasks to the list.¶
Use a list to keep track of tasks.¶
Use 'st.session_state' to store the tasks (refer the streamlit docs: Session State Docs)¶
Display the tasks in the Streamlit app using st.write or a more structured layout if you prefer.¶
Sample Code:¶
import streamlit as st
# Create an empty list to store tasks
tasks = []
# See the difference between a normal variable and session_state variable.
# Collect task input from the user
task_input = st.text_input("Enter a task:")
# Add task to the list when the button is clicked
if st.button("Add Task"):
tasks.append(task_input)
# Display the list of tasks
st.write("Tasks:")
for i, task in enumerate(tasks):
st.write(f"{i + 1}. {task}")
Answer: ✅¶
import streamlit as st
# Title
st.title("To-Do List")
# Input field for task
task = st.text_input("Enter a new task:")
# Button to add task
if st.button("Add Task"):
if task:
st.write(f"Added: {task}")
# List to display tasks
task_list = st.empty()
# Initialize task list
if 'tasks' not in st.session_state:
st.session_state.tasks = []
# Add task to the list
if task:
st.session_state.tasks.append(task)
# Display tasks
if st.session_state.tasks:
task_list.write("## Tasks:")
for i, t in enumerate(st.session_state.tasks):
task_list.write(f"{i+1}. {t}")
# Checkbox to clear tasks
if st.checkbox("Clear Tasks"):
st.session_state.tasks = []
What the Code does:¶
- It creates a Streamlit app titled "To-Do List."
- It provides an input field for entering a new task.
- When the "Add Task" button is clicked, it adds the task to a list if it's not empty.
- It uses the st.empty() element to reserve a spot for displaying tasks.
- It initializes an empty list to store tasks in the Streamlit session state.
- It adds tasks to the session state list when the "Add Task" button is clicked.
- It displays the list of tasks using a loop.
- It provides a "Clear Tasks" checkbox to clear all tasks.
This code provides a simple to-do list that allows you to add tasks and clear them as needed. You can expand upon this basic example to add more features and functionality to your to-do list app.