Gradio 最快创建Web 界面部署到服务器并演示机器学习模型,本文提供教学案例以及部署方法,避免使用繁琐的django

ops/2024/10/8 22:59:36/

最近学习hugging face里面的物体检测模型,发现一个方便快捷的工具!

Gradio 是通过友好的 Web 界面演示机器学习模型的最快方式,以便任何人都可以在任何地方使用它!

一、核心优势:

使用这个开发这种演示机器学习模型的web界面会比django会快上不少!
只需要一个py文件即可实现模型界面创建,部署模型到服务器及时间响应所有功能。

二、重要参考连接:

官网如下:

Gradio

别人的部署到hugging face的space服务器案例如下:(可全网任意访问-)

https://huggingface.co/spaces/ClassCat/DETR-Object-Detection

案例对应的代码如下:

https://huggingface.co/spaces/ClassCat/DETR-Object-Detection/tree/main

三、自己本地服务器部署的案例

自己的物检测及体识别的代码(亲测成功):

python">import torch
from transformers import pipelinefrom PIL import Imageimport matplotlib.pyplot as plt
import matplotlib.patches as patchesfrom random import choice
import iodetector50 = pipeline(model="facebook/detr-resnet-50")#自动下载模型,大约200MB# detector101 = pipeline(model="facebook/detr-resnet-101")import gradio as grCOLORS = ["#ff7f7f", "#ff7fbf", "#ff7fff", "#bf7fff","#7f7fff", "#7fbfff", "#7fffff", "#7fffbf","#7fff7f", "#bfff7f", "#ffff7f", "#ffbf7f"]fdic = {"family" : "Arial","style" : "italic","size" : 15,"color" : "yellow","weight" : "bold"
}def get_figure(in_pil_img, in_results):plt.figure(figsize=(16, 10))plt.imshow(in_pil_img)#pyplot.gcf()ax = plt.gca()for prediction in in_results:selected_color = choice(COLORS)x, y = prediction['box']['xmin'], prediction['box']['ymin'],w, h = prediction['box']['xmax'] - prediction['box']['xmin'], prediction['box']['ymax'] - prediction['box']['ymin']ax.add_patch(plt.Rectangle((x, y), w, h, fill=False, color=selected_color, linewidth=3))ax.text(x, y, f"{prediction['label']}: {round(prediction['score']*100, 1)}%", fontdict=fdic)plt.axis("off")return plt.gcf()def infer(model, in_pil_img):results = Noneif model == "detr-resnet-101":results = detector101(in_pil_img)else:results = detector50(in_pil_img)figure = get_figure(in_pil_img, results)buf = io.BytesIO()figure.savefig(buf, bbox_inches='tight')buf.seek(0)output_pil_img = Image.open(buf)return output_pil_imgwith gr.Blocks(title="DETR Object Detection - ClassCat",css=".gradio-container {background:lightyellow;}") as demo:#sample_index = gr.State([])gr.HTML("""<div style="font-family:'Times New Roman', 'Serif'; font-size:16pt; font-weight:bold; text-align:center; color:royalblue;">DETR Object Detection</div>""")gr.HTML("""<h4 style="color:navy;">1. Select a model.</h4>""")model = gr.Radio(["detr-resnet-50", "detr-resnet-101"], value="detr-resnet-50", label="Model name")gr.HTML("""<br/>""")gr.HTML("""<h4 style="color:navy;">2-a. Select an example by clicking a thumbnail below.</h4>""")gr.HTML("""<h4 style="color:navy;">2-b. Or upload an image by clicking on the canvas.</h4>""")with gr.Row():input_image = gr.Image(label="Input image", type="pil")output_image = gr.Image(label="Output image with predicted instances", type="pil")gr.Examples(['samples/cats.jpg', 'samples/detectron2.png'], inputs=input_image)gr.HTML("""<br/>""")gr.HTML("""<h4 style="color:navy;">3. Then, click "Infer" button to predict object instances. It will take about 10 seconds (on cpu)</h4>""")send_btn = gr.Button("Infer")send_btn.click(fn=infer, inputs=[model, input_image], outputs=[output_image])gr.HTML("""<br/>""")gr.HTML("""<h4 style="color:navy;">Reference参考链接</h4>""")gr.HTML("""<ul>""")gr.HTML("""<li><a href="https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/detr_attention.ipynb" target="_blank">Hands-on tutorial for DETR</a>""")gr.HTML("""</ul>""")#demo.queue()
demo.launch(debug=True)

界面及功能都正常,展示如下:

tips1:运行上述代码,如果报代理错误:

在终端使用如下代码再重新启动jupyter-noterbook,使用下面命令即可解决:

python">(base) jie@dell:~/桌面$ unset all_proxy; unset ALL_PROXY

tip2:如果拖动自己的图片在预测框显示错误,原因是点击预测太快了。需要等图片上传完后点预测才能成功,点太快会出现错误两字。不限制图片尺寸。

四、入门gradio案例:

python">import gradio as grdef greet(name):return "Hello " + name + "!"demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()   

实现对姓名打招呼的功能,本地服务器的界面如下:

四、尝试在远程服务器上搭建(重要)

本人项目链接:https://huggingface.co/spaces/wuqi57/facebook-detr-resnet-50

在远程服务器上需要下载包和上传模型文件,官方提供了api:

https://huggingface.co/facebook/detr-resnet-50/tree/main?inference_api=true

以及打包好的space环境 

https://huggingface.co/facebook/detr-resnet-50/tree/main?space_deploy=true

上面两种方式就可以直接使用,直接创建一个app.py文件就可以运行,避免了上传大量的模型文件和下载相应的库。(实例见本人上面的项目链接)


http://www.ppmy.cn/ops/14123.html

相关文章

C# Solidworks二次开发:枚举应用实战(第三讲)

大家好&#xff0c;今天继续介绍枚举相关内容。 下面是今天要介绍的枚举&#xff1a; &#xff08;1&#xff09;第一个为swACisOutputVersion&#xff0c;这个枚举为ACIS的版本&#xff0c;下面是官方的具体解释&#xff1a; 其枚举值为&#xff1a; MemberDescriptionswAc…

表单插件——jquery.form.js

表单插件——jquery.form.js 表单插件(Form Plugin) 下载地址 :http://plugins.jquery.com/form/ 文件名:jquery.form.js version: 3.50.0-2014.02.05(最新版本) 功能:提供表单数据、重置表单项目、使用Ajax提交数据等 获取表单数据&#xff1a; 对于表单而言&#xff0c…

python爬虫之xpath4

1 最终项目实现的代码 仙剑 #!/usr/bin/env python ​ import logging import requests import re from urllib.parse import urljoin import pymongo import multiprocessing ​ mongo_client pymongo.MongoClient("mongodb://192.168.135.131:27017/") db mong…

[Swift]单元测试

编写单元测试是确保你的代码质量和功能正确性的重要步骤 一、编写单元测试的详细流程 1. 创建一个新的Xcode项目 如果你尚未创建一个项目&#xff0c;首先你需要在Xcode中创建一个新的iOS项目&#xff1a; 打开Xcode&#xff0c;选择“File” > “New” > “Project”…

【Interconnection Networks 互连网络】Dragonfly Topology 蜻蜓网络拓扑

蜻蜓拓扑 Dragonfly Topology 1. 拓扑参数2. Topology Description 拓扑描述3. Topology Variations 拓扑变体 蜻蜓拓扑 Dragonfly Topology 1. 拓扑参数 Dragonfly拓扑参数&#xff1a; N N N: 网络中终端(terminal)的总数量 p p p: 连接到每个路由器的终端数量 a a a: 每…

ArcGIS无法开始编辑TIN!开始编辑TIN显示灰色

ArcGIS无法开始编辑TIN&#xff01;开始编辑TIN显示灰色&#xff1f; 解决方案&#xff01; 1、确认自定义——扩展模块中空间分析、3D分析模块勾选。 2、确认以上后&#xff0c;还是不能编辑的话&#xff0c;我们可以调出 3D分析分析工具条&#xff0c;你就会发现。TIN编辑工…

Spring Gateway的入门概述简介

1. 为什么要有网关 在微服务中&#xff0c;一般都会把相对独立的业务或者功能划分成一个独立的服务&#xff0c;做到业务或者功能之间的隔离&#xff0c;分开部署。但是在请求到这些正式的服务的时候一般会有一些预前的处理&#xff0c;比如&#xff1a;权限校验&#xff0c;流…

自建zerotier服务——实现更快速安全的远程连接

zerotier介绍 ZeroTier 是地球上智能可编程的以太网交换机。它允许所有网络设备、虚拟机 (VMs)、容器和应用程序通信&#xff0c;就好像它们都位于同一个物理数据中心或云区域中一样。 功能简介&#xff1a; 全球虚拟网络&#xff1a; ZeroTierOne 可以创建一个全球虚拟的软件…