Streamlit是一个用于机器学习、数据可视化的 Python 框架,它能几行代码就构建出一个精美的在线 app 应用。相比于Gradio它有更强大的功能。

# 安装
pip install streamlit
pip install streamlit-chat
# 测试
streamlit hello
Local URL: http://localhost:8501
Network URL: http://192.168.3.41:8501
Ready to create your own Python apps super quickly?
Head over to https://docs.streamlit.io
May you create awesome apps!
会出现一些案例:

import streamlit as st
最常用的几种
实时读取数据并作图。
app.py
import streamlit as st
import pandas as pd
import numpy as np
st.title('Uber pickups in NYC')
DATE_COLUMN = 'Date/Time'
DATA_URL = ('./data/uber-raw-data-sep14.csv')
# 增加缓存
@st.cache_data
# 下载数据函数
def load_data(nrows):
# 读取csv文件
data = pd.read_csv(DATA_URL, nrows=nrows)
# 将数据以panda的数据列的形式展示出来
data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])
# 返回最终数据
return data
# 直接打印文本信息
data_load_state = st.text('正在下载')
# 下载一万条数据中的数据
data = load_data(10000)
# 最后输出文本显示
data_load_state.text("完成!(using st.cache_data)")
# 检查原始数据
if st.checkbox('Show raw data'):
st.subheader('Raw data')
st.write(data)
# 绘制直方图
# 添加一个子标题
st.subheader('Number of pickups by hour')
# 使用numpy生成一个直方图,按小时排列
hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0, 24))[0]
# 使用Streamlit 的 st.bar_chart() 方法来绘制直方图
st.bar_chart(hist_values)
# 使用滑动块筛选结果
hour_to_filter = st.slider('hour', 0, 23, 17)
# 实时更新
filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter]
# 为地图添加一个副标题
st.subheader('Map of all pickups at %s:00' % hour_to_filter)
# 使用st.map()函数绘制数据
st.map(filtered_data)
运行
streamlit run app.py

其中uber-raw-data-sep14.csv数据集下载地址如下:
链接:https://pan.baidu.com/s/1vv_TP5o_jgwXJqsP3158QA 提取码:9527
import cv2
import streamlit as st
import numpy as np
from PIL import Image
def brighten_image(image, amount):
img_bright = cv2.convertScaleAbs(image, beta=amount)
return img_bright
def blur_image(image, amount):
blur_img = cv2.GaussianBlur(image, (11, 11), amount)
return blur_img
def enhance_details(img):
hdr = cv2.detailEnhance(img, sigma_s=12, sigma_r=0.15)
return hdr
def main_loop():
st.title("OpenCV Demo App")
st.subheader("This app allows you to play with Image filters!")
st.text("We use OpenCV and Streamlit for this demo")
blur_rate = st.sidebar.slider("Blurring", min_value=0.5, max_value=5.0)
brightness_amount = st.sidebar.slider("Brightness", min_value=-50, max_value=50, value=0)
apply_enhancement_filter = st.sidebar.checkbox('Enhance Details')
image_file = st.file_uploader("Upload Your Image", type=['jpg', 'png', 'jpeg'])
if not image_file:
return None
original_image = Image.open(image_file)
original_image = np.array(original_image)
processed_image = blur_image(original_image, blur_rate)
processed_image = brighten_image(processed_image, brightness_amount)
if apply_enhancement_filter:
processed_image = enhance_details(processed_image)
st.text("Original Image vs Processed Image")
st.image([original_image, processed_image])
if __name__ == '__main__':
main_loop()
运行效果:

在上一节的基于FastAPI构建聊天机器人的基础上使用Streamlit-UI构建聊天界面。
为了保证兼容性,推荐安装以下版本的streamlit。
pip install streamlit==1.39.0
代码实现:
streamlitui_robot_chat.py
import streamlit as st
import requests
# 定义fastapi后端服务器地址
backend_url = "http://127.0.0.1:6066/chat"
# 设计页面
st.set_page_config(page_title="ChatBot", layout="centered")
# 设计聊天对话框
st.title("基于Streamlit的聊天机器人")
def clear_chat_history():
st.session_state.history = []
# st.sidebar负责设计侧边栏
with st.sidebar:
st.title("ChatBot")
sys_prompt = st.text_input("系统提示词:", value="You are a helpful assistant.")
history_len = st.slider("保留历史对话的数量:", min_value=1, max_value=10, value=1, step=1)
temperature = st.slider("temperature:", min_value=0.01, max_value=2.0, value=0.5, step=0.01)
top_p = st.slider("top_p:", min_value=0.01, max_value=1.0, value=0.5, step=0.01)
max_tokens = st.slider("max_tokens:", min_value=256, max_value=4096, value=1024, step=8)
stream = st.checkbox("stream", value=True)
st.button("清空聊天历史", on_click=clear_chat_history)
# 定义存储历史
if "history" not in st.session_state:
st.session_state.history = []
# 显示聊天历史
for messgae in st.session_state.history:
with st.chat_message(messgae["role"]):
st.markdown(messgae["content"])
# 输入框
# 海象运算符(:=), 用于检查赋值的内容(prompt)是否为空
if prompt := st.chat_input("来和我聊天~~~"):
# 显示用户消息
with st.chat_message("user"):
st.markdown(prompt)
# 构建请求数据
data = {
"query": prompt,
"sys_prompt": sys_prompt,
"history_len": history_len,
"history": st.session_state.history,
"temperature": temperature,
"top_p": top_p,
"max_tokens": max_tokens
}
# 发送请求到fastapi后端
response = requests.post(backend_url, json=data, stream=True)
if response.status_code == 200:
chunks = ""
assistant_placeholder = st.chat_message("assistant")
assistant_text = assistant_placeholder.markdown("")
if stream: # 流式输出
for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
# 处理响应的内容,并累加起来
chunks += chunk
# 实时显示和更新助手的消息
assistant_text.markdown(chunks)
else:
for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
chunks += chunk
assistant_text.markdown(chunks)
st.session_state.history.append({"role": "user", "content": prompt})
st.session_state.history.append({"role": "assistant", "content": chunks})
分别启动vLLM推理服务器和FastAPI后端聊天接口。然后输入以下命令,启动聊天界面:
streamlit run streamlitui_robot_chat.py
运行效果:
