Transformers.js 文档

Node.js 中的服务端推理

您正在查看 main 版本,该版本需要从源代码安装。如果您想要常规的 npm 安装,请查看最新的稳定版本 (v3.0.0)。
Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Node.js 中的服务端推理

尽管 Transformers.js 最初设计用于浏览器,但它也能够在服务器上运行推理。在本教程中,我们将设计一个简单的 Node.js API,该 API 使用 Transformers.js 进行情感分析。

我们还将向您展示如何在 CommonJS 和 ECMAScript 模块中使用该库,以便您可以选择最适合您项目的模块系统

  • ECMAScript 模块 (ESM) - 用于重新打包 JavaScript 代码的官方标准格式。它是现代浏览器中的默认模块系统,模块使用 import 导入,使用 export 导出。幸运的是,从 13.2.0 版本开始,Node.js 已经稳定支持 ES 模块。
  • CommonJS - Node.js 中的默认模块系统。在该系统中,模块使用 require() 导入,使用 module.exports 导出。

尽管您始终可以使用 Python 库 进行服务端推理,但使用 Transformers.js 意味着您可以使用 JavaScript 编写所有代码(而无需设置和与单独的 Python 进程通信)。

实用链接

先决条件

开始入门

让我们从创建一个新的 Node.js 项目开始,并通过 NPM 安装 Transformers.js

npm init -y
npm i @huggingface/transformers

接下来,创建一个名为 app.js 的新文件,这将是我们应用程序的入口点。根据您使用的是 ECMAScript 模块 还是 CommonJS,您需要执行一些不同的操作(见下文)。

我们还将创建一个名为 MyClassificationPipeline 的辅助类来控制 pipeline 的加载。它使用 单例模式 在首次调用 getInstance 时延迟创建一个 pipeline 的单例实例,并将此 pipeline 用于所有后续调用

ECMAScript 模块 (ESM)

要指示您的项目使用 ECMAScript 模块,您需要在您的 package.json 中添加 "type": "module"

{
  ...
  "type": "module",
  ...
}

接下来,您需要在 app.js 的顶部添加以下导入

import http from 'http';
import querystring from 'querystring';
import url from 'url';

之后,让我们导入 Transformers.js 并定义 MyClassificationPipeline 类。

import { pipeline, env } from '@huggingface/transformers';

class MyClassificationPipeline {
  static task = 'text-classification';
  static model = 'Xenova/distilbert-base-uncased-finetuned-sst-2-english';
  static instance = null;

  static async getInstance(progress_callback = null) {
    if (this.instance === null) {
      // NOTE: Uncomment this to change the cache directory
      // env.cacheDir = './.cache';

      this.instance = pipeline(this.task, this.model, { progress_callback });
    }

    return this.instance;
  }
}

CommonJS

首先在 app.js 的顶部添加以下导入

const http = require('http');
const querystring = require('querystring');
const url = require('url');

之后,让我们导入 Transformers.js 并定义 MyClassificationPipeline 类。由于 Transformers.js 是一个 ESM 模块,我们将需要使用 import() 函数动态导入该库

class MyClassificationPipeline {
  static task = 'text-classification';
  static model = 'Xenova/distilbert-base-uncased-finetuned-sst-2-english';
  static instance = null;

  static async getInstance(progress_callback = null) {
    if (this.instance === null) {
      // Dynamically import the Transformers.js library
      let { pipeline, env } = await import('@huggingface/transformers');

      // NOTE: Uncomment this to change the cache directory
      // env.cacheDir = './.cache';

      this.instance = pipeline(this.task, this.model, { progress_callback });
    }

    return this.instance;
  }
}

创建一个基本的 HTTP 服务器

接下来,让我们使用内置的 HTTP 模块创建一个基本服务器。我们将监听发送到服务器的请求(使用 /classify 端点),提取 text 查询参数,并通过 pipeline 运行它。

// Define the HTTP server
const server = http.createServer();
const hostname = '127.0.0.1';
const port = 3000;

// Listen for requests made to the server
server.on('request', async (req, res) => {
  // Parse the request URL
  const parsedUrl = url.parse(req.url);

  // Extract the query parameters
  const { text } = querystring.parse(parsedUrl.query);

  // Set the response headers
  res.setHeader('Content-Type', 'application/json');

  let response;
  if (parsedUrl.pathname === '/classify' && text) {
    const classifier = await MyClassificationPipeline.getInstance();
    response = await classifier(text);
    res.statusCode = 200;
  } else {
    response = { 'error': 'Bad request' }
    res.statusCode = 400;
  }

  // Send the JSON response
  res.end(JSON.stringify(response));
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

由于我们使用了延迟加载,因此发送到服务器的第一个请求也将负责加载 pipeline。如果您希望在服务器启动运行时立即开始加载 pipeline,则可以在定义 MyClassificationPipeline 后添加以下代码行

MyClassificationPipeline.getInstance();

要启动服务器,请运行以下命令

node app.js

服务器应在 http://127.0.0.1:3000/ 上运行,您可以在 Web 浏览器中访问它。您应该看到以下消息

{"error":"Bad request"}

这是因为我们没有使用有效的 text 查询参数来定位 /classify 端点。让我们再试一次,这次使用有效的请求。例如,您可以访问 http://127.0.0.1:3000/classify?text=I%20love%20Transformers.js,您应该看到

[{"label":"POSITIVE","score":0.9996721148490906}]

太棒了!我们已成功创建了一个基本的 HTTP 服务器,该服务器使用 Transformers.js 对文本进行分类。

(可选)自定义

模型缓存

默认情况下,首次运行应用程序时,它将下载模型文件并将它们缓存在您的文件系统上(在 ./node_modules/@huggingface/transformers/.cache/ 中)。所有后续请求都将使用此模型。您可以通过设置 env.cacheDir 来更改缓存的位置。例如,要将模型缓存在当前工作目录的 .cache 目录中,您可以添加

env.cacheDir = './.cache';

使用本地模型

如果您想使用本地模型文件,您可以按如下方式设置 env.localModelPath

// Specify a custom location for models (defaults to '/models/').
env.localModelPath = '/path/to/models/';

您还可以通过将 env.allowRemoteModels 设置为 false 来禁用远程模型的加载

// Disable the loading of remote models from the Hugging Face Hub:
env.allowRemoteModels = false;
< > 在 GitHub 上更新