Transformers.js 文档

Node.js 中的服务器端推理

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

并获得增强的文档体验

开始使用

Node.js 中的服务器端推理

尽管 Transformers.js 最初设计用于浏览器,但它也能够在服务器上运行推理。在本教程中,我们将设计一个简单的 Node.js 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 的辅助类来控制管道的加载。它使用单例模式,在首次调用 getInstance 时延迟创建一个唯一的管道实例,并在所有后续调用中使用此管道。

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 查询参数,并通过管道运行它。

// 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}/`);
});

由于我们使用延迟加载,第一次向服务器发出的请求也将负责加载管道。如果您希望在服务器启动后立即开始加载管道,可以在定义 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}]

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

(可选)自定义

模型缓存

默认情况下,当您第一次运行应用程序时,它会下载模型文件并将其缓存在您的文件系统上(在 ./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 上更新