gradio--AI展示利器,快速构建机器学习模型交互式应用

点击上方“AI搞事情”关注我们


 :https://www.gradio.app/
github:https://github.com/gradio-app/gradio
论 文:Abid A , Abdalla A , Abid A ,et al.Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild[J]. 2019.DOI:10.48550/arXiv.1906.02569.

简介

快速构建针对人工智能交互式界面的python 的 webApp 库,封装前端页面 + 后端接口 + AI 算法模型推理,无需编写繁琐的HTML、CSS和JavaScript代码,方便 AI 算法工程师快速展示成果,支持机器学习模型、自然语言处理模型、计算机视觉模型等。

Gradio支持多种输入和输出类型,包括文本、图像、音频和视频。可以通过定义回调函数来处理输入,并将输出返回给用户。Gradio还提供了自动化的界面布局和样式,使得界面设计变得简单而直观。

安装初体验

pip install gradio
hello world 小栗子
import gradio as gr

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()

运行后在http://localhost:7860/可以访问web程序,访问IP和端口可以通过server_name="0.0.0.0", server_port=1234设置,并进行交互体验.

PC端打开是这样的:

6973fb7e2ea5df27d9230ae7ce1b8720.png

移动端打开是这样的,看来还做了移动端的兼容:

5ea1fb332ba0aa61a5f583b15fff8c69.png
傻瓜聊天机器人
import random
import gradio as gr

def random_response(message, history):
    return random.choice(["Yes", "No"])

demo = gr.ChatInterface(fn=random_response, title='chatgpt')

demo.launch()
71d0f52a5f2dc297f8139c8885814d66.png

根据上面两个简单demo,Gradio应用的基础模块有:

  • 应用界面:gr.Interface(简易场景),gr.ChatInterface(对话场景), gr.Blocks(定制化场景) gr.TabbedInterface (多页面场景)

  • 输入输出:gr.Image(图像), gr.Textbox(文本框), gr.DataFrame(数据框), gr.Dropdown(下拉选项), gr.Number(数字), gr.Markdown, gr.Files

  • fn功能函数:核心功能实现函数

  • 控制组件:gr.Button(按钮),gr.Checkbox(复选框),gr.Radio(单选按钮)等

  • 布局组件:gr.Tab(标签页), gr.Row(行布局), gr.Column(列布局)等

构建应用

图像处理

展示简单的图像旋转、灰度图转换操作,并将输入图片和结果展示在web页面。

import gradio as gr


def process_image(img, op_type):
    if op_type == "旋转90度":
        img = img.rotate(90)
    if op_type == "转绘图":
        img = img.convert("L")
    return img


demo = gr.Interface(
    fn=process_image,
    inputs=[gr.Image(type="pil"), gr.Radio(["旋转90度", "转绘图"])],
    outputs="image"
)

if __name__ == '__main__':
    demo.launch()
7d2f07582925cd01e8d8d3189d3f58a5.png

人脸检测

import gradio as gr
import time
import cv2

# 人脸检测函数
def face_rec(img):
    # 转为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 创建人脸级联分类器
    face_detecter = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
    faces = face_detecter.detectMultiScale(gray,
                                           scaleFactor=1.15,
                                           minNeighbors=3,
                                           minSize=(40, 40))
    for face in faces:
        print('face: ', face)
        (x, y, w, h) = face
        cv2.rectangle(img, (x, y), (x + w, y + h), [0, 0, 255], 2)
        face_img = img[y:y + h, x:x + w]  # 把检测处理的人脸框切片出来

        eye = cv2.CascadeClassifier('./haarcascades/haarcascade_eye.xml')  # 创建眼睛级联分类器
        eyes = eye.detectMultiScale(face_img)  # 在人脸切片图片上检测眼睛

        for eye in eyes:
            (ex, ey, ew, eh) = eye
            cv2.rectangle(face_img, (ex, ey), (ex + ew, ey + eh), [0, 255, 0], 2)  ##在人脸切片图片上框出眼睛,face_img已经修改
            img[y:y + h, x:x + w] = face_img  # 把框出眼睛的人脸切片图片贴到img上去

    return img

demo = gr.Interface(
    fn=face_rec,
    inputs=gr.Image(),
    outputs="image",
    examples=["images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg", "images/5.png"],
)

if __name__ == "__main__":
    demo.launch()
64f66d67fea8f200b7293d9a37bddef0.png

examples:指定输入的示例,如左下角所示

文本分类

根据语义信息进行情感分类,判断积极情绪还是消极情绪。这里采用的是distilbert-base-multilingual-cased-sentiments-student模型;这个模型是一个多语言模型,可以处理多种语言,包括英文、中文、日语等。

import gradio as gr
from transformers import pipeline

pipe = pipeline("text-classification",
                model="lxyuan/distilbert-base-multilingual-cased-sentiments-student",
                return_all_scores=True
                )  # 会自动从huggingface下载模型,不过一般打不开

def clf(text):
    result = pipe(text)
    res = {}
    for pred_label in result[0]:
        res[pred_label['label']] = pred_label['score']
    return res

demo = gr.Interface(fn=clf, inputs="text", outputs="label")
gr.close_all()

if __name__ == '__main__':
    demo.launch(share=True)
2febee3d97d2cb27002dc939a0ccb3c7.png

模型下载可以看这个项目:HuggingFace-Download-Accelerator

python hf_download.py --model lxyuan/distilbert-base-multilingual-cased-sentiments-student --save_dir ./hf_hub

矩阵操作

demo实现了矩阵的转置操作,输入输出为Dataframenumpy

import numpy as np

import gradio as gr

def transpose(matrix):
    return matrix.T

demo = gr.Interface(
    transpose,
    gr.Dataframe(type="numpy", datatype="number", row_count=5, col_count=3),
    "numpy",
    examples=[
        [np.zeros((3, 3)).tolist()],
        [np.ones((2, 2)).tolist()],
        [np.random.randint(0, 10, (3, 10)).tolist()],
        [np.random.randint(0, 10, (10, 3)).tolist()],
        [np.random.randint(0, 10, (10, 10)).tolist()],
    ],
    cache_examples=False
)

if __name__ == "__main__":
    demo.launch()
7e72d0f053f3049870c650446fc2df98.png

分享应用

1. 内网穿透共享应用

通过在 launch() 方法中设置 share=True,可以轻松地公开共享 Gradio服务。通过内网穿透工具frpc可以将本地服务映射到公共网络,使得远程可以访问。

没有安装frpc会提示如下信息:则需要按提示安装软件,才能将本地服务通过Gradio服务器以XXXXXX.gradio.app的链接分享到公网上,且共享链接在 72 小时内有效。

注意:由于将本地服务暴露到公网,需要注意隐私和数据安全,注意不要函数公开任何敏感信息或者违法乱纪的不当言论,或允许在您的设备上发生任何关键更改。

Could not create share link. Missing file: F:\Users\admin\anaconda3\lib\site-packages\gradio\frpc_windows_amd64_v0.2. 

Please check your internet connection. This can happen if your antivirus software blocks the download of this file. You can install manually by following these steps: 

1. Download this file: https://cdn-media.huggingface.co/frpc-gradio-0.2/frpc_windows_amd64.exe
2. Rename the downloaded file to: frpc_windows_amd64_v0.2
3. Move the file to this location: F:\Users\admin\anaconda3\lib\site-packages\gradio

2. 托管社区

HuggingFace

HuggingFace:目前最大的开源机器学习模型社区(AI模型的GitHub),Gradio团队21年已经被HuggingFace的收购;为了在公网展示模型效果,可以将 Gradio 的模型部署到 HuggingFace的 Space托管空间中。

  1. 注册huggingface账号:https://huggingface.co/join

  2. 在space空间中创建项目:https://huggingface.co/spaces

  3. 创建好的项目有一个Readme文档,可以根据说明操作,也可以手工编辑app.pyrequirements.txt文件。

fe6a9bce6b106116d3a929cf4454922b.png
modelscope

modelscope:国内的开源AI模型共享网站,对标国外的HuggingFace,modelscope创空间是AI应用展示空间,支持Gradio、Streamlit、Static搭建web AI应用。

397784154bfe6406499333ba8f5e8d37.png

3. 部署到云服务器

  1. 首先,你得有一台云服务器。

  2. 运行启动gradio项目代码,通过通过server_name="0.0.0.0", server_port=8000指定所有ID可访问和端口。

  3. 防火墙、安全组添加端口,开放指定端口。

  4. IP:port【域名,有的话】访问,即可访问服务器的AI服务。

关注我们

有趣的灵魂在等你

43da20cb30981029f4975794da7d51e7.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据您提供的引用内容,"No such file or directory: 'C:\Users\qxt\PycharmProjects\BasicSR\docs\gradio-3.32.2-py3-none-any.whl'"这个错误提示是系统找不到指定的文件或目录。具体来说,这个错误通常是由于文件或目录不存在导致的。可能是文件名或路径名拼写错误,或者文件或目录已被删除或移动到其他位置。 在这种情况下,解决这个问题的方法包括: 1. 检查文件路径和文件名的正确性,确保没有拼写错误。 2. 确保文件或目录确实存在于指定的位置。可以通过在文件资源管理器中手动检查该文件或目录是否存在。 3. 如果文件或目录已被删除或移动,可以尝试从备份中恢复文件或重新下载所需的文件。 希望这些信息能够帮助您解决问题。如果您还有其他问题,请随时提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [FileNotFoundError:[Errno 2] No such file or directory :](https://blog.csdn.net/qq_42772612/article/details/114150060)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [npm WARN saveError ENOENT: no such file or directory解决](https://blog.csdn.net/qq_32068809/article/details/79512709)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值