通过本文你可以了解到:
- 如何安装streamlit,运行起来第一个demo
- 熟悉streamlit的基本语法,常用的一些组件
- 利用streamlit库构建应用
大模型学习参考:
- 大模型学习资料整理:如何从0到1学习大模型,搭建个人或企业RAG系统,如何评估与优化(更新中…)
欢迎大家访问个人博客网址:https://www.maogeshuo.com,博主积极更新中…
媒介
Streamlit是一个开源的Python框架,供数据科学家和AI/ML工程师利用,只需几行代码即可交付交互式数据应用步伐。
官方文档所在:streamlit doc
经验:
- 官方给出了非常多的组件利用案例,在编写代码时请结合官方文档+pycharm的代码提示+函数注释,函数注释中一班都给出了组件的详细利用
- 修改完结构后,刷新访问网站,可以实时查看更改后的结果,无需重新streamlite run demo.py
streamlit 安装
- pip install streamlit
- 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(): 用于添加应用步伐的标题。
- import streamlit as st
- st.title('My Streamlit App')
复制代码 - st.write(): 可以将文本、数据框架、图表等内容写入应用步伐。
- st.write('Hello, world!')
复制代码 - st.header() 和 st.subheader(): 用于添加标题和子标题。
- st.header('This is a header')
- st.subheader('This is a subheader')
复制代码 - st.text(): 表现纯文本。
- st.text('This is some text.')
复制代码 - st.markdown(): 可以利用Markdown语法添加格式化文本。
- st.markdown('**This** is some Markdown *text*.')
复制代码 - st.image(): 表现图像。
- from PIL import Image
- image = Image.open('example.jpg')
- st.image(image, caption='Sunset', use_column_width=True)
复制代码 - 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)
复制代码 - st.dataframe(): 表现数据框。
- import pandas as pd
- df = pd.DataFrame({'Column 1': [1, 2, 3], 'Column 2': [4, 5, 6]})
- st.dataframe(df)
复制代码 - st.selectbox(): 表现下拉框,用户可以从选项中进行选择。
- option = st.selectbox('Choose an option', ['Option 1', 'Option 2', 'Option 3'])
复制代码 - st.slider(): 表现滑块,用户可以调整数值。
- value = st.slider('Select a value', 0, 100, 50)
复制代码 - st.button(): 表现按钮,用户可以点击实行相关操纵。
- if st.button('Click me'):
- st.write('Button clicked!')
复制代码 这些是Streamlit中常用的一些组件,可以资助你构建出功能丰富的交互式数据科学应用步伐。
如上常用组件,运行代码streamlit run streamlit_hello.py:
- import numpy as npimport streamlit as stimport pandas as pdst.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 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'])
- value = st.slider('Select a value', 0, 100, 50)
- if st.button('Click me'):
- 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 应用步伐的性能和相应速率,同时减少资源斲丧。
案例分享
搭建简单对话界面
- 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})
复制代码
利用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"大模型回复:\n{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
复制代码 结果展示
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |