跳到主要内容

在 Hugging Face 使用 Transformers.js

Transformers.js 是一个 JavaScript 库,用于直接在浏览器中运行 🤗 Transformers,无需服务器!它被设计为在功能上等同于原始 Python 库,这意味着你可以使用非常相似的 API 运行相同的预训练模型。

在 Hub 上探索 transformers.js

你可以通过在模型页面中按库筛选来找到 transformers.js 模型。

快速入门

从现有代码翻译非常简单!就像 Python 库一样,我们支持 pipeline API。管道将预训练模型与输入预处理和输出后处理组合在一起,使其成为使用库运行模型的最简单方法。

Python(原始)Javascript(我们的)
from transformers import pipeline

# Allocate a pipeline for sentiment-analysis
pipe = pipeline('sentiment-analysis')

out = pipe('I love transformers!')
# [{'label': 'POSITIVE', 'score': 0.999806941}]
import { pipeline } from '@huggingface/transformers';

// Allocate a pipeline for sentiment-analysis
let pipe = await pipeline('sentiment-analysis');

let out = await pipe('I love transformers!');
// [{'label': 'POSITIVE', 'score': 0.999817686}]

你还可以通过将模型 ID 或路径指定为 pipeline 函数的第二个参数来使用不同的模型。例如:

// Use a different model for sentiment-analysis
let pipe = await pipeline('sentiment-analysis', 'nlptown/bert-base-multilingual-uncased-sentiment');

有关支持的任务和模型的完整列表,请参阅文档

安装

要通过 NPM 安装,请运行:

npm i @huggingface/transformers

有关更多信息,包括如何通过 CDN 或静态托管在 vanilla JS(无任何打包器)中使用它,请参阅 README

其他资源