Title: Working with Streamlit

Create a Streamlit App

  • ✦ The best approach to learn Streamlit is through hands-on experience.
    • As you go through this note, make sure to experiment with each function in your Visual Studio Code.
    • With your app active, Streamlit's interface will prompt you to rerun the app and display updates every time you introduce a new element to your script and save your changes.

Step 1: Get the Sample App Up and Running

  • ✦ Streamlit has a wonderful "Getting Started" tutorial.
    • Going through the tutorial and understand the explanation in there
    • It's a carefully crafted, so after you have gone through the tutorial, you will have a good understanding of How Streamlit works and the different key components that you should be paying attention when you are creating your own Streamlit app.
image

πŸ”₯ Create your First Streamlit App
NEW

  • ✦ Next, copy the complete code from the tutorial from below
    • Then, paste the code to replace the content in "hello_world.py".
import streamlit as st
import pandas as pd
import numpy as np


st.title('Uber pickups in NYC')

  
DATE_COLUMN = 'date/time'
DATA_URL = ('https://s3-us-west-2.amazonaws.com/'

            'streamlit-demo-data/uber-raw-data-sep14.csv.gz')

@st.cache_data
def load_data(nrows):
    data = pd.read_csv(DATA_URL, nrows=nrows)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])
    return data

data_load_state = st.text('Loading data...')
data = load_data(10000)
data_load_state.text("Done! (using st.cache_data)")

if st.checkbox('Show raw data'):
    st.subheader('Raw data')
    st.write(data)

st.subheader('Number of pickups by hour')
hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0]
st.bar_chart(hist_values)

# Some number in the range 0-23
hour_to_filter = st.slider('hour', 0, 23, 17)
filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter]

st.subheader('Map of all pickups at %s:00' % hour_to_filter)
st.map(filtered_data)
  • ✦ Run the Streamlit App locally from your computer
    • by running the following line in the Visual Studio Code's terminal
    • streamlit run hello_world.py
  • ✦ Your browser will open up and the working Streamlit app will be displayed there!

Step 2: Understand the Basics by Getting your Hands Dirty

  • ✦ We are not stopping yet.
  • ✦ Now with the sample Streamlit App display on the browser, any changes that you make to the Streamlit code (from your Visual Studio Code) will reflect on the browser. If it doesn't, just hit the fresh button on the browser.
    • Next, please go through the official guide on "Basic Concepts of Streamlit".
    • The guide will provide additional explanation to the sample Streamlit app that you just deployed locally, such as what is magic command and how the interactions between the slider and the data filtering work.
    • Moreover, there are also new components being covered in this guide.
To Do: Copy the Code and Try it on Your Visual Studio Code
  • It's important that while you are going through this guide, copy over the sample code from the guide to your "hello_world.py" and observe the changes on the browser.
  • We think that there is nothing more effective than learning Streamlit, by actually experimenting with the code yourself!
image

πŸ”₯ Experiment new Code on the Fly
NEW



Step 3: Continue to Explore the Other Widgets

if you have been following up to this point, you would have most the required understanding to get started on building on your own Streamlit app.

Most of the time, it's about using the right widgets that allow your applications to:

  • ✦ Take in the inputs from users
  • ✦ Display the outputs to the users
 a widget is an interactive element that can be added to your app, allowing users to input data or adjust parameters in real-time. Widgets can range from simple buttons and text inputs to sliders and selectors, and somethings complex like editable tables or 3D rendering.

Many of these decisions are specific to your PoC project. As we will be starting to work on the PoC project very soon, it is definitely a good time to check out the different widgets available on Streamlit and scout for the widgets that are potentially useful for your project.


  • ✦ The best way to find out how the widgets work?

      1. Understand and see the the widget looks like on the Official API Reference section
      • This is probably the section on Streamlit documentation page that we would visit most often.
      • One reason is because each widget is unique. Different widgets take in different inputs (parameters to the relevant functions) and may have specific ways to produce the output.
      • It is very important for us to know what are the input and output of the widgets that we want to implement them, so that we can implement them correctly, without having to spend too much time on diagnosing the errors later.
      1. πŸ”₯ Copy the code over to your Visual Studio Code and try it out!!!
image

πŸ”₯ Experiment new Code on the Fly
NEW



Create a Multi-Page Streamlit App (Simpler)

As your app grows large, it becomes useful to organize your script into multiple pages. This makes your app easier to manage as a developer and easier to navigate as a user. Streamlit provides a frictionless way to create multipage apps. Pages are automatically shown in a navigation widget inside your app's sidebar. If a user clicks on a page in the sidebar, Streamlit navigates to that page without reloading the frontend β€” making app browsing incredibly fast! In this guide, let’s learn how to create multipage apps.

Structuring your multipage app

Streamlit identifies pages in a multipage app by directory structure and filenames. The file you pass to streamlit run is called your entrypoint file. This is your app's homepage. When you have a pages/ directory next to your entrypoint file, Streamlit will identify each Python file within it as a page. The following example has three pages. main.py is the entrypoint file and homepage.

your_working_directory/ 
β”œβ”€β”€ pages/ 
β”‚ β”œβ”€β”€ a_page.py 
β”‚ └── another_page.py 
└── main.py

Run your multipage app just like you would for a single-page app.

streamlit run main.py

Only files with .py extensions are identified as Pages

Only .py files in the pages/ directory will be identified as pages. Streamlit ignores all other files in the pages/ directory and its subdirectories. Streamlit also ignores Python files in subdirectories of pages/.



Naming and Ordering your pages

The entrypoint file is your app's homepage and the first page users will see when visiting your app. Once you've added pages to your app, the entrypoint file appears as the topmost page in the sidebar. Streamlit determines the page label and ordering of each page from your filenames.

Filenames for pages

Filenames are composed of four different parts as follows:

  1. number. A non-negative integer.
  2. separator. Any combination of underscore ("_"), dash ("-"), and space (" ").
  3. label. Everything up to, but not including, ".py".
  4. ".py"

How pages are sorted in the sidebar

The entrypoint file is always displayed first. The remaining pages are sorted as follows:

  • ✦ Files that have a number appear before files without a number.
  • ✦ Files are sorted based on the number (if any), followed by the label (if any).
  • ✦ When files are sorted, Streamlit treats the number as an actual number rather than a string. So 03 is the same as 3.

This table shows examples of filenames and their corresponding labels, sorted by the order in which they appear in the sidebar.

Filename Rendered label
1 - first page.py first page
12 monkeys.py monkeys
123.py 123
123_hello_dear_world.py hello dear world
_12 monkeys.py 12 monkeys
We can also set labels may differ from the page title set in st.set_page_config.|

In the script for the particular page, we can place this line st.set_page_config(page_title="Your Preferred Label for the Page") to set the custom label.




Key Takeaways on the working of Streamlit App

Now that you know a little more about all the individual pieces, let's close the loop and review how it works together:

  1. Streamlit apps are Python scripts that run from top to bottom.
  2. Every time a user opens a browser tab pointing to your app, the script is executed and a new session starts.
  3. As the script executes, Streamlit draws its output live in a browser.
  4. Every time a user interacts with a widget, your script is re-executed and Streamlit redraws its output in the browser.
    • The output value of that widget matches the new value during that rerun.
  5. Scripts use the Streamlit cache to avoid recomputing expensive functions, so updates happen very fast.
  6. Session State lets you save information that persists between reruns when you need more than a simple widget. We will look into more of this in next topic.
  7. Streamlit apps can contain multiple pages, which are defined in separate .py files in a pages folder.