ToB企服应用市场:ToB评测及商务社交产业平台

标题: streamlit:如何快速构建一个应用,不会前端也能写出好看的界面 [打印本页]

作者: 守听    时间: 2024-8-20 06:25
标题: streamlit:如何快速构建一个应用,不会前端也能写出好看的界面
通过本文你可以了解到:
  
    大模型学习参考:
      欢迎大家访问个人博客网址:https://www.maogeshuo.com,博主积极更新中…
  
  
媒介


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

streamlit 安装

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

查看demo

streamlit组件介绍

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

Streamlit 提供了一系列常用组件,用于构建交互式应用步伐。以下是常见的 Streamlit 组件:
这些组件可以资助你构建出功能丰富的交互式应用步伐,根据需要选择合适的组件来实现你的应用步伐功能。
下面是一些Streamlit中常用的组件及其简要介绍:
这些是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,它们分别用于缓存数据和资源,以下是它们的介绍:
这些缓存组件提供了不同的功能,可以根据详细的需求选择合适的缓存方式。通过合理地利用缓存,可以明显提高 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库利用:

代码

  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企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4