This is the 28th day of my participation in the August Text Challenge.More challenges in August

The environment

  • 10 64 – bit Windows
  • Anaconda with python 3.8
  • Streamlit 0.86.0
  • Yolov5 v5.0

What is streamlit

Streamlit is an open source Python library that is quick to create custom Web applications and easy to share with others, especially in the field of machine learning and data science. The whole process doesn’t require you to know anything about the front end, including HTML, CSS, javascript, etc., and is very friendly to non-front end developers.

Streamlit installation

Streamlit requires python version 3.6 or greater and can be installed directly using PIP

pip install streamlit
Copy the code

After the installation is successful, use its built-in Hello app to test and run the command

streamlit hello
Copy the code

When the service starts, it will automatically open the page for us, and the address is http://localhost:8501

As you can see, Streamlit uses port 8501 by default

In addition, Streamlit officially provides a slightly more sophisticated application that combines yolov3’s target detection algorithm with a repository address: github.com/streamlit/d… , interested can go to research, short code, but complete function

So, for our own written source file, how to run it? In fact, it is very simple, such as the source file app.py, then can be executed

streamlit run app.py
Copy the code

Here are two more commonly used commands

  • Streamlit docs View documents
  • Streamlit cache Clear The cache

Streamlit common components

button

Import streamlit as st button = st.button(' button ')Copy the code

Text entry field

Import streamlit as st st.text_input(' Please enter your favorite programming language ', key="name")Copy the code

Text display

import streamlit as st

st.write('Hello streamlit.')
Copy the code

Streamlit supports markdown syntax perfectly, and you can use the write method directly, for example

Import streamlit as st st. write (" ", "# first-level headlines # # # # # 2 level 3 title emphasis on * * * * > this is reference. The python, Java, c/c + +. The rust" "")Copy the code

In addition to the write method, Streamlit also provides the Text method, which can also display text information

import streamlit as st

st.text('Hello streamlit.')
Copy the code

The title

import streamlit as st

st.title('title')
Copy the code

In addition to title, Streamlit also provides headers and subheaders

import streamlit as st

st.header('header')
st.subheader('subheader')
Copy the code

slider

import streamlit as st

number = st.slider('Pick a number', 0, 100)
Copy the code

Select box

import streamlit as st

flag = st.checkbox('Yes')
Copy the code

The radio button

import streamlit as st

languages = ['python', 'c', 'rust', 'c++']

st.radio('Pick a language', languages)
Copy the code

Drop down selection box

Import Streamlit as st St. selectbox(' Which programming languages are used? ', ('python', 'c', 'java', 'rust'))Copy the code

Date picker

import streamlit as st

date = st.date_input('Pick a date')
Copy the code

Color picker

import streamlit as st

color = st.color_picker('Pick a color')
Copy the code

File selector

import streamlit as st

file = st.file_uploader('Pick a file')
Copy the code

Other streamlit features

According to json

import streamlit as st

st.json({
    "code": 0,
    "data": {
        "sex": "female",
        "age": 18,
        "score": 100
    }
})
Copy the code

According to the code

from numpy.core.arrayprint import _leading_trailing
import streamlit as st

code = """
    def func():
        print('Hello streamlit.')
"""
st.code(code, language='python')
Copy the code

Displays the dataframe in pandas

from numpy.core.arrayprint import _leading_trailing
import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(50, 5), columns=(
    'col %d' % i for i in range(5)))
st.dataframe(df)

Copy the code

St. dataframe(df) in the last sentence can be replaced with St. write(df) for the same effect

Display table

import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(50, 5), columns=(
    'col %d' % i for i in range(5)))
st.table(df)
Copy the code

Unlike the dataframe above, the table displays all data without a scroll bar

Indicative data display

You also need to install another library, Streamlit-metrics, by executing the PIP install streamlit-metrics installation command

Import streamlit as st from streamlit_metrics import metric_row st.write metric_row({" follow ": 100, "like ": 200, "watching ": 300," sharing ": 400})Copy the code

Streamlit session state and callbacks

Session Status Session State

When you open a new page in your browser, you create a session. Session state is a way of interacting with data when a page rerun(rather than a f5-like page refresh) occurs.

Let’s look at an example of counting

import streamlit as st

st.title('Hello streamlit.')
counter = 0

increment = st.button('Increment')
if increment:
    counter += 1

st.write('Count= ', counter)
Copy the code

As you can see, only the first time you click the button, the Count goes up by 1, and the next clicks, the counter doesn’t change, which is obviously different from what we expected.

Let’s modify the code above

from typing import Counter
import streamlit as st

st.title('Hello streamlit.')
if 'counter' not in st.session_state:
    st.session_state.counter = 0

increment = st.button('Increment')
if increment:
    st.session_state.counter += 1

st.write('Count= ', st.session_state.counter)
Copy the code

This works fine, and every time you click the button, Count increases by 1

The callback callbacks

Callbacks are python functions that are called when an input component changes, such as a button being clicked, a slider being pulled, and so on.

Modify the above example using callbacks

from typing import Counter
import streamlit as st

# callbacks
def increment_counter():
    st.session_state.counter += 1


st.title('Callbacks')
if 'counter' not in st.session_state:
    st.session_state.counter = 0

st.button('Increment', on_click=increment_counter)
st.write('Count= ', st.session_state.counter)
Copy the code

The effect of code execution is the same. This is an example without passing arguments. If you need data interaction, you can use args or kwargs, as shown in the following example

import streamlit as st

st.title('Callbacks with args')
if 'counter' not in st.session_state:
    st.session_state.counter = 0

increment_value = st.number_input('Enter a value', value=0, step=1)


def increment_counter(increment_value):
    st.session_state.counter += increment_value


increment = st.button('Increment', on_click=increment_counter,
                      args=(increment_value, ))

st.write('Count = ', st.session_state.counter)
Copy the code

Let’s look at the use of kwargs, which accepts named parameters

import streamlit as st

st.title('Callbacks with kwargs')
if 'counter' not in st.session_state:
    st.session_state.counter = 0


def increment_counter(increment_value=0):
    st.session_state.counter += increment_value


def decrement_counter(decrement_value=0):
    st.session_state.counter -= decrement_value


st.button('Increment', on_click=increment_counter,
          kwargs=dict(increment_value=5))

st.button('Decrement', on_click=decrement_counter,
          kwargs=dict(decrement_value=1))

st.write('Count = ', st.session_state.counter)
Copy the code

Click Increment to increase Count by 5, and Decrement to decrease Count by 1

Notes on session status

There are two things to note about session state

  • Session state exists as long as the page is open and connected to the Streamlit server. Once the TAB is closed, all content stored in the session state is lost

  • Session state is not persisted. If the Streamlit server crashes, all content stored in session state is deleted

Streamlit deployment

One of streamlit’s most important advantages is sharing

Go to streamlit. IO/Sharing and request an invitation

After filling in the basic information, it’s time to wait for a reply

Streamlit processing was quick, and I received a confirmation email the next day

In the email, detailed deployment steps are given, and basically just follow them

  1. To save the project to Github, which is the main branch by default, you need requirements. TXT

  2. Go to share.streamlit. IO/and log in using your Github account

  3. Create an

  1. Fill in project information, branch and entry files correctly

  1. As deployment begins, dependencies are installed in the background

  1. Project running

I made a mistake here

Traceback (most recent call last): The File "/ home/appuser/venv/lib/python3.7 / site - packages/streamlit/script_runner. Py", line 350, in _run_script exec (code, module.__dict__) File "/app/yolov5-streamlit/main.py", line 5, in <module> from detect import detect File "/app/yolov5-streamlit/detect.py", line 5, In < module > import cv2 File "/ home/appuser venv/lib/python3.7 / site - packages/cv2 / set py", line 5, in <module> from .cv2 import * ImportError: libGL.so.1: cannot open shared object file: No such file or directoryCopy the code

Here you need to change opencv-python in the requirements. TXT file to opencv-python-headless

After clicking rerun in the upper right, reinstall the dependencies and you are ready to run successfully

Finally, let’s test if it works. Select a local image to upload and click Detect

No problem. At this point, the entire App deployment is complete and you can share it with your friends

If you want to play it online, you can visit it

Share. Streamlit. IO/xugaoxiang /…

Download the source code

Github address: github.com/xugaoxiang/…

The entry file is main.py, which contains very little interface code related to Streamlit. The yolov5 code is basically copied from the original project with only 2 changes

  1. The detect method in detect.py adds a parameteropt
  2. Modify video detection after stored format from originalmp4vChanged toavc1. The reason is thatstreamlitIn thevideoSuitable for playh264The codingmp4For detailed operation, please refer toXugaoxiang.com/2021/08/20/…

The resources

  • docs.streamlit.io/en/stable/
  • Github.com/ultralytics…
  • Discuss. Streamlit. IO/t/streamlit…