개요

Streamlit은 Python으로 데이터 앱·대시보드·ML 데모를 빠르게 만들 수 있는 오픈소스 프레임워크. HTML/CSS/JS 없이 순수 Python 코드만으로 인터랙티브 웹 앱 구현.


설치 & 실행

pip install streamlit
 
# 앱 실행
streamlit run app.py
 
# 접속: http://localhost:8501

기본 구성 요소

import streamlit as st
import pandas as pd
import numpy as np
 
# 제목 & 텍스트
st.title("내 첫 Streamlit 앱")
st.header("헤더")
st.subheader("서브헤더")
st.write("일반 텍스트 또는 **마크다운** 지원")
st.markdown("## 마크다운")
 
# 입력 위젯
name = st.text_input("이름을 입력하세요")
age = st.slider("나이", 0, 100, 25)
option = st.selectbox("선택", ["A", "B", "C"])
checked = st.checkbox("동의함")
uploaded = st.file_uploader("파일 업로드")
 
# 버튼
if st.button("클릭"):
    st.success("버튼 클릭됨!")
 
# 데이터 표시
df = pd.DataFrame({"A": [1,2,3], "B": [4,5,6]})
st.dataframe(df)
st.table(df)
 
# 차트
st.line_chart(df)
st.bar_chart(df)
 
# 레이아웃
col1, col2 = st.columns(2)
with col1:
    st.write("왼쪽 컬럼")
with col2:
    st.write("오른쪽 컬럼")
 
# 사이드바
st.sidebar.title("사이드바")
model = st.sidebar.selectbox("모델 선택", ["GPT-4", "Claude"])

세션 상태 (상태 유지)

import streamlit as st
 
# 세션 상태 초기화
if "count" not in st.session_state:
    st.session_state.count = 0
 
if st.button("증가"):
    st.session_state.count += 1
 
st.write(f"카운트: {st.session_state.count}")

캐싱 (성능 최적화)

import streamlit as st
import pandas as pd
 
@st.cache_data  # 데이터 캐시 (파일 읽기, DB 쿼리 등)
def load_data():
    return pd.read_csv("large_file.csv")
 
@st.cache_resource  # 리소스 캐시 (모델 로딩 등)
def load_model():
    import torch
    return torch.load("model.pt")
 
df = load_data()  # 첫 호출만 실행, 이후 캐시 반환

LLM 챗봇 예시

import streamlit as st
from openai import OpenAI
 
client = OpenAI()
st.title("ChatGPT 클론")
 
# 대화 기록
if "messages" not in st.session_state:
    st.session_state.messages = []
 
# 이전 메시지 표시
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])
 
# 입력
if prompt := st.chat_input("메시지를 입력하세요"):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)
 
    # AI 응답
    with st.chat_message("assistant"):
        response = client.chat.completions.create(
            model="gpt-4",
            messages=st.session_state.messages
        )
        reply = response.choices[0].message.content
        st.markdown(reply)
    st.session_state.messages.append({"role": "assistant", "content": reply})

Streamlit vs 대안

항목StreamlitGradioDash
학습 곡선낮음낮음중간
커스텀제한적제한적자유
ML 특화강함매우 강함보통
배포Streamlit CloudHugging Face직접

관련 항목