通过自动重新加载更快地开发

先决条件:本指南要求你了解 Blocks。 请务必先阅读构造块指南

Prerequisite: This Guide requires you to know about Blocks. Make sure to read the Guide to Blocks first.

本指南涵盖自动重新加载、在 Python IDE 中重新加载以及将 gradio 与 Jupyter Notebooks 结合使用。

This guide covers auto reloading, reloading in a Python IDE, and using gradio with Jupyter Notebooks.

为什么要自动重新加载?

当你构建 Gradio 演示时,尤其是在 Blocks 之外,你可能会发现不断重新运行代码以测试你的更改很麻烦。

When you are building a Gradio demo, particularly out of Blocks, you may find it cumbersome to keep re-running your code to test your changes.

为了更快、更方便地编写代码,当你在Python IDE (如 VS Code、Sublime Text、PyCharm 等)或一般情况下开发时,我们可以更轻松地立即“重新加载”你的 Gradio 应用程序从终端运行你的 Python 代码。 我们还开发了一个类似的“魔术命令”,如果你使用Jupyter Notebooks (或 Colab 等任何类似环境),它可以让你更快地重新运行单元格。

To make it faster and more convenient to write your code, we've made it easier to "reload" your Gradio apps instantly when you are developing in a Python IDE (like VS Code, Sublime Text, PyCharm, or so on) or generally running your Python code from the terminal. We've also developed an analogous "magic command" that allows you to re-run cells faster if you use Jupyter Notebooks (or any similar environment like Colab).

这份简短的指南将涵盖这两种方法,因此无论你如何编写 Python,你都会知道如何更快地构建 Gradio 应用程序。

This short Guide will cover both of these methods, so no matter how you write Python, you'll leave knowing how to build Gradio apps faster.

重新加载 Python IDE 🔥

如果你使用 Python IDE 构建 Gradio Blocks,你的代码文件(我们将其命名为 run.py )可能如下所示:

If you are building Gradio Blocks using a Python IDE, your file of code (let's name it run.py) might look something like this:

import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("# Greetings from Gradio!")
    inp = gr.Textbox(placeholder="What is your name?")
    out = gr.Textbox()

    inp.change(fn=lambda x: f"Welcome, {x}!", 
               inputs=inp, 
               outputs=out)

if __name__ == "__main__":
    demo.launch()    

问题是,任何时候你想要更改布局、事件或组件,你都必须关闭并通过编写 python run.py 重新运行你的应用程序。

The problem is that anytime that you want to make a change to your layout, events, or components, you have to close and rerun your app by writing python run.py.

你可以通过将 1 word: python 更改为 gradio 来以重新加载模式运行你的代码,而不是这样做:

Instead of doing this, you can run your code in reload mode by changing 1 word: python to gradio:

在终端中,运行 gradio run.py 。 就是这样!

In the terminal, run gradio run.py. That's it!

现在,在看到类似这样的内容后,你会看到:

Now, you'll see that after you'll see something like this:

Launching in *reload mode* on: http://127.0.0.1:7860 (Press CTRL+C to quit)

Watching...

WARNING:  The --reload flag should not be used in production on Windows.

这里的重要部分是 Watching... 这行发生的事情是 Gradio 将观察 run.py 文件所在的目录,如果文件发生变化,它将自动为你重新运行该文件。 这样你就可以专注于编写代码,并且你的 Gradio 演示会自动刷新🥳

The important part here is the line that says Watching... What's happening here is that Gradio will be observing the directory where run.py file lives, and if the file changes, it will automatically rerun the file for you. So you can focus on writing your code, and your Gradio demo will refresh automatically 🥳

⚠️ 警告: gradio 命令不会检测传递给 launch() 方法的参数,因为 launch() 方法永远不会在重新加载模式下被调用。 例如,在 launch() 中设置 authshow_error 将不会反映在应用程序中。

⚠️ Warning: the gradio command does not detect the parameters passed to the launch() methods because the launch() method is never called in reload mode. For example, setting auth, or show_error in launch() will not be reflected in the app.

在使用 reload 模式时要记住一件重要的事情:Gradio 专门在你的代码中寻找一个名为 demo 的 Gradio Blocks/Interface demo。 如果你将演示命名为其他名称,则需要将演示的 FastAPI 应用程序的名称作为代码中的第二个参数传递。 对于 Gradio 演示,可以使用 .app 属性访问 FastAPI 应用程序。 因此,如果你的 run.py 文件如下所示:

There is one important thing to keep in mind when using the reload mode: Gradio specifically looks for a Gradio Blocks/Interface demo called demo in your code. If you have named your demo something else, you will need to pass in the name of your demo's FastAPI app as the 2nd parameter in your code. For Gradio demos, the FastAPI app can be accessed using the .app attribute. So if your run.py file looked like this:

import gradio as gr

with gr.Blocks() as my_demo:
    gr.Markdown("# Greetings from Gradio!")
    inp = gr.Textbox(placeholder="What is your name?")
    out = gr.Textbox()

    inp.change(fn=lambda x: f"Welcome, {x}!", 
               inputs=inp, 
               outputs=out)

if __name__ == "__main__":
    my_demo.launch()    

然后你会像这样以重新加载模式启动它: gradio run.py my_demo.app

Then you would launch it in reload mode like this: gradio run.py my_demo.app.

🔥 如果你的应用程序接受命令行参数,你也可以传入它们。 这是一个例子:

🔥 If your application accepts command line arguments, you can pass them in as well. Here's an example:

import gradio as gr
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name", type=str, default="User")
args, unknown = parser.parse_known_args()

with gr.Blocks() as demo:
    gr.Markdown(f"# Greetings {args.name}!")
    inp = gr.Textbox()
    out = gr.Textbox()

    inp.change(fn=lambda x: x, inputs=inp, outputs=out)

if __name__ == "__main__":
    demo.launch()

你可以这样运行: gradio run.py --name Gretel

Which you could run like this: gradio run.py --name Gretel

另外,如果你更改 run.py 源代码或 Gradio 源代码,则会发生这种自动重新加载。 这意味着如果你决定为 Gradio 本身做出贡献,这会很有用 ✅

As a small aside, this auto-reloading happens if you change your run.py source code or the Gradio source code. Meaning that this can be useful if you decide to contribute to Gradio itself

Jupyter 笔记本魔术 🔮

如果使用 Jupyter Notebooks(或 Colab Notebooks 等)开发代码呢? 我们也有东西给你!

What about if you use Jupyter Notebooks (or Colab Notebooks, etc.) to develop code? We got something for you too!

我们开发了一个神奇的命令,可以为你创建和运行 Blocks 演示。 要使用它,请在笔记本顶部加载 gradio 扩展:

We've developed a magic command that will create and run a Blocks demo for you. To use this, load the gradio extension at the top of your notebook:

%load_ext gradio

然后,在你正在开发 Gradio 演示的单元格中,只需在顶部编写魔术命令%%blocks ,然后像往常一样编写布局和组件:

Then, in the cell that you are developing your Gradio demo, simply write the magic command %%blocks at the top, and then write the layout and components like you would normally:

%%blocks 

import gradio as gr

gr.Markdown("# Greetings from Gradio!")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()

inp.change(fn=lambda x: f"Welcome, {x}!", 
           inputs=inp, 
           outputs=out)

请注意:

Notice that:

  • 你不需要将 with gr.Blocks() as demo:demo.launch() 代码——Gradio 会自动为你完成!

    You do not need to put the boiler plate with gr.Blocks() as demo: and demo.launch() code — Gradio does that for you automatically!

  • 每次你重新运行单元时,Gradio 都会在同一端口上并使用相同的底层 Web 服务器重新启动你的应用程序。 这意味着你将比正常重新运行单元更快地看到你的更改。

    Every time you rerun the cell, Gradio will re-launch your app on the same port and using the same underlying web server. This means you'll see your changes much, much faster than if you were rerunning the cell normally.

这是它在 jupyter notebook 中的样子:

Here's what it looks like in a jupyter notebook:

🪄 这也适用于 colab 笔记本! 这是一个 colab notebook ,你可以在其中看到 Blocks 魔法的作用。 尝试进行一些更改并使用 Gradio 代码重新运行单元格!

🪄 This works in colab notebooks too! Here's a colab notebook where you can see the Blocks magic in action. Try making some changes and re-running the cell with the Gradio code!

Notebook Magic 现在是作者构建 Gradio 演示的首选方式。 无论你如何编写 Python 代码,我们都希望这两种方法中的任何一种都能给你带来更好的 Gradio 开发体验。

The Notebook Magic is now the author's preferred way of building Gradio demos. Regardless of how you write Python code, we hope either of these methods will give you a much better development experience using Gradio.


下一步

现在你知道如何使用 Gradio 快速开发,开始构建你自己的!

Now that you know how to develop quickly using Gradio, start building your own!

如果你正在寻找灵感,请尝试探索其他人使用 Gradio 构建的演示,浏览公共 Hugging Face Spaces🤗

If you are looking for inspiration, try exploring demos other people have built with Gradio, browse public Hugging Face Spaces 🤗