《Gradio Python 客户端入门》
Gradio Python 客户端使将任何 Gradio 应用程序用作 API 变得非常容易。例如,考虑这个 Hugging Face Space,它转录从麦克风录制的音频文件。
使用该库,我们可以轻松地将 Gradio 用作 API 以编程方式转录音频文件。gradio_client
这是执行此作的完整代码:
from gradio_client import Client, handle_file
client = Client("abidlabs/whisper")
client.predict(
audio=handle_file("audio_sample.wav")
)
>> "This is a test of the whisper speech recognition model.
Gradio 客户端可与任何托管的 Gradio 应用程序配合使用!虽然 Client 主要用于托管在 Hugging Face Spaces 上的应用程序,但您的应用程序可以托管在任何地方,例如您自己的服务器。
先决条件:要使用 Gradio 客户端,您无需非常详细地了解该库。但是,大致熟悉 Gradio 的输入和输出组件概念会很有帮助。gradio
安装
如果您已经有最新版本的 ,则 将作为依赖项包含在内。但请注意,本文档反映了 的最新版本,因此如果您不确定,请升级!gradio
gradio_client
gradio_client
轻量级软件包可以从 pip(或 pip3)安装,并经过测试,可与 Python 版本 3.10 或更高版本配合使用:gradio_client
$ pip install --upgrade gradio_client
连接到 Hugging Face Spaces 上的 Gradio 应用程序
首先连接实例化对象并将其连接到在 Hugging Face Spaces 上运行的 Gradio 应用程序。Client
from gradio_client import Client
client = Client("abidlabs/en2fr") # a Space that translates from English to French
您还可以通过使用参数传入 HF 令牌来连接到私有 Spaces。您可以在此处获取您的 HF 代币:https://huggingface.co/settings/tokenshf_token
from gradio_client import Client
client = Client("abidlabs/my-private-space", hf_token="...")
复制 Space 供私人使用
虽然您可以将任何公共空间用作 API,但如果您发出的请求过多,Hugging Face 可能会限制您的速率。要无限制地使用空间,只需复制空间即可创建私人空间。 然后使用它来提出您想要的任意数量的请求!
它包括一个类方法:为了简化此过程(您需要传入 Hugging Face 令牌或使用 Hugging Face CLI 登录):gradio_client
Client.duplicate()
import os
from gradio_client import Client, handle_file
HF_TOKEN = os.environ.get("HF_TOKEN")
client = Client.duplicate("abidlabs/whisper", hf_token=HF_TOKEN)
client.predict(handle_file("audio_sample.wav"))
>> "This is a test of the whisper speech recognition model."
如果您之前复制了 Space,则重新运行不会创建新的 Space。相反,客户端将附加到之前创建的 Space。因此,多次重新运行该方法是安全的。duplicate()
Client.duplicate()
注意:如果原始 Space 使用 GPU,您的私有 Space 也会使用 GPU,并且您的 Hugging Face 帐户将根据 GPU 的价格计费。为了最大限度地减少费用,您的 Space 将在 1 小时不活动后自动进入休眠状态。您还可以使用 的参数 设置硬件。hardware
duplicate()
连接通用 Gradio 应用程序
如果您的应用程序在其他地方运行,只需提供完整的 URL,包括“http://”或“https://”。以下是对在分享 URL 上运行的 Gradio 应用进行预测的示例:
from gradio_client import Client
client = Client("https://bec81a83-5b5c-471e.gradio.live")
使用身份验证连接到 Gradio 应用程序
如果要连接的 Gradio 应用程序需要用户名和密码,请将它们作为元组提供给类的参数:auth
Client
from gradio_client import Client
Client(
space_name,
auth=[username, password]
)
检查 API 端点
连接到 Gradio 应用程序后,您可以通过调用该方法查看可用的 API。对于 Whisper Space,我们看到以下内容:Client.view_api()
Client.predict() Usage Info
---------------------------
Named API endpoints: 1
- predict(audio, api_name="/predict") -> output
Parameters:
- [Audio] audio: filepath (required)
Returns:
- [Textbox] output: str
我们看到在这个空间里有 1 个 API 端点,并向我们展示了如何使用 API 端点进行预测:我们应该调用该方法(我们将在下面探讨),提供一个 类型的参数,它是一个 ..predict()
input_audio
str
filepath or URL
我们还应该为方法提供参数。虽然如果 Gradio 应用程序只有 1 个命名端点,这不是必需的,但它确实允许我们在单个应用程序中调用不同的端点(如果它们可用)。api_name='/predict'
predict()
“查看 API”页面
作为运行该方法的替代方法,您可以单击 Gradio 应用程序页脚中的“通过 API 使用”链接,该链接向我们显示了相同的信息以及示例用法。.view_api()
View API 页面还包括一个“API 记录器”,可让您正常与 Gradio UI 交互,并将您的交互转换为相应的代码以使用 Python 客户端运行。
进行预测
进行预测的最简单方法是简单地使用适当的参数调用函数:.predict()
from gradio_client import Client
client = Client("abidlabs/en2fr", api_name='/predict')
client.predict("Hello")
>> Bonjour
如果有多个参数,那么你应该将它们作为单独的参数传递给 ,就像这样:.predict()
from gradio_client import Client
client = Client("gradio/calculator")
client.predict(4, "add", 5)
>> 9.0
建议提供关键字参数而不是位置参数:
from gradio_client import Client
client = Client("gradio/calculator")
client.predict(num1=4, operation="add", num2=5)
>> 9.0
这允许您利用 default 参数。例如,此 Space 包括 Slider 组件的默认值,因此在使用客户端访问该组件时无需提供该值。
from gradio_client import Client
client = Client("abidlabs/image_generator")
client.predict(text="an astronaut riding a camel")
默认值为对应 Gradio 组件的初始值。如果组件没有初始值,但如果 predict 函数中的相应参数具有默认值 ,则该参数在客户端中也是可选的。当然,如果你想覆盖它,你也可以包含它:None
from gradio_client import Client
client = Client("abidlabs/image_generator")
client.predict(text="an astronaut riding a camel", steps=25)
要提供文件或 URL 作为输入,应将文件路径或 URL 传递到 .这将负责将文件上传到 Gradio 服务器,并确保文件得到正确预处理:gradio_client.handle_file()
from gradio_client import Client, handle_file
client = Client("abidlabs/whisper")
client.predict(
audio=handle_file("https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3")
)
>> "My thought I have nobody by a beauty and will as you poured. Mr. Rochester is serve in that so don't find simpus, and devoted abode, to at might in a r—"
异步运行作业
Oe 应注意这是一个阻塞作,因为它会等待作完成,然后再返回预测。.predict()
在许多情况下,最好让作业在后台运行,直到您需要预测结果为止。为此,您可以使用该方法创建一个实例,然后调用该作业以获取结果。例如:Job
.submit()
.result()
from gradio_client import Client
client = Client(space="abidlabs/en2fr")
job = client.submit("Hello", api_name="/predict") # This is not blocking
# Do something else
job.result() # This is blocking
>> Bonjour
from gradio_client import Client
client = Client(space="abidlabs/en2fr")
job = client.submit("Hello", api_name="/predict") # This is not blocking
# Do something else
job.result() # This is blocking
>> Bonjour
添加回调
或者,可以添加一个或多个回调,以便在作业完成运行后执行作,如下所示:
from gradio_client import Client
def print_result(x):
print("The translated result is: {x}")
client = Client(space="abidlabs/en2fr")
job = client.submit("Hello", api_name="/predict", result_callbacks=[print_result])
# Do something else
>> The translated result is: Bonjour
地位
该对象还允许您通过调用该方法来获取正在运行的作业的状态。这将返回具有以下属性的对象:(状态代码,表示状态的一组已定义字符串之一。请参阅类)、(此作业在队列中的当前位置)、(总队列大小)、(此作业将完成的估计时间)、(表示作业是否成功完成的布尔值)和(生成状态的时间)。Job
.status()
StatusUpdate
code
utils.Status
rank
queue_size
eta
success
time
from gradio_client import Client
client = Client(src="gradio/calculator")
job = client.submit(5, "add", 4, api_name="/predict")
job.status()
>> <Status.STARTING: 'STARTING'>
注意:该类还有一个实例方法,该方法返回一个布尔值,指示作业是否已完成。Job
.done()
取消作业
该类还有一个实例方法,用于取消已排队但尚未启动的作业。例如,如果运行:Job
.cancel()
client = Client("abidlabs/whisper")
job1 = client.submit(handle_file("audio_sample1.wav"))
job2 = client.submit(handle_file("audio_sample2.wav"))
job1.cancel() # will return False, assuming the job has started
job2.cancel() # will return True, indicating that the job has been canceled
如果第一个作业已开始处理,则不会取消该作业。如果第二个作业 尚未启动,则会成功取消并从队列中删除。
生成器终端节点
某些 Gradio API 端点不返回单个值,而是返回一系列值。您可以通过运行以下命令随时从此类生成器终端节点获取返回的一系列值:job.outputs()
from gradio_client import Client
client = Client(src="gradio/count_generator")
job = client.submit(3, api_name="/count")
while not job.done():
time.sleep(0.1)
job.outputs()
>> ['0', '1', '2']
请注意,在生成器终端节点上运行仅为您提供终端节点返回的第一个值。job.result()
该对象也是可迭代的,这意味着您可以使用它来显示从终端节点返回的生成器函数的结果。下面是使用 as 生成器的等效示例:Job
Job
from gradio_client import Client
client = Client(src="gradio/count_generator")
job = client.submit(3, api_name="/count")
for o in job:
print(o)
>> 0
>> 1
>> 2
您还可以取消具有迭代输出的作业,在这种情况下,作业将在当前迭代完成运行后立即完成。
from gradio_client import Client
import time
client = Client("abidlabs/test-yield")
job = client.submit("abcdef")
time.sleep(3)
job.cancel() # job cancels after 2 iterations
具有会话状态的演示
Gradio 演示可以包含会话状态,这为演示提供了一种在页面会话中保留用户交互信息的方法。
例如,请考虑以下演示,该演示维护用户在组件中提交的单词列表。当用户提交新单词时,该单词将被添加到状态中,并显示该单词以前出现的次数:gr.State
import gradio as gr
def count(word, list_of_words):
return list_of_words.count(word), list_of_words + [word]
with gr.Blocks() as demo:
words = gr.State([])
textbox = gr.Textbox()
number = gr.Number()
textbox.submit(count, inputs=[textbox, words], outputs=[number, words])
demo.launch()
如果你要使用 Python 客户端连接这个 Gradio 应用程序,你会注意到 API 信息只显示一个输入和输出:
Client.predict() Usage Info
---------------------------
Named API endpoints: 1
- predict(word, api_name="/count") -> value_31
Parameters:
- [Textbox] word: str (required)
Returns:
- [Number] value_31: float
这是因为 Python 客户端会自动为您处理状态 —— 当您发出一系列请求时,一个请求返回的状态将存储在内部,并自动提供给后续请求。如果您想重置状态,可以通过调用 来实现。Client.reset_session()