프토토타입이란?
- 릴리즈하기 전에 샘플버전
- Test 하기 위해 개발
- AI 모델의 input -> output을 확인.
-> AI 모델을 활용하여 titanic 예측 생존을 구현하였는데, 이를 웹페이지에 나타나게 해서 간단히 실험해 볼 수 있게 만듦.
🤔다른 조직의 도움 없이 빠르게 웹 서비스를 만드는 방법이 무엇일까?
👉 그것이 바로 Streamlit
1. 설치
pip install streamlit==1.36.0
2. 파일 만들기
01-streamlit-hello.py 만들고 나서 밑에 코드 치기.
import streamlit as st
st.title("hello streamlit")
st.write("Hello world")
3. streamlit 실행
터미널에서
streamlit run 01-streamlit-hello.py
Localhost
:현재 개발중인 컴퓨터에서만 접속 가능한 주소(localhost)Network URL
:동일한 네트워크에 연결된 다른 기기에서 접속 가능한 주소(ip주소등으로 표현)
Input : Write, Text, Input, Chat, Media
Output : Data, Chart
Streamlit Text 작성
- 제목, 굵은 글씨 사용할때
import streamlit as st
import pandas as pd
import numpy as np
import time
st.title("Title")
st.header("Header")
st.subheader("subheader")
st.write("Hello world")
Streanlit Text/Number/Data Input
- 사용자가 직접 문자나 숫자등을 입력하라고 할때
text_input =st.text_input("텍스트입력하셈: ")
st.write(text_input)
password_input = st.text_input("텍스트입력: ", type ="password")
number_input = st.number_input("숫자 입력: ")
st.write(number_input)
st.date_input("날짜를 입력하세요")
st.time_input("시간을 입력하세요")
Streamlit File uploader
- 파일 업로드 하고 싶은 경우(st.file_uploader)
uploaded_file = st.file_uploader("choose a file", type =["png","jpg","jpeg"])
Streamlit Radio Button, Select box
- 여러 옵션 중 하나만 선택
selected_item = st.radio("Radio part", ("A","B","C"))
if selected_item == "A":
st.write("A!!")
elif selected_item =="B":
st.write("B!!")
else:
st.write("C!!")
option = st.selectbox("select in selectionbox",("k","s","z"))
st.write("You selected: ", option)
multiselected = st.multiselect("multi selected",["A","B","C","D"]) #여러 옵션 선택
st.write("you selected", multiselected)
Streamlit Slider
- 주어진 범위에서 값을 선택하고 싶은 경우
values = st.slider(select a range of values, 0.0,100.0,(25.0, 75.0)) #최소,최대,기본디폴트값
st.write("values", values)
Streamlit checkbox
- True, False 옵션을 Input 으로 받고 싶은 경우
checkbox_bn = st.checkbox("체크박스 버튼")
if checkbox_bn:
st.write("체크박스 버튼 클릭!") #선택한 순간에 나타남.
## 만약 항상 체크하는게 좋다고 하면
checkbox_bn2 = st.checkbox("디폴트로 체크되어짐", value = True)
if checkbox_bn2:
st.write("항상 클릭됨")
Streamlit Button
- 버튼을 명시적으로 누를 때, 특정 동작 실시(특정 함수, 머신러닝 모델 예측)
if st.button("버튼 클릭되면"):
st.write("클릭후 보이는 메세지")
Streamlit Form
- 여러 입력을 그룹화하고 한번에 제출하고 싶은 경우
with st.form(key ="입력 form"):
username = st.text_input("Username")
password = st.text_input("Password", type = "password")
st.form_submit_button("login")
Streamlit Pandas, DataFrame, Markdown
df = pd.DataFrame({
'first column':[1,2,3,4],
'second column':[10,20,30,40]
})
st.markdown("======")
st.write(df) # 문자 숫자 dataframe 차드 등을 표시
st.dataframe(df) # Interactive 한 Dataframe, 컬럼 클릭/정렬
st.table(df) # Static 한 DataFrame
# 강조할 수도 있음.
st.dataframe(df.style.highlight_max(axis =0)) #axis =0은 row 1은 column
st.table(df.style.highlight_max(axis =0))
Streamlit Metric JSON
- Metric :지표를 표시하고 싶은 경우
- JSON : JSON 데이터를 표시하고 싶은 경우
st.metric("MY metric", 42,2)
st.json(df.to_json())
Streamlit Line Chart
chart_data = pd.DataFrame(
np.random.randn(3,20)m
columns = ["a","b","c"]
)
st.line_chart(chart_data)
Streamlit Map Chart
st.map(map_data)
Streamlit caption,code,latex
st.caption("caption")
st.code("a = 123")
st.latex("\int ax^2 \,dx")
(참고로 위 라텍스는 이렇게 나옴.)
Streamlit Spinner
- 연산이 진행되는 도중, 메세지를 보여주고 싶은 경우
- with 로 감싸서 하위에 원하는 함수 추가
with st.spinner("Please wait.."):
time.sleep(5)
Streamlit Status Box
- 성공하는 상황, 정보를 주고 받고 싶은 경우, 경고, 에러메세지 표현
st.success("Success")
st.info("Info")
st.warning("Warining")
st.error("Error message")
Streamlit Sidebar
- ui,ux -> Sidebar 를 사용하고 싶은 경우
- Sidebar에 파라미터를 지정하거나, 암호 설정가능
st.sidebar.button("hi")
Streamlit Columns
- 여러 칸으로 나눠서 Component 를 추가하고 싶은 경우 활용
col1, col2,col3,col4 = st.columns(4)
col1.write("Col1")
...
적으면 됨
Streamlit Expander
with st.expander("클릭하면 열려요"):
st.write("Contents!")
Streamlit 은 화면에서 무언가 업데이트 되면, 전체 Streamlit 코드 다시 실행
ex1) Code가 수정되는 경우
ex2) 사용자가 Streamlit widget과 상호작용하는 경우.
Session State
-> Global Variable 처럼 공유할 수 있는 변수를 만들고 저장.
-> session state 가 없다면 처음부터 다시 실행하므로 increment, decrement 못함
st.title("Counter Example with session state")
if "Count" not in st.session_state:
st.session_state.count = 0
increment = st.button("Increment1")
if increment:
st.session_state.count += 1
decrement = st.button("decrement1")
if decrement:
st.session_state.count -= 1
st.write(st.session_state.count)
UI 가 변경될 때 모든 코드를 다시 실행하는 특성 때문에 생기는 이슈-> 이런 경우 해결하기 위해 캐싱 데코레이터 활용(캐싱: 성능을 위해 데이터를 메모리 등에 저장.)
#캐싱하는법
@st.cache_data # 데이터 , API Request의 Response
@st.cache_resource #DB연결, ML모델 load
@st.cache_data
def fetch_large_dataset():
df = pd.read_csv("")
return df
stream으로 실시가 동영상 송출 가능
https://github.com/whitphx/streamlit-webrtc
https://style-transfer-webrtc.streamlit.app/
https://cheat-sheet.streamlit.app/
stream category(다른 사람이 한것들 볼 수 있음):https://streamlit.io/gallery?category=favorites