接触到大模型后,会发现很多为了简化可视化,不需要像flask那般,直接借助python完成web界面的可视化,下面介绍几种库:
gradio | streamit | dash | |
---|---|---|---|
主要使用场景 | 可交互小 Demo | 工作流、DashBoard | DashBoard、生产环境的复杂演示应用 |
上手难度 | 简单 | 简单 | 中等 |
组件丰富度 | 低 | 高 | 高 |
综合扩展性 | 低 | 中 | 高 |
Jupyter Notebook 内支持 | 是 | 否 | 是 |
是否完全开源 | 是 | 是 | 部分企业级功能未开源 |
github stars | 13.4k | 23.1k | 18.2k |
案例列表 | https://github.com/gradio-app/awesome-demos | https://streamlit.io/gallery | https://dash.gallery/Portal/ |
安装: pip install gradio -i https://pypi.tuna.tsinghua.edu.cn/simple
使用:
Gradio 基于 svelte,官方文档Gradio, 提供两个类来构建应用程序UI:
Gradio的应用界面模块提供了不同的选择,根据开发者的需求和技术水平,可以选择使用gr.Interface进行简易场景的应用界面开发,或使用gr.Blocks进行更定制化的界面设计。其常见组件如下:
事件类型 | 触发条件 | 适用组件 |
---|---|---|
change |
用户完成输入或选择后触发 | Textbox, Slider, Dropdown, File, Image, Audio, Video |
input |
用户每次输入内容时触发 | Textbox, Slider |
click |
用户点击按钮时触发 | Button |
edit |
用户完成图像编辑时触发 | Image(编辑模式) |
submit |
用户按下回车键提交内容时触发 | Textbox, Textarea |
这些事件提供了丰富的动态交互支持,可以用来增强用户体验,实现高度个性化和实时交互的 Web 应用程序。
###基于gr.Interface
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(
fn=greet,
inputs=gr.Textbox(lines=2, placeholder="Name Here..."),
outputs="text",
)
demo.launch()
###基于gr.Blocks
####with gr.Tab分页, with gr.Accordion可折叠框,with gr.Row()行内显示
import numpy as np
import gradio as gr
def flip_text(x):
return x[::-1]
def flip_image(x):
return np.fliplr(x)
with gr.Blocks() as demo:
gr.Markdown("Flip text or image files using this demo.")
with gr.Tab("Flip Text"):
text_input = gr.Textbox()
text_output = gr.Textbox()
text_button = gr.Button("Flip")
with gr.Tab("Flip Image"):
with gr.Row():
image_input = gr.Image()
image_output = gr.Image()
image_button = gr.Button("Flip")
with gr.Accordion("Open for More!"):
gr.Markdown("Look at me...")
text_button.click(flip_text, inputs=text_input, outputs=text_output)
image_button.click(flip_image, inputs=image_input, outputs=image_output)
demo.launch()
具体使用可以参考:Gradio入门到进阶全网最详细教程[一]:快速搭建AI算法可视化部署演示(侧重项目搭建和案例分享) - 知乎
pip install streamit
streamit基于 React ,它的上手使用也非常之简单,下面是一个简单示例
import streamlit as st
import numpy as np
import pandas as pd
st.title("This is my first app")
# 有很多方式展示数据 (表格、数组、pandas的表格数据结构),magic方法、st.write()方法
# magic方法
st.write("magic方法使用")
df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
# pd.DataFrame( data, index, columns, dtype, copy)
# data数据,index 行标签,columns列标签 默认为np.arange(n),dtype 每一列数据类型,copy 能复制数据默认false
df # 每当Streamlit在自己的行中看到变量或文字值时,它都会使用st.write()自动将其写入您的应用程序。
# st.write()方法,可以自动渲染 文本、数据、Matplotlib图形、Altair图表等等。
st.write("write() 方法使用")
st.write(pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
}))
运行Streamlit的另一种方法是将其作为Python模块运行。这在配置 PyCharm 等 IDE 以使用 Streamlit 时很有用:
# Running
python -m streamlit run your_script.py
# is equivalent to:
streamlit run your_script.py
对其基础使用可以参考streamlit 入门之基本概念 - 知乎