使用gradio,只需在原有的代碼中增加幾行,快速部署
機(jī)器學(xué)習(xí)模型,就能自動(dòng)化生成交互式web頁(yè)面
,并支持多種輸入輸出格式,比如圖像分類(lèi)中的圖>>標(biāo)簽,超分辨率中的圖>>圖等。
同時(shí)還支持生成能外部網(wǎng)絡(luò)訪問(wèn)的鏈接
,能夠迅速讓你的朋友,同事體驗(yàn)?zāi)愕乃惴ā?/p>
參考
- https://gradio.app/demos/
- https://www.machinelearningnuggets.com/gradio-tutorial/
- https://gradio.app/quickstart/
安裝
注意,不要把python文件與
pip install gradio
一、簡(jiǎn)單的歡迎界面分析——(輸入文字UI+ 函數(shù)處理+輸出文字)
邏輯:輸入U(xiǎn)I中的參數(shù),提交后自動(dòng)傳入綁定的函數(shù),
其中 “text” 表示輸入輸出UI控件是文本框。
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet,inputs="text", outputs="text")
demo.launch()
'''
如果需要在服務(wù)器部署后,局域網(wǎng)訪問(wèn), 修改為:
'''
# demo.queue().launch( server_name="0.0.0.0")
UI操作效果
默認(rèn)啟動(dòng) ,如果7860已經(jīng)占用,自動(dòng)變?yōu)?861,如果端口無(wú)法啟動(dòng) 。。 端口被占用時(shí),可指定端口
demo.launch(server_port=30001)
http://127.0.0.1:7860/
動(dòng)效
分析
在上面的例子中,我們看到一個(gè)簡(jiǎn)單的基于文本的函數(shù)gr.InterfaceInterface
核心類(lèi)使用三個(gè)必需參數(shù)進(jìn)行初始化:Interfacefn
:將 UI 包裹起來(lái)的函數(shù),該函數(shù)可以是任何功能,從音樂(lè)生成器到稅收計(jì)算器,再到預(yù)訓(xùn)練機(jī)器學(xué)習(xí)模型的預(yù)測(cè)函數(shù)inputs
:用于輸入的組件(例如,或"text",“image”,“audio”)outputs
:用于輸出的組件(例如,或"text",“image”,“l(fā)abel”)
使用控件函數(shù)設(shè)置控件的參數(shù)
設(shè)置2行文本寬度,文本框的內(nèi)的提示詞
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(
fn=greet,
inputs=gr.Textbox(lines=2, placeholder="這里是提示文本框輸入的內(nèi)容..."),
outputs="text",
)
demo.launch()
UI界面
多UI控件輸入、輸出
3個(gè)UI控件作為輸入,2個(gè)輸出,
輸入名字,是否是早晨,今天的溫度,
自動(dòng)輸入問(wèn)候以及華氏溫度與攝氏溫度的轉(zhuǎn)換
import gradio as gr
def greet(name, is_morning, temperature):
# salutation表示致意、問(wèn)候
salutation = "Good morning" if is_morning else "Good evening"
greeting = f"{salutation} {name}. It is {temperature} degrees today"
# 攝氏溫度 = (華氏溫度 – 32) ÷ 1.8
celsius = (temperature - 32) * 5 / 9
return greeting, round(celsius, 2)
demo = gr.Interface(
fn=greet,
inputs=["text", "checkbox", gr.Slider(0, 100,label="華氏溫度")],
outputs=["text", "number"],
)
demo.launch(server_port=30001)
二、簡(jiǎn)單界面控件組合
2.1 多個(gè)tags界面,(不同輸入輸出功能)
每個(gè)tags的功能、輸入輸出控件科技不同、且獨(dú)立
多tags代碼
import gradio as gr
#app 1
def user_greeting(name):
return "Hi! " + name + " Welcome !!??"
#app 2
def user_help(value):
return f"you pick {value} "
def tags3(img):
return img
# tags1的輸入、輸出,以及對(duì)應(yīng)處理函數(shù)
app1 = gr.Interface(fn = user_greeting, inputs="text", outputs="text")
# tags1的輸入、輸出,以及對(duì)應(yīng)處理函數(shù)
app2 = gr.Interface(fn = user_help, inputs="slider", outputs="text")
# tags1的輸入、輸出,以及對(duì)應(yīng)處理函數(shù)
app3 = gr.Interface(fn = tags3, inputs="image", outputs="image")
demo = gr.TabbedInterface(
[app1, app2,app3],
tab_names=["第一個(gè)界面", "第二個(gè)界面","tags3_圖像"],
title="多選項(xiàng)卡demo"
)
demo.launch()
2.2 進(jìn)度條顯示函數(shù)處理時(shí)間(process)
進(jìn)度條可以反映某些變量的值
2.2 進(jìn)度條代碼
import gradio as gr
import time
# from https://gradio.app/docs/#progress
def my_function(x=10, progress_demo=gr.Progress()):
x=int(x)
progress_demo(0, desc="Starting...")
time.sleep(1)
for i in progress_demo.tqdm(range(x)):
time.sleep(0.1)
res=f'run {x} steps'
return res
gr.Interface(my_function,
gr.Number(),
gr.Textbox()).queue().launch()
三、圖像相關(guān)操作、模型部署
3.1 對(duì)上傳圖片,直接處理
上傳一張圖片,輸入為灰度圖像,其中處理函數(shù)可以修改為自己的。### 完整代碼
import numpy as np
import gradio as gr
from PIL import Image
def gray(input_img):
# 灰度值 = 0.2989 * R + 0.5870 * G + 0.1140 * B
# image[..., :3]表示提取圖像的前三個(gè)通道(即R、G、B通道)
# 省略號(hào)可以在索引中表示對(duì)應(yīng)維度的完整范圍。
gray = np.dot(input_img[..., :3], [0.2989, 0.5870, 0.1140])
gray = gray.astype(np.uint8) # 將灰度圖像轉(zhuǎn)換為無(wú)符號(hào)整型 ,如果不加一般會(huì)報(bào)錯(cuò)
# pil_image = Image.fromarray(gray) # 將灰度圖像數(shù)組轉(zhuǎn)換為PIL圖像對(duì)象
return gray
demo = gr.Interface(gray, gr.inputs.Image(), outputs="image")
demo.launch(server_port=7862)
'''
如果需要在服務(wù)器部署后,局域網(wǎng)訪問(wèn), 添加服務(wù)名 server_name 修改為:
'''
# demo.queue().launch( server_name="0.0.0.0")
3.2 分類(lèi)模型UI部署 (需要安裝pytorch環(huán)境)
下載模型界面(可手動(dòng))
Downloading: “https://github.com/pytorch/vision/zipball/v0.6.0” to C:\Users\admin/.cache\torch\hub\v0.6.0.zip
Downloading: “https://download.pytorch.org/models/resnet18-f37072fd.pth” to C:\Users\admin/.cache\torch\hub\checkpoints\resnet18-f37072fd.pth
代碼
import gradio as gr
import torch
import requests
from torchvision import transforms
model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', pretrained=True).eval()
response = requests.get("https://git.io/JJkYN")
labels = response.text.split("\n")
print('labels',labels)
def predict(inp):
inp = transforms.ToTensor()(inp).unsqueeze(0)
with torch.no_grad():
prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)
confidences = {labels[i]: float(prediction[i]) for i in range(1000)}
return confidences
demo = gr.Interface(fn=predict,
inputs=gr.inputs.Image(type="pil"),
outputs=gr.outputs.Label(num_top_classes=3),
# examples=[["cheetah.jpg"]],
)
demo.launch(server_port=7865)
附錄
端口被占用 [Errno 10048] error while attempting to bind on address
ERROR: [Errno 10048] error while attempting to bind on address (‘127.0.0.1’, 7860): 通常每個(gè)套接字地址(協(xié)議/網(wǎng)絡(luò)地址/端口)只允許使用一次。
解決方法1 (指定打開(kāi)的端口)
server_port=xxx文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-502228.html
...........
demo.launch(server_port=30001)
解決方法2
打開(kāi)命令端文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-502228.html
找到占用端口+殺死
netstat -ano|findstr "7860"
taskkill -F -PID your_id
到了這里,關(guān)于【AI模型部署】基于gradio和python的網(wǎng)頁(yè)交互界面(web-ui)——簡(jiǎn)易使用方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!