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

守听  金牌会员 | 2024-8-20 06:25:03 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 551|帖子 551|积分 1653

通过本文你可以了解到:
  

  • 如何安装streamlit,运行起来第一个demo
  • 熟悉streamlit的基本语法,常用的一些组件
  • 利用streamlit库构建应用
    大模型学习参考:
  

  • 大模型学习资料整理:如何从0到1学习大模型,搭建个人或企业RAG系统,如何评估与优化(更新中…)
    欢迎大家访问个人博客网址:https://www.maogeshuo.com,博主积极更新中…
  
  
媒介


Streamlit是一个开源的Python框架,供数据科学家和AI/ML工程师利用,只需几行代码即可交付交互式数据应用步伐。
官方文档所在:streamlit doc
经验:


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

  1. pip install streamlit
  2. streamlit hello
复制代码
实行完streamlit hello后,点击 http://localhost:8501

查看demo

streamlit组件介绍

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

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

  • st.write(): 用于在应用步伐中表现文本、数据框架、图表等内容。
  • st.title(): 添加应用步伐的标题。
  • st.header()st.subheader(): 添加标题和子标题。
  • st.text(): 表现纯文本。
  • st.markdown(): 利用 Markdown 语法添加格式化文本。
  • st.image(): 表现图像。
  • st.pyplot(): 表现 Matplotlib 图表。
  • st.altair_chart(): 表现 Altair 图表。
  • st.dataframe(): 表现数据框。
  • st.table(): 表现表格。
  • st.selectbox(): 表现下拉框,用户可以从选项中进行选择。
  • st.multiselect(): 表现多选框,用户可以从选项中进行多选。
  • st.slider(): 表现滑块,用户可以调整数值。
  • st.text_input(): 表现文本输入框,用户可以输入文本。
  • st.number_input(): 表现数字输入框,用户可以输入数字。
  • st.text_area(): 表现多行文本输入框。
  • st.checkbox(): 表现复选框,用户可以勾选或取消勾选。
  • st.radio(): 表现单选按钮,用户可以从选项中进行单选。
  • st.button(): 表现按钮,用户可以点击实行相关操纵。
  • st.file_uploader(): 表现文件上传器,用户可以上传文件。
  • st.date_input()st.time_input(): 表现日期和时间输入框。
  • st.color_picker(): 表现颜色选择器,用户可以选择颜色。
  • st.spinner(): 表现加载状态的旋转器。
这些组件可以资助你构建出功能丰富的交互式应用步伐,根据需要选择合适的组件来实现你的应用步伐功能。
下面是一些Streamlit中常用的组件及其简要介绍:

  • st.title(): 用于添加应用步伐的标题。
    1. import streamlit as st
    2. st.title('My Streamlit App')
    复制代码
  • st.write(): 可以将文本、数据框架、图表等内容写入应用步伐。
    1. st.write('Hello, world!')
    复制代码
  • st.header()st.subheader(): 用于添加标题和子标题。
    1. st.header('This is a header')
    2. st.subheader('This is a subheader')
    复制代码
  • st.text(): 表现纯文本。
    1. st.text('This is some text.')
    复制代码
  • st.markdown(): 可以利用Markdown语法添加格式化文本。
    1. st.markdown('**This** is some Markdown *text*.')
    复制代码
  • st.image(): 表现图像。
    1. from PIL import Image
    2. image = Image.open('example.jpg')
    3. st.image(image, caption='Sunset', use_column_width=True)
    复制代码
  • st.pyplot()st.altair_chart(): 表现Matplotlib和Altair图表。
    1. import matplotlib.pyplot as plt
    2. plt.plot([1, 2, 3])
    3. st.pyplot()
    4. import altair as alt
    5. chart = alt.Chart(data).mark_bar().encode(
    6.     x='category',
    7.     y='count'
    8. )
    9. st.altair_chart(chart, use_container_width=True)
    复制代码
  • st.dataframe(): 表现数据框。
    1. import pandas as pd
    2. df = pd.DataFrame({'Column 1': [1, 2, 3], 'Column 2': [4, 5, 6]})
    3. st.dataframe(df)
    复制代码
  • st.selectbox(): 表现下拉框,用户可以从选项中进行选择。
    1. option = st.selectbox('Choose an option', ['Option 1', 'Option 2', 'Option 3'])
    复制代码
  • st.slider(): 表现滑块,用户可以调整数值。
    1. value = st.slider('Select a value', 0, 100, 50)
    复制代码
  • st.button(): 表现按钮,用户可以点击实行相关操纵。
    1. if st.button('Click me'):
    2.     st.write('Button clicked!')
    复制代码
这些是Streamlit中常用的一些组件,可以资助你构建出功能丰富的交互式数据科学应用步伐。
如上常用组件,运行代码streamlit run streamlit_hello.py:
  1. import numpy as npimport streamlit as stimport pandas as pdst.title('My Streamlit App')st.write('Hello, world!')
  2. st.header('This is a header')
  3. st.subheader('This is a subheader')
  4. st.text('This is some text.')
  5. st.markdown('**This** is some Markdown *text*.')
  6. from PIL import Imageimage = Image.open('../data/stream_demo/onetwo.jpeg')st.image(image, caption='Sunset', use_column_width=True)import matplotlib.pyplot as pltplt.plot([1, 2, 3])st.pyplot()import altair as altchart_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'])
  7. value = st.slider('Select a value', 0, 100, 50)
  8. if st.button('Click me'):
  9.     st.write('Button clicked!')
复制代码


高级组件

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

  • st.cache_data:

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

  • st.cache_resource:

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

这些缓存组件提供了不同的功能,可以根据详细的需求选择合适的缓存方式。通过合理地利用缓存,可以明显提高 Streamlit 应用步伐的性能和相应速率,同时减少资源斲丧。
案例分享

搭建简单对话界面

  1. import streamlit as st
  2. if __name__ == '__main__':
  3.     st.title('Chat with me :sunflower:')
  4.     # 初始化history
  5.     if "messages" not in st.session_state:
  6.         st.session_state.messages = []
  7.     # 展示对话
  8.     for msg in st.session_state.messages:
  9.         with st.chat_message(msg['role']):
  10.             st.markdown(msg["content"])
  11.     # React to user input
  12.     if prompt := st.chat_input("Say something"):
  13.         # Display user message in chat message container
  14.         with st.chat_message("user"):
  15.             st.markdown(prompt)
  16.         # Add user message to chat history
  17.         st.session_state.messages.append({"role": "user", "content": prompt})
  18.     response = f"Echo: {prompt}"
  19.     # Display assistant response in chat message container
  20.     with st.chat_message("assistant"):
  21.         st.markdown(response)
  22.     # Add assistant response to chat history
  23.     st.session_state.messages.append({"role": "assistant", "content": response})
复制代码

利用Qwen大模型对话

采用了Qwen大模型量化后的q2版本,详细参考代码,注释也比力全。
对话方式两种:


  • 平凡输出
  • 流式输出
python库利用:


  • 底子库:os、sys、time
  • llama_cpp:加载大模型
  • dotenv:加载.env配置的情况变量
代码

  1. import os
  2. import sys
  3. import time
  4. import streamlit as st
  5. from llama_cpp import Llama
  6. from dotenv import load_dotenv, find_dotenv
  7. BASE_DIR = os.path.dirname(__file__)
  8. sys.path.append(BASE_DIR)
  9. # 加载env环境中内容
  10. _ = load_dotenv(find_dotenv())
  11. def get_llm_model(
  12.         prompt: str = None,
  13.         model: str = None,
  14.         temperature: float = 0.0,
  15.         max_token: int = 2048,
  16.         n_ctx: int = 512,
  17.         stream: bool = False):
  18.     """
  19.     根据模型名称去加载模型,返回response数据
  20.     :param stream:
  21.     :param prompt:
  22.     :param model:
  23.     :param temperature:
  24.     :param max_token:
  25.     :param n_ctx:
  26.     :return:
  27.     """
  28.     if model in ['Qwen_q2']:
  29.         model_path = os.environ[model]
  30.         llm = Llama(model_path=model_path, n_ctx=n_ctx)
  31.         start = time.time()
  32.         response = llm.create_chat_completion(
  33.             messages=[
  34.                 {
  35.                     "role": "system",
  36.                     "content": "你是一个智能超级助手,请用专业的词语回答问题,整体上下文带有逻辑性,如果不知道,请不要乱说",
  37.                 },
  38.                 {
  39.                     "role": "user",
  40.                     "content": "{}".format(prompt)
  41.                 },
  42.             ],
  43.             temperature=temperature,
  44.             max_tokens=max_token,
  45.             stream=stream
  46.         )
  47.         cost = time.time() - start
  48.         print(f"模型生成时间:{cost}")
  49.         print(f"大模型回复:\n{response}")
  50.         if not stream:
  51.             return response['choices'][0]['message']['content']
  52.         else:
  53.             return response
  54. def get_llm_model_with_stream(
  55.         prompt: str = None,
  56.         model: str = None,
  57.         temperature: float = 0.0,
  58.         max_token: int = 2048,
  59.         n_ctx: int = 512,
  60.         stream: bool = True):
  61.     """
  62.     流式输出结果
  63.     :param prompt:
  64.     :param model:
  65.     :param temperature:
  66.     :param max_token:
  67.     :param n_ctx:
  68.     :param stream:
  69.     :return:
  70.     """
  71.     response = ""
  72.     start_time = time.time()
  73.     stream_results = get_llm_model(prompt, model, temperature, max_token, n_ctx, stream)
  74.     for res in stream_results:
  75.         content = res["choices"][0].get("delta", {}).get("content", "")
  76.         response += content
  77.         yield content
  78.     cost_time = time.time() - start_time
  79.     print(f"cost_time: {cost_time}, response: {response}")
  80. if __name__ == '__main__':
  81.     st.title('Chat with Qwen :sunflower:')
  82.     # 初始化history
  83.     if "messages" not in st.session_state:
  84.         st.session_state.messages = []
  85.     # 展示对话
  86.     for msg in st.session_state.messages:
  87.         with st.chat_message(msg['role']):
  88.             st.markdown(msg["content"])
  89.     # React to user input
  90.     if prompt := st.chat_input("Say something"):
  91.         # Display user message in chat message container
  92.         with st.chat_message("user"):
  93.             st.markdown(prompt)
  94.         # Add user message to chat history
  95.         st.session_state.messages.append({"role": "user", "content": prompt})
  96.     # 普通方式输出
  97.     # if prompt is not None:
  98.     #     response = get_llm_model(prompt=prompt, model="Qwen_q2")
  99.     #     # Display assistant response in chat message container
  100.     #     with st.chat_message("assistant"):
  101.     #         st.markdown(response)
  102.     #     # Add assistant response to chat history
  103.     #     st.session_state.messages.append({"role": "assistant", "content": response})
  104.     # 流式输出
  105.     if prompt is not None:
  106.         stream_res = get_llm_model_with_stream(prompt=prompt, model="Qwen_q2")
  107.         with st.chat_message("assistant"):
  108.             content = st.write_stream(stream_res)
  109.         print("流式输出:", content)
  110.         st.session_state.messages.append({"role": "assistant", "content": content})
  111. # streamlit run chat_with_qwen.py
复制代码
结果展示




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

守听

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表