0.참고사이트
https://streamlit.io/playground?example=hello
1.차트실습
import streamlit as st
import pandas as pd
import numpy as np
# 데이터 시각화와 위젯 소개 텍스트 출력st.write("Streamlit supports a wide range of data visualizations, including [Plotly, Altair, and Bokeh charts](https://docs.streamlit.io/develop/api-reference/charts). 📊 And with over 20 input widgets, you can easily make your data interactive!")
all_users = ["Alice", "Bob", "Charly"]
# 입력 위젯을 담은 컨테이너 생성with st.container(border=True):
users = st.multiselect("Users", all_users, default=all_users) # 사용자 선택 멀티셀렉트 rolling_average = st.toggle("Rolling average") # 이동 평균 토글# 더미 데이터 생성 (랜덤으로 생성한 테스트용 가상 데이터)np.random.seed(42)
data = pd.DataFrame(np.random.randn(20, len(users)), columns=users)
# 이동 평균 처리 (선택한 경우)if rolling_average:
data = data.rolling(7).mean().dropna()
# 탭 구성: 차트와 데이터프레임으로 분리 출력tab1, tab2 = st.tabs(["Chart", "Dataframe"])
tab1.line_chart(data, height=250) # 선형 차트 출력tab2.dataframe(data, height=250, use_container_width=True) # 데이터프레임 출력
Python
복사
2.LLM 기초 챗봇 실습
import streamlit as st
import random
import time
# 1. 소개 문구 출력st.write("Streamlit loves LLMs! 🤖 [Build your own chat app](https://docs.streamlit.io/develop/tutorials/llms/build-conversational-apps) in minutes, then make it powerful by adding images, dataframes, or even input widgets to the chat.")
# 2. 설명 캡션 출력st.caption("Note that this demo app isn't actually connected to any LLMs. Those are expensive ;)")
# 3. 세션 상태에 채팅 기록이 없으면 초기화if "messages" not in st.session_state:
# 최초 실행 시 assistant의 시작 메시지 추가 st.session_state.messages = [{"role": "assistant", "content": "Let's start chatting! 👇"}]
# 4. 기존 채팅 기록을 화면에 출력for message in st.session_state.messages:
with st.chat_message(message["role"]): # 사용자 또는 assistant 역할에 따라 말풍선 다르게 표시 st.markdown(message["content"]) # 채팅 내용 출력# 5. 사용자 입력 받기if prompt := st.chat_input("What is up?"):
# 5-1. 사용자 입력을 채팅 기록에 추가 st.session_state.messages.append({"role": "user", "content": prompt})
# 5-2. 사용자 입력을 채팅 말풍선으로 출력 with st.chat_message("user"):
st.markdown(prompt)
# 5-3. assistant 응답 생성 및 출력 with st.chat_message("assistant"):
message_placeholder = st.empty() # 채팅이 실시간으로 입력되는 것처럼 보이게 하기 위한 임시 공간 full_response = "" # 전체 응답 문자열 저장용 assistant_response = random.choice(
[ # 임의로 선택된 응답 목록 중 하나를 선택 "Hello there! How can I assist you today?",
"Hi, human! Is there anything I can help you with?",
"Do you need help?",
]
)
# 5-4. 응답을 한 단어씩 출력하며 타이핑 효과 구현 for chunk in assistant_response.split():
full_response += chunk + " " time.sleep(0.05) # 50ms 딜레이로 타이핑 효과 message_placeholder.markdown(full_response + "▌") # 타이핑 중인 커서 추가 # 최종 응답을 출력 (커서 제거) message_placeholder.markdown(full_response)
# 5-5. assistant의 응답도 채팅 기록에 추가 st.session_state.messages.append({"role": "assistant", "content": full_response})
Python
복사
3.스트림릿+opencv실습
import streamlit as st
import cv2
import numpy as np
from PIL import Image
import requests
# 1. 소개 문구 출력st.write("Streamlit은 컴퓨터 비전이나 자연어 처리와 같은 전통적인 머신러닝 분야에도 적합합니다. 👁️ \OpenCV를 활용한 엣지(윤곽선) 검출 예시입니다.")
# 2. 이미지 업로드 위젯 표시uploaded_file = st.file_uploader("이미지를 업로드하세요", type=["jpg", "jpeg", "png"])
# 3. 이미지 입력 처리if uploaded_file:
# 사용자가 업로드한 이미지를 열기 image = Image.open(uploaded_file)
else:
# 업로드하지 않은 경우, 샘플 이미지 URL에서 이미지 불러오기 image = Image.open(requests.get("https://picsum.photos/200/120", stream=True).raw)
# 4. 엣지(윤곽선) 검출 실행# - 이미지를 NumPy 배열로 변환한 후 Canny 엣지 검출 알고리즘 적용edges = cv2.Canny(np.array(image), 100, 200)
# 5. 탭 UI 생성 (탭 1: 윤곽선 이미지, 탭 2: 원본 이미지)tab1, tab2 = st.tabs(["윤곽선 검출 결과", "원본 이미지"])
# 6. 각 탭에 이미지 출력tab1.image(edges, use_column_width=True) # 엣지 이미지 출력tab2.image(image, use_column_width=True) # 원본 이미지 출력
Python
복사
4.스트림릿+지리공간
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
# 1. 소개 문구 출력st.write("Streamlit: 지리공간 데이터 시각화에서도 많이 사용됨\n \n",
"🌍 PyDeck, Folium, Kepler.gl 등을 지원\n ")
# 2. 샘플 지리 좌표 데이터 생성 (서울 중심으로 분포)chart_data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.56, 126.97],
columns=['lat', 'lon'])
# 3. pydeck 지도 시각화 구성st.pydeck_chart(pdk.Deck(
map_style=None, # 지도 기본 스타일 없음 (투명 배경) initial_view_state=pdk.ViewState( # 초기 뷰포트 설정 latitude=37.56, # 위도 (서울) longitude=126.97, # 경도 (서울) zoom=11, # 줌 레벨 pitch=50, # 지도 기울기 ),
layers=[
# 3-1. HexagonLayer: 3D 육각형 밀도 시각화 pdk.Layer(
'HexagonLayer',
data=chart_data,
get_position='[lon, lat]', # 위치 데이터 radius=200, # 육각형 크기 elevation_scale=4, # 높이 스케일 elevation_range=[0, 1000], # 높이 범위 pickable=True, # 클릭 가능 extruded=True, # 3D 효과 적용 ),
# 3-2. ScatterplotLayer: 점 형태의 산점도 표시 pdk.Layer(
'ScatterplotLayer',
data=chart_data,
get_position='[lon, lat]', # 위치 데이터 get_color='[200, 30, 0, 160]', # RGBA 색상 get_radius=200, # 점 크기 ),
],
))
Python
복사