快速开始

先决条件:Gradio 需要 Python 3.7 或更高版本,仅此而已!

Prerequisite: Gradio requires Python 3.7 or higher, that's all!

Gradio 是做什么的?

与他人分享你的机器学习模型、API 或数据科学工作流程的最佳方式之一是创建一个交互式应用程序,让你的用户或同事可以在他们的浏览器中试用该演示。

One of the best ways to share your machine learning model, API, or data science workflow with others is to create an interactive app that allows your users or colleagues to try out the demo in their browsers.

Gradio 允许你构建演示并共享它们,所有这些都在 Python 中。 通常只需几行代码! 让我们开始吧。

Gradio allows you to build demos and share them, all in Python. And usually in just a few lines of code! So let's get started.

Hello, World

要使用简单的“Hello, World”示例运行 Gradio,请执行以下三个步骤:

To get Gradio running with a simple "Hello, World" example, follow these three steps:

  1. 使用 pip 安装 Gradio:

    Install Gradio using pip:

       pip install gradio
    
  2. 将以下代码作为 Python 脚本或在 Jupyter Notebook(或Google Colab )中运行:

    Run the code below as a Python script or in a Jupyter Notebook (or Google Colab):

    import gradio as gr

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

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

demo.launch()

我们将导入的名称缩短为 gr ,以便使用 Gradio 提高代码的可读性。 这是你应该遵循的广泛采用的约定,以便使用你的代码的任何人都可以轻松理解它。

We shorten the imported name to gr for better readability of code using Gradio. This is a widely adopted convention that you should follow so that anyone working with your code can easily understand it.

  1. 下面的演示将自动出现在 Jupyter Notebook 中,或者如果从脚本运行则在 http://localhost:7860 上的浏览​​器中弹出:

    The demo below will appear automatically within the Jupyter Notebook, or pop in a browser on http://localhost:7860 if running from a script:

    在本地开发时,如果你想将代码作为 Python 脚本运行,你可以使用 Gradio CLI 以重新加载模式启动应用程序,这将提供无缝和快速的开发。 在自动重新加载指南中了解有关重新加载的更多信息。

    When developing locally, if you want to run the code as a Python script, you can use the Gradio CLI to launch the application in reload mode, which will provide seamless and fast development. Learn more about reloading in the Auto-Reloading Guide.

       gradio app.py
    

    注意:你也可以执行 python app.py ,但它不会提供自动重新加载机制。

    Note: you can also do python app.py, but it won't provide the automatic reload mechanism.

Interface

你会注意到,为了制作演示,我们创建了一个 gr.Interface 。 这个 Interface 类可以用用户界面包装任何 Python 函数。 在上面的示例中,我们看到了一个简单的基于文本的函数,但该函数可以是任何东西,从音乐生成器到税收计算器再到预训练机器学习模型的预测函数。

You'll notice that in order to make the demo, we created a gr.Interface. This Interface class can wrap any Python function with a user interface. In the example above, we saw a simple text-based function, but the function could be anything from music generator to a tax calculator to the prediction function of a pretrained machine learning model.

核心 Interface 类使用三个必需参数进行初始化:

The core Interface class is initialized with three required parameters:

让我们仔细看看这些用于提供输入和输出的组件。

Let's take a closer look at these components used to provide input and output.

组件属性

我们在前面的示例中看到了一些简单的 Textbox 组件,但是如果你想更改 UI 组件的外观或行为方式怎么办?

We saw some simple Textbox components in the previous examples, but what if you want to change how the UI components look or behave?

假设你想要自定义输入文本字段——例如,你希望它更大并且有一个文本占位符。 如果我们使用 Textbox 的实际类而不是使用字符串快捷方式,你可以通过组件属性访问更多的可定制性。

Let's say you want to customize the input text field — for example, you wanted it to be larger and have a text placeholder. If we use the actual class for Textbox instead of using the string shortcut, you have access to much more customizability through component attributes.

import gradio as gr

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

demo = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(lines=2, placeholder="Name Here..."),
    outputs="text",
)
demo.launch()

多个输入和输出组件

假设你有一个更复杂的函数,具有多个输入和输出。 在下面的示例中,我们定义了一个函数,它接受一个字符串、布尔值和数字,并返回一个字符串和数字。 看一下如何传递输入和输出组件列表。

Suppose you had a more complex function, with multiple inputs and outputs. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. Take a look how you pass a list of input and output components.

import gradio as gr

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

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

你只需将组件包装在一个列表中。 inputs 列表中的每个组件按顺序对应于函数的一个参数。 outputs 列表中的每个组件对应于函数返回的值之一,同样按顺序。

You simply wrap the components in a list. Each component in the inputs list corresponds to one of the parameters of the function, in order. Each component in the outputs list corresponds to one of the values returned by the function, again in order.

图像示例

Gradio 支持多种类型的组件,例如 ImageDataFrameVideoLabel 。 让我们尝试一个图像到图像的功能来感受一下这些!

Gradio supports many types of components, such as Image, DataFrame, Video, or Label. Let's try an image-to-image function to get a feel for these!

import numpy as np
import gradio as gr

def sepia(input_img):
    sepia_filter = np.array([
        [0.393, 0.769, 0.189], 
        [0.349, 0.686, 0.168], 
        [0.272, 0.534, 0.131]
    ])
    sepia_img = input_img.dot(sepia_filter.T)
    sepia_img /= sepia_img.max()
    return sepia_img

demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), "image")
demo.launch()

当使用 Image 组件作为输入时,你的函数将接收一个形状为 (height, width, 3) 的 NumPy 数组,其中最后一个维度表示 RGB 值。 我们还将以 NumPy 数组的形式返回图像。

When using the Image component as input, your function will receive a NumPy array with the shape (height, width, 3), where the last dimension represents the RGB values. We'll return an image as well in the form of a NumPy array.

你还可以使用 type= 关键字参数设置组件使用的数据类型。 例如,如果你希望你的函数采用图像的文件路径而不是 NumPy 数组,则输入 Image 组件可以写成:

You can also set the datatype used by the component with the type= keyword argument. For example, if you wanted your function to take a file path to an image instead of a NumPy array, the input Image component could be written as:

gr.Image(type="filepath", shape=...)

另请注意,我们的输入 Image 组件带有一个编辑按钮🖉,它允许裁剪和放大图像。 以这种方式处理图像有助于揭示机器学习模型中的偏差或隐藏缺陷!

Also note that our input Image component comes with an edit button 🖉, which allows for cropping and zooming into images. Manipulating images in this way can help reveal biases or hidden flaws in a machine learning model!

你可以在Gradio 文档中阅读更多关于许多组件以及如何使用它们的信息。

You can read more about the many components and how to use them in the Gradio docs.

块:更多的灵活性和控制

Gradio 提供了两个类来构建应用程序:

Gradio offers two classes to build apps:

  1. Interface, that provides a high-level abstraction for creating demos that we've been discussing so far.

  2. Interface ,它为创建我们迄今为止一直在讨论的演示提供了高级抽象。

  3. Blocks, a low-level API for designing web apps with more flexible layouts and data flows. Blocks allows you to do things like feature multiple data flows and demos, control where components appear on the page, handle complex data flows (e.g. outputs can serve as inputs to other functions), and update properties/visibility of components based on user interaction — still all in Python. If this customizability is what you need, try Blocks instead!

  4. Blocks ,一种用于设计具有更灵活布局和数据流的 Web 应用程序的低级 API。 Blocks 允许你做一些事情,比如以多个数据流和演示为特色,控制组件在页面上出现的位置,处理复杂的数据流(例如,输出可以作为其他功能的输入),以及根据用户交互更新组件的属性/可见性——仍然全部在 Python 中。 如果你需要这种可定制性,请尝试使用 Blocks

你好,构造块

让我们看一个简单的例子。 请注意此处的 API 与 Interface 有何不同。

Let's take a look at a simple example. Note how the API here differs from Interface.

import gradio as gr

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

with gr.Blocks() as demo:
    name = gr.Textbox(label="Name")
    output = gr.Textbox(label="Output Box")
    greet_btn = gr.Button("Greet")
    greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet")


demo.launch()

注意事项:

Things to note:

更复杂

这是一个应用程序,可让你体验 Blocks 的可能性:

Here's an app to give you a taste of what's possible with Blocks:

import numpy as np
import gradio as gr


def flip_text(x):
    return x[::-1]


def flip_image(x):
    return np.fliplr(x)


with gr.Blocks() as demo:
    gr.Markdown("Flip text or image files using this demo.")
    with gr.Tab("Flip Text"):
        text_input = gr.Textbox()
        text_output = gr.Textbox()
        text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")

    with gr.Accordion("Open for More!"):
        gr.Markdown("Look at me...")

    text_button.click(flip_text, inputs=text_input, outputs=text_output)
    image_button.click(flip_image, inputs=image_input, outputs=image_output)

demo.launch()

这里还有很多事情要做! 我们将在“使用构造块构建”部分为你介绍如何创建像这样的复杂 Blocks 应用程序。

A lot more going on here! We'll cover how to create complex Blocks apps like this in the building with blocks section for you.

恭喜,你现在已经熟悉了 Gradio 的基础知识! 🥳 转到我们的下一个指南,了解有关 Gradio 主要功能的更多信息。

Congrats, you're now familiar with the basics of Gradio! 🥳 Go to our next guide to learn more about the key features of Gradio.