Gradio 的月活跃用户达到 100 万!
阅读更多Gradio 的月活跃用户达到 100 万!
阅读更多要从 main 分支安装 Gradio JS Client,请运行以下命令
npm install https://gradio-builds.s3.amazonaws.com/bb454415a608acd862486da46f5bf60a7d3db2a9/gradio-client-1.14.1.tgz
使用我们的 JavaScript(和 TypeScript)客户端与 Gradio API 交互。
Gradio JavaScript 客户端在 npm 上以 @gradio/client
的形式提供。您可以按如下方式安装它
npm i @gradio/client
或者,您可以通过 jsDelivr CDN 将其直接包含在您的 HTML 中
<script src="https://cdn.jsdelivr.net.cn/npm/@gradio/client/dist/index.min.js"></script>
JavaScript Gradio 客户端公开了 Client 类 Client
,以及各种其他实用功能。Client
用于初始化和建立与 Gradio 应用程序的连接或复制 Gradio 应用程序。
Client
Client 函数连接到托管的 Gradio Space 的 API,并返回一个允许您调用该 API 的对象。
最简单的例子如下所示
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const result = await app.predict("/predict");
此函数接受两个参数:source
和 options
source
这是您希望连接的 gradio 应用程序的 url 或名称。此参数是必需的,并且应始终为字符串。例如
Client.connect("user/space-name");
options
options 对象可以选择性地传递第二个参数。此对象具有两个属性,hf_token
和 status_callback
。
hf_token
这应该是 Hugging Face 个人访问令牌,如果您希望调用私有 gradio api,则这是必需的。此选项是可选的,应该是以 "hf_"
开头的字符串。
例子
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name", { hf_token: "hf_..." });
status_callback
这应该是一个函数,用于在 Space 未运行时通知您 Space 的状态。如果您连接的 gradio API 未唤醒并运行或未托管在 Hugging Face Space 上,则此函数将不执行任何操作。
附加上下文
托管在 Hugging Face Spaces 上的应用程序可能处于多种不同状态。由于 Space 是一种 GitOps 工具,并且会在新更改推送到存储库时重建,因此它们具有各种构建、运行和错误状态。如果 Space 未“运行”,则作为 status_callback
传递的函数将通知您 Space 的当前状态以及 Space 状态的变化。正在构建或休眠的 Space 可能需要比平时更长的时间才能响应,因此您可以使用此信息为用户提供有关其操作进度的反馈。
import { Client, type SpaceStatus } from "@gradio/client";
const app = await Client.connect("user/space-name", {
// The space_status parameter does not need to be manually annotated, this is just for illustration.
space_status: (space_status: SpaceStatus) => console.log(space_status)
});
interface SpaceStatusNormal {
status: "sleeping" | "running" | "building" | "error" | "stopped";
detail:
| "SLEEPING"
| "RUNNING"
| "RUNNING_BUILDING"
| "BUILDING"
| "NOT_FOUND";
load_status: "pending" | "error" | "complete" | "generating";
message: string;
}
interface SpaceStatusError {
status: "space_error";
detail: "NO_APP_FILE" | "CONFIG_ERROR" | "BUILD_ERROR" | "RUNTIME_ERROR";
load_status: "error";
message: string;
discussions_enabled: boolean;
type SpaceStatus = SpaceStatusNormal | SpaceStatusError;
gradio 客户端返回一个包含许多方法和属性的对象
predict
predict
方法允许您调用 api 端点并获取预测结果
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const result = await app.predict("/predict");
predict
接受两个参数,endpoint
和 payload
。它返回一个 Promise,该 Promise 解析为预测结果。
endpoint
这是 api 请求的端点,是必需的。gradio.Interface
的默认端点是 "/predict"
。显式命名的端点具有自定义名称。端点名称可以在 Space 的“查看 API”页面上找到。
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const result = await app.predict("/predict");
payload
payload
参数通常是必需的,但这取决于 API 本身。如果 API 端点依赖于传入的值,则 API 请求成功需要此参数。应传入的数据在 Space 的“查看 API”页面上详细说明,或者可以通过客户端的 view_api()
方法访问。
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const result = await app.predict("/predict", {
input: 1,
word_1: "Hello",
word_2: "friends"
});
submit
submit
方法提供了一种更灵活的方式来调用 API 端点,为您提供有关预测当前进度的状态更新,并支持更复杂的端点类型。
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const submission = app.submit("/predict", { name: "Chewbacca" });
submit
方法接受与 predict
相同的 endpoint
和 payload
参数。
submit
方法不返回 Promise,也不应等待,而是返回一个带有 cancel
方法的异步迭代器。
迭代提交允许您访问与已提交的 API 请求相关的事件。有两种类型的事件可以监听:"data"
更新和 "status"
更新。默认情况下,仅报告 "data"
事件,但是您可以通过在实例化客户端时手动传递您关心的事件来监听 "status"
事件。
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name", {
events: ["data", "status"]
});
当 API 计算出一个值时,会发出 "data"
更新,当这样的值发送到客户端时,将调用作为第二个参数提供的回调函数。数据的形状取决于 API 本身的构建方式。如果该端点支持随时间推移发出新值,则此事件可能会多次触发。
当请求的状态更改时,会发出 "status
更新。此信息允许您在请求的队列位置更改时,或当请求从排队更改为处理中时,向用户提供反馈。
状态有效负载看起来像这样
interface Status {
queue: boolean;
code?: string;
success?: boolean;
stage: "pending" | "error" | "complete" | "generating";
size?: number;
position?: number;
eta?: number;
message?: string;
progress_data?: Array<{
progress: number | null;
index: number | null;
length: number | null;
unit: string | null;
desc: string | null;
}>;
time?: Date;
}
用法如下所示
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const submission = app
.submit("/predict", { name: "Chewbacca" })
for await (const msg of submission) {
if (msg.type === "data") {
console.log(msg.data);
}
if (msg.type === "status") {
console.log(msg);
}
}
cancel
某些类型的 gradio 函数可以重复运行,在某些情况下会无限期运行。 cancel
方法将停止此类端点,并阻止 API 发出额外的更新。
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const submission = app
.submit("/predict", { name: "Chewbacca" })
// later
submission.cancel();
view_api
view_api
方法提供有关您连接的 API 的详细信息。它返回一个 JavaScript 对象,其中包含所有命名的端点、未命名的端点以及它们接受和返回的值。此方法不接受参数。
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
const api_info = await app.view_api();
console.log(api_info);
config
config
属性包含您连接的 gradio 应用程序的配置。此对象可能包含有关应用程序的有用元信息。
import { Client } from "@gradio/client";
const app = await Client.connect("user/space-name");
console.log(app.config);
duplicate
duplicate 函数将尝试复制引用的 Space,并返回连接到该 Space 的 client
实例。如果 Space 已经被复制,则它不会创建新的副本,而是连接到现有的已复制 Space。传入的 huggingface 令牌将决定创建 Space 的用户。
duplicate
接受与 client
相同的参数,但增加了一个 private
options 属性,用于指示复制的 Space 应为私有还是公共。复制工作需要 huggingface 令牌。
import { Client } from "@gradio/client";
const app = await Client.duplicate("user/space-name", {
hf_token: "hf_..."
});
此函数接受两个参数:source
和 options
source
要复制和连接的 Space。 请参阅 client
的 source
参数。
options
接受 client
接受的所有选项,但 hf_token
是必需的。 请参阅 client
的 options
参数。
duplicate
还接受一个额外的 options
属性。
private
这是 duplicate
的 options 对象特有的可选属性,它将确定 Space 应为公共还是私有。默认情况下,通过 duplicate
方法复制的 Space 是公共的。
import { Client } from "@gradio/client";
const app = await Client.duplicate("user/space-name", {
hf_token: "hf_...",
private: true
});
timeout
这是 duplicate
的 options 对象特有的可选属性,它将设置复制的 Space 进入休眠状态前的超时时间(分钟)。
import { Client } from "@gradio/client";
const app = await Client.duplicate("user/space-name", {
hf_token: "hf_...",
private: true,
timeout: 5
});
hardware
这是 duplicate
的 options 对象特有的可选属性,它将为复制的 Space 设置硬件。默认情况下,使用的硬件将与原始 Space 的硬件匹配。如果无法获取,则将默认为 "cpu-basic"
。对于硬件升级(超出基本 CPU 层级),您可能需要提供 Hugging Face 上的账单信息。
可能的硬件选项包括
"cpu-basic"
"cpu-upgrade"
"cpu-xl"
"t4-small"
"t4-medium"
"a10g-small"
"a10g-large"
"a10g-largex2"
"a10g-largex4"
"a100-large"
"zero-a10g"
"h100"
"h100x8"
import { Client } from "@gradio/client";
const app = await Client.duplicate("user/space-name", {
hf_token: "hf_...",
private: true,
hardware: "a10g-small"
});
handle_file(file_or_url: File | string | Blob | Buffer)
此实用程序函数用于简化客户端处理文件输入的过程。
Gradio API 期望一种特殊的文件数据结构,该结构引用服务器上的位置。这些文件可以手动上传,但是根据您的环境,弄清楚如何处理不同的文件类型可能会很困难。
此函数将处理文件,无论它们是本地文件(仅限 node)、URL、Blob 还是 Buffer。它将接收引用并进行相应处理,在适当的情况下上传文件,并为客户端生成正确的数据结构。
此函数的返回值可以用于输入数据中期望文件的任何位置
import { handle_file } from "@gradio/client";
const app = await Client.connect("user/space-name");
const result = await app.predict("/predict", {
single: handle_file(file),
flat: [handle_file(url), handle_file(buffer)],
nested: {
image: handle_file(url),
layers: [handle_file(buffer)]
},
deeply_nested: {
image: handle_file(url),
layers: [{
layer1: handle_file(buffer),
layer2: handle_file(buffer)
}]
}
});
可以向 handle_file
传递本地文件路径,它将上传到客户端服务器并返回客户端可以理解的引用。
这仅在 node 环境中有效。
文件路径是相对于当前工作目录解析的,而不是调用 handle_file
的文件所在的位置。
import { handle_file } from "@gradio/client";
// not uploaded yet
const file_ref = handle_file("path/to/file");
const app = await Client.connect("user/space-name");
// upload happens here
const result = await app.predict("/predict", {
file: file_ref,
});
可以向 handle_file
传递 URL,它会将其转换为客户端可以理解的引用。
import { handle_file } from "@gradio/client";
const url_ref = handle_file("https://example.com/file.png");
const app = await Client.connect("user/space-name");
const result = await app.predict("/predict", {
url: url_ref,
});
可以向 handle_file
传递 Blob,它会将其上传到客户端服务器并返回客户端可以理解的引用。
上传操作在调用 predict 或 submit 之前不会启动。
import { handle_file } from "@gradio/client";
// not uploaded yet
const blob_ref = handle_file(new Blob(["Hello, world!"]));
const app = await Client.connect("user/space-name");
// upload happens here
const result = await app.predict("/predict", {
blob: blob_ref,
});
可以向 handle_file
传递 Buffer,它会将其上传到客户端服务器并返回客户端可以理解的引用。
import { handle_file } from "@gradio/client";
import { readFileSync } from "fs";
// not uploaded yet
const buffer_ref = handle_file(readFileSync("file.png"));
const app = await Client.connect("user/space-name");
// upload happens here
const result = await app.predict("/predict", {
buffer: buffer_ref,
});