Python – Gradio 快速开始

本文摘要:

Python第三方库Gradio快速上手
Gradio官方首页

快速开始

  1. 提前准备:Python3.7足矣
  2. pip安装
pip install gradio

为了更快安装,可以使用清华镜像源。

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple gradio
  1. 执行以下代码
import gradio as gr

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

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

接口会自动出现在控制台,http://localhost:7860,浏览器打开即可看见如下页面。
Python - Gradio 快速开始
根据代码不难看出,在NAME输入内容,Submit后,右侧显示’Hello XXX!!’
Python - Gradio 快速开始

了解Interface类

Gradio 可以包装几乎任何 Python 函数为易于使用的用户界面。从上面例子我们看到,简单的基于文本的函数。但这个函数还可以处理很多类型。
Interface类通过以下三个参数进行初始化:
fn:包装的函数
inputs:输入组件类型,‘image’ 或 ‘audio’等(
查看文档了解更多)
ouputs:输出组件类型,‘image’ 或 ‘audio’等(查看文档了解更多)
通过这三个参数,我们可以快速创建一个接口并发布他们。

自定制组件

我们想自定制文本输入字段,我们想要一个更大的输入框,可以用Textbox代替。可以定制更多组件,更多详细定制可查看文档

Interface.launch()方法返回三个值

  1. app,为 Gradio 演示提供支持的 FastAPI 应用程序
  2. local_url,本地地址
  3. share_url,公共地址,当share=True时生成
import gradio as gr

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

iface = gr.Interface(
    fn=greet,
    inputs=gr.inputs.Textbox(lines=2, placeholder="Name Here..."),
    outputs="text",
)
if __name__ == "__main__":
    app, local_url, share_url = iface.launch()

多个输入和输出

示例代码如下

import gradio as gr

def greet(name, is_morning, temperature):
    salutation = "Good morning" if is_morning else "Good evening"
    greeting = "%s %s. It is %s degrees today" % (salutation, name, temperature)
    celsius = (temperature - 32) * 5 / 9
    return greeting, round(celsius, 2)

iface = gr.Interface(
    fn=greet,
    inputs=["text", "checkbox", gr.inputs.Slider(0, 100)],
    outputs=["text", "number"],
)
iface.launch()

效果演示
Python - Gradio 快速开始
Python - Gradio 快速开始
inputs列表里的每个字段按顺序对应函数的每个参数,outputs同理。

动态界面接口

在Interface添加live=True参数,只要输入发生变化,结果马上发生改变。

import gradio as gr

def calculator(num1, operation, num2):
    if operation == "add":
        return num1 + num2
    elif operation == "subtract":
        return num1 - num2
    elif operation == "multiply":
        return num1 * num2
    elif operation == "divide":
        return num1 / num2

iface = gr.Interface(
    calculator,
    ["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number"],
    "number",
    live=True,
)

iface.launch()

Python - Gradio 快速开始

Flagging标记

相信有小伙伴已经注意到,输出框下有个Flag按钮。当测试您的模型的用户看到某个输入导致输出错误或意外的模型行为,他们可以标记这个输入让开发者知道。这个文件夹由Interface的flagging_dir参数指定,默认为’flagged’。将这些会导致错误的输入保存到一个csv文件。如果Interface包含文件数据,文件夹也会创建来保存这些标记数据。
如下图所示,数据类型的则保存为如下格式
Python - Gradio 快速开始
文件类型的则保存为如下格式
Python - Gradio 快速开始

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年3月29日
下一篇 2023年3月29日

相关推荐