文章目录 Gradio 基础使用示例 简介 安装 示例-简单的输入、输出 示例-启动配置 示例-聊天对话 示例-多页面Tab切换 示例-使用Block自定义布局 示例-Plot绘图 示例-状态管理 示例-提示、进度条 参考
Gradio 基础使用示例
简介
Gradio 是一个用于构建快速原型和部署机器学习应用程序的开源库。它的目标是使机器学习模型的创建和部署变得简单易用,无需深入了解 Web 开发或前端知识。 以下是 Gradio 的一些关键特点和优势: 简单易用 : Gradio 提供了简单直观的 API,使得用户能够快速创建交互式的机器学习界面,无需繁琐的代码编写。多样化输入输出 : Gradio 支持多种类型的输入和输出,包括图像、文本、音频等,同时还能够处理多个输入和输出。即时预览 : 在开发过程中,Gradio 提供了即时预览功能,让用户可以实时查看和测试他们的应用程序,以便进行调试和优化。部署简单 : Gradio 允许用户一键部署他们的应用程序,无需复杂的配置或部署流程,可以将应用程序轻松地分享给其他人使用。可定制性 : 尽管 Gradio 提供了许多预定义的组件和样式,但用户仍然可以通过自定义 CSS 和 JavaScript 来定制界面的外观和行为。跨平台兼容性 : Gradio 可以在多个平台上运行,包括本地环境、云端服务器以及基于 Docker 的容器中。 总的来说,Gradio 提供了一个简单而强大的工具,使得任何人都能够轻松地构建和部署交互式的机器学习应用程序,从而促进了机器学习技术的普及和应用。 当然,你也可以用Gradio来做一些简单功能的可视化,以便于日常使用,不是非要应用到AI方面。
安装
$ pip install gradio==4.29 -i "https://pypi.doubanio.com/simple/"
当前安装的版本信息,输出如下
Successfully installed aiofiles-23.2.1 altair-5.3.0 attrs-23.2.0 contourpy-1.2.1 cycler-0.12.1 ffmpy-0.3.2 filelock-3.14.0 fonttools-4.51.0 fsspec-2024.3.1 gradio-4.29.0 gradio-client-0.16.1 httpcore-1.0.5 httpx-0.27.0 huggingface-hub-0.23.0 importlib-resources-6.4.0 jsonschema-4.22.0 jsonschema-specifications-2023.12.1 kiwisolver-1.4.5 markdown-it-py-3.0.0 matplotlib-3.8.4 mdurl-0.1.2 orjson-3.10.3 pillow-10.3.0 pydub-0.25.1 pygments-2.18.0 pyparsing-3.1.2 python-multipart-0.0.9 referencing-0.35.1 requests-2.31.0 rich-13.7.1 rpds-py-0.18.1 ruff-0.4.3 semantic-version-2.10.0 shellingham-1.5.4 tomlkit-0.12.0 typer-0.12.3 urllib3-2.2.1 websockets-11.0.3
示例-简单的输入、输出
import gradio as grprint ( gr. __version__) def process_data ( text, image, filter_type) : print ( type ( image) ) processed_text = text. upper( ) if filter_type: image = image. convert( filter_type) return processed_text, imageiface = gr. Interface( fn= process_data, inputs= [ gr. Textbox( label= "输入文本" ) , gr. Image( label= "上传图片" , type = "pil" ) , gr. Radio( label= "图像转换模式" , info= "参考 https://blog.csdn.net/u012977885/article/details/105733554" , choices= [ "1" , "L" , "P" , "RGB" , "RGBA" , "CMYK" , "YCbCr" , "I" , "F" ] , value= "L" ) , ] , outputs= [ gr. Text( label= "处理后的文本" ) , gr. Image( label= "处理后的图片" ) ] , title= "文本、图像处理" , description= "输入文本、图像,以获得处理。" ,
) iface. launch( )
示例-启动配置
iface. launch( server_name= '127.0.0.1' , server_port= 8080 , show_error= True )
iface. launch( auth= ( "admin" , "admin12345" ) )
def my_auth ( username, password) : return username == "admin" and password == "admin12345"
iface. launch( auth= my_auth, auth_message= "login error" )
iface. launch( share= True )
示例-聊天对话
聊天接口 通过使用yield
,可以实现流式响应 Streaming outputs
import gradio as gr
import timeprint ( gr. __version__) def slow_echo ( message, history) : for i in range ( len ( message) ) : time. sleep( 0.05 ) yield "机器人回复: " + message[ : i+ 1 ] iface = gr. ChatInterface( slow_echo) . queue( ) iface. launch( )
示例-多页面Tab切换
import gradio as gr
import timedef function1 ( input1) : return f"处理结果: { input1} " def function2 ( input2) : return f"分析结果: { input2} " iface1 = gr. Interface( function1, "text" , "text" )
iface2 = gr. Interface( function2, "text" , "text" ) tabbed_interface = gr. TabbedInterface( [ iface1, iface2] , [ "界面1" , "界面2" ] )
tabbed_interface. launch( )
import gradio as gr
import timedef process_data ( text, image, filter_type) : print ( type ( image) ) processed_text = text. upper( ) if filter_type: image = image. convert( filter_type) return processed_text, imagebase_iface = gr. Interface( fn= process_data, inputs= [ gr. Textbox( label= "输入文本" ) , gr. Image( label= "上传图片" , type = "pil" ) , gr. Radio( label= "图像转换模式" , info= "参考 https://blog.csdn.net/u012977885/article/details/105733554" , choices= [ "1" , "L" , "P" , "RGB" , "RGBA" , "CMYK" , "YCbCr" , "I" , "F" ] , value= "L" ) , ] , outputs= [ gr. Text( label= "处理后的文本" ) , gr. Image( label= "处理后的图片" ) ] , title= "文本、图像处理" , description= "输入文本、图像,以获得处理。" ,
) def slow_echo ( message, history) : for i in range ( len ( message) ) : time. sleep( 0.05 ) yield "机器人回复: " + message[ : i+ 1 ] chat_iface = gr. ChatInterface( slow_echo) . queue( ) tabbed_interface = gr. TabbedInterface( [ base_iface, chat_iface] , [ "基础界面" , "聊天界面" ] )
tabbed_interface. launch( )
示例-使用Block自定义布局
import gradio as gr
import timedef process_data ( text, image, filter_type) : print ( type ( image) ) processed_text = text. upper( ) if filter_type: image = image. convert( filter_type) return processed_text, imagebase_iface = gr. Interface( fn= process_data, inputs= [ gr. Textbox( label= "输入文本" ) , gr. Image( label= "上传图片" , type = "pil" ) , gr. Radio( label= "图像转换模式" , info= "参考 https://blog.csdn.net/u012977885/article/details/105733554" , choices= [ "1" , "L" , "P" , "RGB" , "RGBA" , "CMYK" , "YCbCr" , "I" , "F" ] , value= "L" ) , ] , outputs= [ gr. Text( label= "处理后的文本" ) , gr. Image( label= "处理后的图片" ) ] , title= "文本、图像处理" , description= "输入文本、图像,以获得处理。" ,
) def slow_echo ( message, history) : for i in range ( len ( message) ) : time. sleep( 0.05 ) yield "机器人回复: " + message[ : i+ 1 ] chat_iface = gr. ChatInterface( slow_echo) . queue( ) with gr. Blocks( ) as block1_iface: with gr. Row( ) : with gr. Column( ) : input_text = gr. Textbox( label= "输入" ) submit_button = gr. Button( "提交" ) with gr. Column( ) : output_text = gr. Label( label= "输出" ) submit_button. click( fn= lambda x: f"你输入了: { x} " , inputs= input_text, outputs= output_text) with gr. Blocks( ) as block2_iface: with gr. Group( ) : input1 = gr. Textbox( ) input2 = gr. Slider( ) with gr. Accordion( "详细设置" ) : checkbox = gr. Checkbox( label= "选项" ) dropdown = gr. Dropdown( choices= [ "选项1" , "选项2" ] ) submit_button = gr. Button( "提交" ) output_label = gr. Label( ) submit_button. click( fn= lambda x, y, z: f" { x} , { y} , { z} " , inputs= [ input1, input2, checkbox] , outputs= output_label) with gr. Blocks( ) as block3_iface: with gr. Row( ) : with gr. Column( ) : input_text = gr. Textbox( label= "输入文本" ) with gr. Group( ) : input_image = gr. Image( label= "上传图片" , type = "pil" ) input_mode = gr. Radio( label= "图像转换模式" , info= "参考 https://blog.csdn.net/u012977885/article/details/105733554" , choices= [ "1" , "L" , "P" , "RGB" , "RGBA" , "CMYK" , "YCbCr" , "I" , "F" ] , value= "L" ) submit_button = gr. Button( "提交" ) with gr. Column( ) : output_text = gr. Text( label= "处理后的文本" ) output_image = gr. Image( label= "处理后的图片" ) submit_button. click( fn= process_data, inputs= [ input_text, input_image, input_mode] , outputs= [ output_text, output_image] ) tabbed_interface = gr. TabbedInterface( [ base_iface, chat_iface, block1_iface, block2_iface, block3_iface] , [ "基础界面" , "聊天界面" , "Block1界面" , "Block2界面" , "Block3界面" ]
)
tabbed_interface. launch( )
示例-Plot绘图
import gradio as gr
import pandas as pd
import plotly. express as px
import matplotlib. pyplot as pltdef explore_data ( dataset, columns) : df = pd. read_csv( dataset) fig = plt. figure( ) plt. scatter( df[ columns[ 0 ] ] , df[ columns[ 1 ] ] ) plt. xlabel( columns[ 0 ] ) plt. ylabel( columns[ 1 ] ) return figdemo = gr. Interface( fn= explore_data, inputs= [ gr. File( label= "上传CSV文件" ) , gr. CheckboxGroup( choices= [ "num" , "age" , "tall" ] , label= "选择列" ) , ] , outputs= gr. Plot( ) ,
)
demo. launch( )
import gradio as gr
import pandas as pd
import seaborn as sns
import matplotlib. pyplot as pltdef plot_data ( file , chart_type) : df = pd. read_csv( file ) if chart_type == "柱状图" : plt. figure( figsize= ( 10 , 6 ) ) sns. barplot( data= df) elif chart_type == "折线图" : plt. figure( figsize= ( 10 , 6 ) ) sns. lineplot( data= df) plt. tight_layout( ) return pltiface = gr. Interface( plot_data, inputs= [ gr. File( ) , gr. Dropdown( [ "柱状图" , "折线图" ] ) ] , outputs= "plot"
)
iface. launch( )
示例-状态管理
每次点击Submit,状态值都会变 官方文档 https://www.gradio.app/guides/interface-state
import gradio as grdef update_output ( input_text, state_obj) : state_obj = state_obj or 0 state_obj += 1 return f"您输入了: { input_text} " , f"状态值: { state_obj} " , state_obj
iface = gr. Interface( fn= update_output, inputs= [ gr. Textbox( ) , gr. State( ) ] , outputs= [ gr. Textbox( ) , gr. Label( ) , gr. State( ) ]
)
iface. launch( )
示例-提示、进度条
来自官方 https://www.gradio.app/guides/key-features#alert-modals https://www.gradio.app/guides/key-features#progress-bars 提示(info、warning、error)
def start_process ( name) : gr. Info( "Starting process" ) if name is None : gr. Warning( "Name is empty" ) . . . if success == False : raise gr. Error( "Process failed" )
import gradio as gr
import timedef slowly_reverse ( word, progress= gr. Progress( ) ) : progress( 0 , desc= "Starting" ) time. sleep( 1 ) progress( 0.05 ) new_string = "" for letter in progress. tqdm( word, desc= "Reversing" ) : time. sleep( 0.25 ) new_string = letter + new_stringreturn new_stringdemo = gr. Interface( slowly_reverse, gr. Text( ) , gr. Text( ) ) demo. launch( )
进度条(通过设置gr.Progress(track_tqdm=True)
,自动追踪tqdm
,显示进度)
import gradio as gr
import time
import tqdm
def slowly_reverse2 ( word, progress= gr. Progress( track_tqdm= True ) ) : time. sleep( 1 ) new_string = "" tqdm_progress = tqdm. tqdm( word, desc= "Reversing" ) for letter in tqdm_progress: time. sleep( 0.25 ) new_string = letter + new_stringreturn new_stringdemo = gr. Interface( slowly_reverse2, gr. Text( ) , gr. Text( ) ) demo. launch( )
参考
官方文档 https://www.gradio.app/guides/key-features 一文搞懂模型展示工具Gradio的所有功能 Gradio入门到进阶全网最详细教程[一]:快速搭建AI算法可视化部署演示(侧重项目搭建和案例分享)