streamlit:如何快速构建一个应用,不会前端也能写出好看的界面

作者 : admin 本文共7510个字,预计阅读时间需要19分钟 发布时间: 2024-06-10 共1人阅读

通过本文你可以了解到:

  • 如何安装streamlit,运行起来第一个demo
  • 熟悉streamlit的基本语法,常用的一些组件
  • 使用streamlit库构建应用

大模型学习参考:

  1. 大模型学习资料整理:如何从0到1学习大模型,搭建个人或企业RAG系统,如何评估与优化(更新中…)

欢迎大家访问个人博客网址:https://www.maogeshuo.com,博主努力更新中…

文章目录

  • 前言
  • streamlit 安装
  • streamlit组件介绍
    • 常用组件
    • 高级组件
  • 案例分享
    • 搭建简单对话界面
    • 使用Qwen大模型对话
      • 代码
      • 结果展示

前言

streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图

Streamlit是一个开源的Python框架,供数据科学家和AI/ML工程师使用,只需几行代码即可交付交互式数据应用程序。

官方文档地址:streamlit doc

经验:

  • 官方给出了非常多的组件使用案例,在编写代码时请结合官方文档+pycharm的代码提示+函数注释,函数注释中一班都给出了组件的具体使用
  • 修改完布局后,刷新访问网站,可以实时查看更改后的结果,无需重新streamlite run demo.py

streamlit 安装

pip install streamlit
streamlit hello

执行完streamlit hello后,点击 http://localhost:8501
streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图(1)
查看demo
streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图(2)

streamlit组件介绍

Streamlit是一个用于构建数据科学界面的Python库,它使得创建交互式应用程序变得非常简单。

常用组件

Streamlit 提供了一系列常用组件,用于构建交互式应用程序。以下是常见的 Streamlit 组件:

  1. st.write(): 用于在应用程序中显示文本、数据框架、图表等内容。

  2. st.title(): 添加应用程序的标题。

  3. st.header()st.subheader(): 添加标题和子标题。

  4. st.text(): 显示纯文本。

  5. st.markdown(): 使用 Markdown 语法添加格式化文本。

  6. st.image(): 显示图像。

  7. st.pyplot(): 显示 Matplotlib 图表。

  8. st.altair_chart(): 显示 Altair 图表。

  9. st.dataframe(): 显示数据框。

  10. st.table(): 显示表格。

  11. st.selectbox(): 显示下拉框,用户可以从选项中进行选择。

  12. st.multiselect(): 显示多选框,用户可以从选项中进行多选。

  13. st.slider(): 显示滑块,用户可以调整数值。

  14. st.text_input(): 显示文本输入框,用户可以输入文本。

  15. st.number_input(): 显示数字输入框,用户可以输入数字。

  16. st.text_area(): 显示多行文本输入框。

  17. st.checkbox(): 显示复选框,用户可以勾选或取消勾选。

  18. st.radio(): 显示单选按钮,用户可以从选项中进行单选。

  19. st.button(): 显示按钮,用户可以点击执行相关操作。

  20. st.file_uploader(): 显示文件上传器,用户可以上传文件。

  21. st.date_input()st.time_input(): 显示日期和时间输入框。

  22. st.color_picker(): 显示颜色选择器,用户可以选择颜色。

  23. st.spinner(): 显示加载状态的旋转器。

这些组件可以帮助你构建出功能丰富的交互式应用程序,根据需要选择合适的组件来实现你的应用程序功能。

下面是一些Streamlit中常用的组件及其简要介绍:

  1. st.title(): 用于添加应用程序的标题。

    import streamlit as st
    st.title('My Streamlit App')
    
  2. st.write(): 可以将文本、数据框架、图表等内容写入应用程序。

    st.write('Hello, world!')
    
  3. st.header()st.subheader(): 用于添加标题和子标题。

    st.header('This is a header')
    st.subheader('This is a subheader')
    
  4. st.text(): 显示纯文本。

    st.text('This is some text.')
    
  5. st.markdown(): 可以使用Markdown语法添加格式化文本。

    st.markdown('**This** is some Markdown *text*.')
    
  6. st.image(): 显示图像。

    from PIL import Image
    image = Image.open('example.jpg')
    st.image(image, caption='Sunset', use_column_width=True)
    
  7. st.pyplot()st.altair_chart(): 显示Matplotlib和Altair图表。

    import matplotlib.pyplot as plt
    plt.plot([1, 2, 3])
    st.pyplot()
    
    import altair as alt
    chart = alt.Chart(data).mark_bar().encode(
        x='category',
        y='count'
    )
    st.altair_chart(chart, use_container_width=True)
    
  8. st.dataframe(): 显示数据框。

    import pandas as pd
    df = pd.DataFrame({'Column 1': [1, 2, 3], 'Column 2': [4, 5, 6]})
    st.dataframe(df)
    
  9. st.selectbox(): 显示下拉框,用户可以从选项中进行选择。

    option = st.selectbox('Choose an option', ['Option 1', 'Option 2', 'Option 3'])
    
  10. st.slider(): 显示滑块,用户可以调整数值。

    value = st.slider('Select a value', 0, 100, 50)
    
  11. st.button(): 显示按钮,用户可以点击执行相关操作。

    if st.button('Click me'):
        st.write('Button clicked!')
    

这些是Streamlit中常用的一些组件,可以帮助你构建出功能丰富的交互式数据科学应用程序。

如上常用组件,运行代码streamlit run streamlit_hello.py:

import numpy as np
import streamlit as st
import pandas as pd
st.title('My Streamlit App')
st.write('Hello, world!')
st.header('This is a header')
st.subheader('This is a subheader')
st.text('This is some text.')
st.markdown('**This** is some Markdown *text*.')
from PIL import Image
image = Image.open('../data/stream_demo/onetwo.jpeg')
st.image(image, caption='Sunset', use_column_width=True)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
st.pyplot()
import altair as alt
chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
chart = alt.Chart(chart_data).mark_bar().encode(
x='category',
y='count'
)
c = (
alt.Chart(chart_data)
.mark_circle()
.encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"])
)
st.altair_chart(c, use_container_width=True)
df = pd.DataFrame({'Column 1': [1, 2, 3], 'Column 2': [4, 5, 6]})
st.dataframe(df)
option = st.selectbox('Choose an option', ['Option 1', 'Option 2', 'Option 3'])
value = st.slider('Select a value', 0, 100, 50)
if st.button('Click me'):
st.write('Button clicked!')

streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图(3)
streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图(4)

高级组件

在 Streamlit 中,除了 st.cache 之外,还有一些其他的缓存相关组件,如 st.cache_datast.cache_resource,它们分别用于缓存数据和资源,以下是它们的介绍:

  1. st.cache_data:

    • st.cache_data 用于缓存数据,通常用于将数据加载到内存中,并在应用程序的多个部分之间共享。这对于那些频繁访问的数据,例如配置文件、数据集等非常有用。
    • 使用方法与 st.cache 类似,你可以将需要缓存的数据加载函数与 @st.cache_data 装饰器一起使用。
    • st.cache 不同,st.cache_data 并不会保存函数的输入参数,它只会缓存函数的输出结果。因此,如果数据的加载方式不依赖于函数的输入参数,则可以使用 st.cache_data 来缓存数据。
  2. st.cache_resource:

    • st.cache_resource 用于缓存外部资源,例如文件、图像、音频等,通常用于减少重复的网络请求或文件读取操作。
    • 你可以使用 @st.cache_resource 装饰器来缓存资源加载函数,这样在多次访问同一资源时,Streamlit 将会从缓存中加载,而不是重新加载资源。
    • st.cachest.cache_data 类似,st.cache_resource 也可以接受参数,用于根据不同的参数值缓存不同的资源。

这些缓存组件提供了不同的功能,可以根据具体的需求选择合适的缓存方式。通过合理地使用缓存,可以显著提高 Streamlit 应用程序的性能和响应速度,同时减少资源消耗。

案例分享

搭建简单对话界面

import streamlit as st
if __name__ == '__main__':
st.title('Chat with me :sunflower:')
# 初始化history
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"])
# React to user input
if prompt := st.chat_input("Say something"):
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
response = f"Echo: {prompt}"
# Display assistant response in chat message container
with st.chat_message("assistant"):
st.markdown(response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})

streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图(5)

使用Qwen大模型对话

采用了Qwen大模型量化后的q2版本,具体参考代码,注释也比较全。

对话方式两种:

  • 普通输出
  • 流式输出

python库使用:

  • 基础库:os、sys、time
  • llama_cpp:加载大模型
  • dotenv:加载.env配置的环境变量

代码

import os
import sys
import time
import streamlit as st
from llama_cpp import Llama
from dotenv import load_dotenv, find_dotenv
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
# 加载env环境中内容
_ = load_dotenv(find_dotenv())
def get_llm_model(
prompt: str = None,
model: str = None,
temperature: float = 0.0,
max_token: int = 2048,
n_ctx: int = 512,
stream: bool = False):
"""
根据模型名称去加载模型,返回response数据
:param stream:
:param prompt:
:param model:
:param temperature:
:param max_token:
:param n_ctx:
:return:
"""
if model in ['Qwen_q2']:
model_path = os.environ[model]
llm = Llama(model_path=model_path, n_ctx=n_ctx)
start = time.time()
response = llm.create_chat_completion(
messages=[
{
"role": "system",
"content": "你是一个智能超级助手,请用专业的词语回答问题,整体上下文带有逻辑性,如果不知道,请不要乱说",
},
{
"role": "user",
"content": "{}".format(prompt)
},
],
temperature=temperature,
max_tokens=max_token,
stream=stream
)
cost = time.time() - start
print(f"模型生成时间:{cost}")
print(f"大模型回复:
{response}")
if not stream:
return response['choices'][0]['message']['content']
else:
return response
def get_llm_model_with_stream(
prompt: str = None,
model: str = None,
temperature: float = 0.0,
max_token: int = 2048,
n_ctx: int = 512,
stream: bool = True):
"""
流式输出结果
:param prompt:
:param model:
:param temperature:
:param max_token:
:param n_ctx:
:param stream:
:return:
"""
response = ""
start_time = time.time()
stream_results = get_llm_model(prompt, model, temperature, max_token, n_ctx, stream)
for res in stream_results:
content = res["choices"][0].get("delta", {}).get("content", "")
response += content
yield content
cost_time = time.time() - start_time
print(f"cost_time: {cost_time}, response: {response}")
if __name__ == '__main__':
st.title('Chat with Qwen :sunflower:')
# 初始化history
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"])
# React to user input
if prompt := st.chat_input("Say something"):
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# 普通方式输出
# if prompt is not None:
#     response = get_llm_model(prompt=prompt, model="Qwen_q2")
#     # Display assistant response in chat message container
#     with st.chat_message("assistant"):
#         st.markdown(response)
#     # Add assistant response to chat history
#     st.session_state.messages.append({"role": "assistant", "content": response})
# 流式输出
if prompt is not None:
stream_res = get_llm_model_with_stream(prompt=prompt, model="Qwen_q2")
with st.chat_message("assistant"):
content = st.write_stream(stream_res)
print("流式输出:", content)
st.session_state.messages.append({"role": "assistant", "content": content})
# streamlit run chat_with_qwen.py

结果展示

streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图(6)
streamlit:如何快速构建一个应用,不会前端也能写出好看的界面插图(7)

本站无任何商业行为
个人在线分享 » streamlit:如何快速构建一个应用,不会前端也能写出好看的界面
E-->