Gradio: 快速构建你的 webApp
如果你了解 web 开发,一定会知道开发一款 webApp 需要涉及很多技术栈:前端:HTML + CSS + JS (可能会涉及不同的 CSS 框架和 JS 框架如 jquery VUE react 等)后端语言:如 python/javaweb 容器:如 flask/tomcat如果你只会 python,又不想重头学习上述技术,你要怎么办?据我所知,有两种解决方案:streamlit 之前我有
原文:Gradio:快速构建你的webApp_Python_AIWeker_InfoQ写作社区

1. 什么是 Gradio
如果你了解 web 开发,一定会知道开发一款 webApp 需要涉及很多技术栈:
-
前端:HTML + CSS + JS (可能会涉及不同的 CSS 框架和 JS 框架如 jquery VUE react 等)
-
后端语言:如 python/java
-
web 容器:如 flask/tomcat
如果你只会 python,又不想重头学习上述技术,你要怎么办?
据我所知,有两种解决方案:
-
streamlit (https://streamlit.io/)
-
Gradio (https://gradio.app/)
streamlit 之前我有介绍过,今天要分享的是Gradio, 提供的功能和 streamlit 类似,你只要会 python 就可以快速构建一个 webApp。

从上图可知,Gradio 定位是快速构建一个针对人工智能的 python 的 webApp 库,在 Hugging Face 等提供各种模型推理展示的平台广告使用,阿里的魔塔展示也是基于此。
大家思考下,Gradio 作为一款 python 库,底层逻辑是什么?
-
结果:Gradio 展示的还是 web 元素
-
过程:所以 Gradio 是即懂 python 又懂 web 开发(css/js/html)的开发者,通过 python 对这些 web 技术做了封装
-
pipline:python 语言--> css/js/html
streamlit 应该也是如此,之前介绍过的 pyecharts 也是如此(封装的是百度的可视化框架 echarts。
开源牛人开发,方便你我,点赞!
2. 简单使用
我们来感受下 Gradio 的便捷之处。
安装:
-
要求 python>=3.7
pip install -U pip -i https://pypi.tuna.tsinghua.edu.cn/simplepip install gradio -i https://pypi.tuna.tsinghua.edu.cn/simple
复制代码
简单例子:
# app.pyimport gradio as grdef greet(name):return "Hello " + name + "!"demo = gr.Interface(fn=greet, inputs="text", outputs="text")demo.launch(server_name="0.0.0.0")# 启动# python -u app.py# Running on local URL: http://0.0.0.0:7860# To create a public link, set `share=True` in `launch()`
复制代码

上面的代码就是简单一个 webApp,功能是输入一个文本,输出一个文本。代码中关键点:
-
导入包
import gradio as gr -
gr.Interface 构建一个 app, 确定输入 inputs 和输出 outputs 的类型,已经处理输入 inputs 的函数(这个函数返回一个 outputs 的类型)
-
提供一个 app 的功能模块函数
-
launch 启动一个 web 容器,对外提供服务
梳理下 web 渲染流程
-
根据输入输出类型(如 text)封装 html 组件(with css 样式,布局等)
-
点击 submit:通过 js 获取输入的值传递(ajax)给后台处理函数(greet),通过 js 回调函数接收函数的返回值,然后通过 js 赋值给 html 元素
3. 组件介绍
上面只是介绍了 Gradio 的简单的使用,Gradio 提供了丰富的 html 组件,如文本框,图像,视频,下拉框,单选框,复选框等等。
我们再来看一个在机器视觉推理比较常见的展示:输入一个图片,输出一个图片,并提供下载。

import gradio as grfrom transformers import DPTFeatureExtractor, DPTForDepthEstimationimport torchimport numpy as npfrom PIL import Imageimport open3d as o3dfrom pathlib import Pathimport osfeature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")def process_image(image_path):image_path = Path(image_path)image_raw = Image.open(image_path)image = image_raw.resize((800, int(800 * image_raw.size[1] / image_raw.size[0])),Image.Resampling.LANCZOS)# prepare image for the modelencoding = feature_extractor(image, return_tensors="pt")# forward passwith torch.no_grad():outputs = model(**encoding)predicted_depth = outputs.predicted_depth## ... 省略return [img, gltf_path, gltf_path]title = "Demo: zero-shot depth estimation with DPT + 3D Point Cloud"description = "This demo is a variation from the original DPT Demo. It uses the DPT model to predict the depth of an image and then uses 3D Point Cloud to create a 3D object."examples = [["examples/1-jonathan-borba-CgWTqYxHEkg-unsplash.jpg"]]iface = gr.Interface(fn=process_image,inputs=[gr.Image(type="filepath", label="Input Image")],outputs=[gr.Image(label="predicted depth", type="pil"),gr.Model3D(label="3d mesh reconstruction", clear_color=[1.0, 1.0, 1.0, 1.0]),gr.File(label="3d gLTF")],title=title,description=description,examples=examples,allow_flagging="never",cache_examples=False)iface.launch(debug=True, enable_queue=False)
复制代码
上面的代码忽略了一些模型推理的细节,主要关注渲染对应的结果就是 inputs 和 outputs。可知,
-
inputs 和 outputs 都是可以多个,Gradio 根据类型展示相应的组件
-
其中:inputs 是 gr.Image 图像,对应的处理函数的参数为文件路径
type="filepath" -
其中:outputs 有三个输出(分布是图片,一个 3d 图片,一个是文件),这里的三个输出要对应处理函数的三个放回。三个输出会对应三个展示渲染,两个图片和一个文件下载
-
另外一个从展示结果看,最下面的位置有一个内部案例的列表 通过
examples=examples参数,进行展示渲染,这是非常有用的,用来展示模型的最佳效果图。
更多的组件使用详见 API
-
https://gradio.app/docs/
另外,可以通过.launch(share=True)来分享功能,这个功能可以生成一个域名,可以在外部直接访问。
4. 总结
本文简单分享了通过 python 库 Gradio 快速构建 webApp 的过程,总结如下:
-
Gradio 的本质是封装 html+css+js 等组件的 python 库
-
Gradio 最佳场景为:展示机器学习的推理效果(可交互)
-
gr.Interface 来渲染效果,注意 inputs 和 outputs 就是待渲染的内容
-
记住详细组件 API:https://gradio.app/docs/
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)