본문 바로가기
데이터 어쩌구/전처리 및 시각화

[python] Demo 만들기 : Streamlit

by annmunju 2023. 8. 28.

초기 세팅 및 사용

  • 설치
$ pipenv install streamlit
  • 테스트
$ pipenv shell
$ streamlit hello
  • 실행
# Running
$ python -m streamlit run your_script.py

# is equivalent to:
$ streamlit run your_script.py

# URL로 실행하기 (Gist 이용)
$ streamlit run <https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py>
  • 포트 번호 지정 후 실행
$ streamlit run your_script.py --server.port 80
  • 디버깅 (.vscode/launch.json)
	"configurations": [
			{
		      "name": "Python: Streamlit",
		      "type": "python",
		      "request": "launch",
		      "module": "streamlit",
		      "args": [
		          "run",
		          "${file}",
		          "--server.port",
		          "<포트 번호>"]
	    }
	]

문법

  • 예시
st.sidebar.markdown('''
# Input
''')

uniqueid = st.sidebar.text_input('ID')

meta = None

if (len(uniqueid) != 0):
    img = df[df['id']==uniqueid]['img']

'''
### Output
'''

container = st.container()

left_col, right_col = container.columns(2)

def show_image():
    left_col.image(img)

def extract_color():
    single_tab, scheme_tab = container.tabs(['tab1', 'tab2'])
    img_array = np.array(Image.open(BytesIO(img)))
    tab1_result, tab2_result = image_refectoring(img_array) # 자체 함수

    single_tab.image(tab1_result)
    scheme_tab.image(tab2_result)

fin_image = st.sidebar.button('제출', on_click=show_image)
if fin_image:
    st.button('결과 확인', on_click=extract_color)

공식 문서

API Reference - Streamlit Docs

Caching

  • 시간이 오래 소요되는 함수의 경우 streamlit의 내장함수인 st.cache_data 혹은 st.cache_resource 를 이용해서 캐시를 저장해 호출해올 수 있다.
  • st.cache_data : 반복 사용으로 인해 캐싱이 필요한 경우 (대부분 사용)
    • 예 1) 인터넷에서 큰 데이터 프레임을 받아와서 매번 사용한다고 가정
      • 처음 실행할때만 느리게 다운로드 되고, 이후에는 즉각적으로 나타남.
    • @st.cache_data # 👈 Add the caching decorator def load_data(url): df = pd.read_csv(url) return df df = load_data("<https://github.com/plotly/datasets/raw/master/uber-rides-data1.csv>") st.dataframe(df) st.button("Rerun")
    • 예 2) 복잡한 ML 모델을 반복 실행할 때
      • 이전에 실행했던 내용이라면 바로 답을 줌
    • @st.cache_data def run_model(inputs): return model(inputs)
  • st.cache_resource : 위 cache_data와 유사하나 캐시 반환값의 복사본을 만들지 않고 개체 자체를 저장함. (스레드 등으로 인한) 개체의 변형이 있으면 충돌이나 데이터 손상이 발생할 수 있음.
    • 예 1) 데이터 베이스 연결
    • @st.cache_resource def init_connection(): host = "hh-pgsql-public.ebi.ac.uk" database = "pfmegrnargs" user = "reader" password = "NWDMCE5xdipIjRrp" return psycopg2.connect(host=host, database=database, user=user, password=password) conn = init_connection()
    • 예 2) ML 모델을 로드할 때
    • @st.cache_resource def load_model(): model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) model.eval() return model model = load_model()
  • 고급 사용 (공식 문서 참고)

REST API? → 사용 불가… 🥲

How to have API call on streamlit?

https://github.com/streamlit/streamlit/issues/439

대안?

https://github.com/davidefiocco/streamlit-fastapi-model-serving/

  • Streamlit(Frontend service)과 Fastapi(Backend service)를 연결해 모델 서빙 (docker 이용)
728x90