국문과 유목민

[Streamlit] Streamlit 명령어 본문

IT 견문록/ProductServing

[Streamlit] Streamlit 명령어

논곰 2022. 5. 18. 14:26

 Stramlit은 datascript를 웹서비스의 형태로 빠르게 공유할 수 있는 라이브러리이다. 프로토타입을 만들 때, 프론트엔드 경험이나 지식 없이도, 매우 쉽고 빠르게 만들 수 있다는 장점이 있다. Voila는 주피터노트북 환경에서 프로토타입을 생성했다면, Streamlit은 파이썬 스크립트 코드에서 구현할 수 있다. 해당 포스팅에서는 streamlit에서 사용하는 기본적인 명령어에 대해서 간단히 작성해두고자 한다. 

설치 및 사용법

설치방법은 어렵지 않고, pip install stramlit을 하면 된다.

pip install stramlit

import

import streamlit as st

사용법

streamlit run [streamlit파일명.py] [--server.port 30001]
# server.port의 경우 default로 8501이 Setting된다.

Streamlit DataFlow

Streamlit은 Streamlit의 화면에서 다음과 같은 것들이 업데이트되면 전체 Streamlit코드가 다시 실행된다. 

  1. Code가 수정되는 경우
  2. 사용자가 Streamlit의 위젯과 상호작용하는 경우

 매번 코드가 재실행되며 발생하는 문제점은 중복 이벤트를 할 수 없다는 것이다. 따라서 전역변수처럼 Streamlit이 업데이트되어도 변하지 않게 설정할 수 있는 방법이 필요했다. 그래서 Session state가 개발됐고, 반복해서 사용하고 싶은 변수가 있을 때 Session State로 만들어서 사용할 수 있게 됐다.
(Default value init 후 특정 조건 충족시 Sesson_state의 변수 바꾸게 적용)

# session_state가 없다면
st.title('Counter Example without session state')

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

decrement = st.button('Decrement')
if decrement:
    count_value -= 1
st.write('Count = ', count_value)


# session_state가 있다면
st.title('Counter Example with session state')

# count session_state에 init
if 'count' not in st.session_state:
    st.session_state.count = 0
    
# increment 버튼이 클릭되면 session_state의 count에 1을 더함
increment = st.button('Increment1')
if increment:
    st.session_state.count += 1
# decrement 버튼이 클릭되면 session_state의 count에 1을 더함
decrement = st.button('Decrement2')
if decrement:
    st.session_state.count -= 1
st.write('Count = ', st.session_state.count)
Session State가 없으면 Increment를 눌러도 매번 0으로 초기화 돼서 1만 표시됨
 

 매번 다시 실행하는 특성 때문에 데이터도 매번 다시 읽을 수 있기 때문에 이런 경우 @st.cache데코레이터를 사용해 캐싱하면 좋다. 예를 들어 모델 Prediction 등을 진행할 때, Model을 load하거나, 큰 데이터를 load하는 일이 있다면 @st.cache를 해두는게 좋다.
(데이터를 읽는 함수를 만들고, 데코레이터를 적용)

DATE_COLUMN = 'date/time'
DATA_URL = ('https://s3-us-west-2.amazonaws.com/'
            'streamlit-demo-data/uber-raw-data-sep14.csv.gz')
@st.cache
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

Display Text

st.text('Fixed width text')
st.markdown('_Markdown_') # see *
st.latex(r''' e^{i\pi} + 1 = 0 ''')
st.write('Most objects use') # 보여줄 수 있는 것이면 어떤 것이든 (df, err, func, keras ...)
st.write(['st', 'is <', 3]) # see *
st.title('My title')
st.header('My header')
st.subheader('My sub')
st.code('for i in range(8): foo()')

Display Data

st.dataframe: Interactive한 DataFrame으로 컬럼클릭이 가능하고 정렬도 가능하다.

st.table: st.dataframe과 다르게 static한 DataFrame이다. 

st.dataframe(my_dataframe)
st.table(data.iloc[0:10])
st.json({'foo':'bar','fu':'ba'})
st.metric('My metric', 42, 2) # (title, 현재값, 오른 값)

Display media

st.image('./header.png')
st.audio(data)
st.video(data)

Display interactive widgets

Button, Checkbox, radiobutton, selectbox, multiselect, slider

st.button('Click me')
st.checkbox('I agree')
st.radio('Pick one', ['cats', 'dogs'])
st.selectbox('Pick one', ['cats', 'dogs'])
st.multiselect('Buy', ['milk', 'apples', 'potatoes'])
st.slider('Pick a number', 0, 100)
st.select_slider('Pick a size', ['S', 'M', 'L'])

input, text_area, uploader, download, color_picker

st.text_input('First name')
st.number_input('Pick a number', 0, 10)
st.text_area('Text to translate')
st.date_input('Your birthday')
st.time_input('Meeting time')
st.file_uploader('Upload a CSV')
st.download_button('Download file', data)
st.color_picker('Pick a color')

Display progress and status

with st.spinner(text='In progress'):
	time.sleep(5)
	st.success('Done')

st.balloons()
st.error('Error message')
st.warning('Warning message')
st.info('Info message')
st.success('Success message')

st.progress(progress_variable_1_to_100)
st.exception(e)

(Spinner) loading 중에는 In Progress가 뜬다 / (Balloons)로딩 될 때마다 balloon이 올라온다. [귀엽다]

 

(Spinner) loading 이후 Done이 뜬다

Columns

 

# Two equal columns:
col1, col2 = st.columns(2)
col1.write("This is column 1")
col2.write("This is column 2")

# Three different columns:
col1, col2, col3 = st.columns([3, 1, 1])
# col1 is larger.

# You can also use "with" notation:
with col1:
    st.radio('Select one:', [1, 2])

Control Flow

streamlit의 Flow를 컨트롤 할 수 있는 명령어

# Stop execution immediately:
st.stop()
# Rerun script immediately:
st.experimental_rerun()

st.form을 활영하면 로그인 화면처럼 구성할 수 있다.

# Group multiple widgets:
with st.form(key='my_form'):
   username = st.text_input('Username')
   password = st.text_input('Password')
   st.form_submit_button('Login')

 부족한 설명에 대해서는 Streamlit에 관한 cheatseat에서 더 잘 설명하고 있으며, 변성윤님의 블로그를 살펴보는 것도 좋은 방법이라고 생각한다.

'IT 견문록 > ProductServing' 카테고리의 다른 글

[FastAPI] FastAPI 기초 지식  (0) 2022.05.25
[Backend] 백엔드 기초 지식  (0) 2022.05.24
[Ipywidget] Ipywidget 명령어  (0) 2022.05.18