Transformers.js 文档

管道

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

并获得增强的文档体验

开始使用

管道

管道(Pipelines)为运行机器学习模型提供了一个高级、易于使用的 API。

示例:使用 pipeline 函数实例化管道。

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

const classifier = await pipeline('sentiment-analysis');
const output = await classifier('I love transformers!');
// [{'label': 'POSITIVE', 'score': 0.999817686}]

pipelines.Pipeline

Pipeline 类是所有管道继承的基类。不同管道之间共享的方法请参考此类。

类型pipelines 的静态类


new Pipeline(options)

创建一个新的 Pipeline。

参数量类型默认描述
选项对象

包含以下属性的对象

[options.task]字符串

管道的任务。用于指定子任务。

[options.model]PreTrainedModel

管道使用的模型。

[options.tokenizer]PreTrainedTokenizer

管道使用的分词器(如果有)。

[options.processor]处理器

管道使用的处理器(如果有)。


pipeline.dispose() : <code> DisposeType </code>

类型Pipeline 的实例方法


pipelines.TextClassificationPipeline

使用任何 ModelForSequenceClassification 的文本分类管道。

示例:使用 Xenova/distilbert-base-uncased-finetuned-sst-2-english 进行情感分析。

const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');
const output = await classifier('I love transformers!');
// [{ label: 'POSITIVE', score: 0.999788761138916 }]

示例:使用 Xenova/bert-base-multilingual-uncased-sentiment 进行多语言情感分析(并返回前 5 个类别)。

const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');
const output = await classifier('Le meilleur film de tous les temps.', { top_k: 5 });
// [
//   { label: '5 stars', score: 0.9610759615898132 },
//   { label: '4 stars', score: 0.03323351591825485 },
//   { label: '3 stars', score: 0.0036155181005597115 },
//   { label: '1 star', score: 0.0011325967498123646 },
//   { label: '2 stars', score: 0.0009423971059732139 }
// ]

示例:使用 Xenova/toxic-bert 进行恶意评论分类(并返回所有类别)。

const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');
const output = await classifier('I hate you!', { top_k: null });
// [
//   { label: 'toxic', score: 0.9593140482902527 },
//   { label: 'insult', score: 0.16187334060668945 },
//   { label: 'obscene', score: 0.03452680632472038 },
//   { label: 'identity_hate', score: 0.0223250575363636 },
//   { label: 'threat', score: 0.019197041168808937 },
//   { label: 'severe_toxic', score: 0.005651099607348442 }
// ]

类型pipelines 的静态类


new TextClassificationPipeline(options)

创建一个新的 TextClassificationPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


textClassificationPipeline._call() : <code> TextClassificationPipelineCallback </code>

类型TextClassificationPipeline 的实例方法


pipelines.TokenClassificationPipeline

使用任何 ModelForTokenClassification 的命名实体识别管道。

示例:使用 Xenova/bert-base-NER 进行命名实体识别。

const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
const output = await classifier('My name is Sarah and I live in London');
// [
//   { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' },
//   { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }
// ]

示例:使用 Xenova/bert-base-NER 进行命名实体识别(并返回所有标签)。

const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] });
// [
//   { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' },
//   { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' },
//   { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' },
//   { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' },
//   { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' },
//   { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' },
//   { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' },
//   { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' }
// ]

类型pipelines 的静态类


new TokenClassificationPipeline(options)

创建一个新的 TokenClassificationPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


tokenClassificationPipeline._call() : <code> TokenClassificationPipelineCallback </code>

类型TokenClassificationPipeline 的实例方法


pipelines.QuestionAnsweringPipeline

使用任何 ModelForQuestionAnswering 的问答管道。

示例:使用 Xenova/distilbert-base-uncased-distilled-squad 进行问答。

const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');
const question = 'Who was Jim Henson?';
const context = 'Jim Henson was a nice puppet.';
const output = await answerer(question, context);
// {
//   answer: "a nice puppet",
//   score: 0.5768911502526741
// }

类型pipelines 的静态类


new QuestionAnsweringPipeline(options)

创建一个新的 QuestionAnsweringPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


questionAnsweringPipeline._call() : <code> QuestionAnsweringPipelineCallback </code>

类型QuestionAnsweringPipeline 的实例方法


pipelines.FillMaskPipeline

使用任何 ModelWithLMHead 的掩码语言建模预测管道。

示例:使用 Xenova/bert-base-uncased 进行掩码语言建模(也称为“填空”)。

const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
const output = await unmasker('The goal of life is [MASK].');
// [
//   { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' },
//   { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' },
//   { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' },
//   { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' },
//   { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }
// ]

示例:使用 Xenova/bert-base-cased 进行掩码语言建模(也称为“填空”)(并返回最佳结果)。

const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
const output = await unmasker('The Milky Way is a [MASK] galaxy.', { top_k: 1 });
// [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]

类型pipelines 的静态类


new FillMaskPipeline(options)

创建一个新的 FillMaskPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


fillMaskPipeline._call() : <code> FillMaskPipelineCallback </code>

类型FillMaskPipeline 的实例方法


pipelines.Text2TextGenerationPipeline

用于使用执行文本到文本生成任务的模型生成文本的 Text2TextGenerationPipeline 类。

示例:使用 Xenova/LaMini-Flan-T5-783M 进行文本到文本生成。

const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');
const output = await generator('how can I become more healthy?', {
  max_new_tokens: 100,
});
// [{ generated_text: "To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues." }]

类型pipelines 的静态类


new Text2TextGenerationPipeline(options)

创建一个新的 Text2TextGenerationPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


text2TextGenerationPipeline._key : <code> ’ generated_text ’ </code>

类型Text2TextGenerationPipeline 的实例属性


text2TextGenerationPipeline._call() : <code> Text2TextGenerationPipelineCallback </code>

类型Text2TextGenerationPipeline 的实例方法


pipelines.SummarizationPipeline

一个用于摘要任务的管道,继承自 Text2TextGenerationPipeline。

示例:使用 Xenova/distilbart-cnn-6-6 进行摘要。

const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');
const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' +
  'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' +
  'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' +
  'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' +
  'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' +
  'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' +
  'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' +
  'tallest free-standing structure in France after the Millau Viaduct.';
const output = await generator(text, {
  max_new_tokens: 100,
});
// [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }]

类型pipelines 的静态类


new SummarizationPipeline(options)

创建一个新的 SummarizationPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


summarizationPipeline._key : <code> ’ summary_text ’ </code>

类型SummarizationPipeline 的实例属性


pipelines.TranslationPipeline

将文本从一种语言翻译成另一种语言。

示例:使用 Xenova/nllb-200-distilled-600M 进行多语言翻译。

有关语言及其对应代码的完整列表,请参阅这里

const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {
  src_lang: 'hin_Deva', // Hindi
  tgt_lang: 'fra_Latn', // French
});
// [{ translation_text: 'La vie est comme une boîte à chocolat.' }]

示例:使用 Xenova/m2m100_418M 进行多语言翻译。

有关语言及其对应代码的完整列表,请参阅这里

const translator = await pipeline('translation', 'Xenova/m2m100_418M');
const output = await translator('生活就像一盒巧克力。', {
  src_lang: 'zh', // Chinese
  tgt_lang: 'en', // English
});
// [{ translation_text: 'Life is like a box of chocolate.' }]

示例:使用 Xenova/mbart-large-50-many-to-many-mmt 进行多语言翻译。

有关语言及其对应代码的完整列表,请参阅这里

const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');
const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {
  src_lang: 'hi_IN', // Hindi
  tgt_lang: 'fr_XX', // French
});
// [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]

类型pipelines 的静态类


new TranslationPipeline(options)

创建一个新的 TranslationPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


translationPipeline._key : <code> ’ translation_text ’ </code>

类型TranslationPipeline 的实例属性


pipelines.TextGenerationPipeline

使用任何 ModelWithLMHeadModelForCausalLM 的语言生成管道。此管道预测指定文本提示后的词语。注意:有关生成参数的完整列表,请参阅 GenerationConfig

示例:使用 Xenova/distilgpt2 进行文本生成(默认设置)。

const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
const text = 'I enjoy walking with my cute dog,';
const output = await generator(text);
// [{ generated_text: "I enjoy walking with my cute dog, and I love to play with the other dogs." }]

示例:使用 Xenova/distilgpt2 进行文本生成(自定义设置)。

const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
const text = 'Once upon a time, there was';
const output = await generator(text, {
  temperature: 2,
  max_new_tokens: 10,
  repetition_penalty: 1.5,
  no_repeat_ngram_size: 2,
  num_beams: 2,
  num_return_sequences: 2,
});
// [{
//   "generated_text": "Once upon a time, there was an abundance of information about the history and activities that"
// }, {
//   "generated_text": "Once upon a time, there was an abundance of information about the most important and influential"
// }]

示例:使用 Xenova/codegen-350M-mono 运行代码生成。

const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');
const text = 'def fib(n):';
const output = await generator(text, {
  max_new_tokens: 44,
});
// [{
//   generated_text: 'def fib(n):\n' +
//     '    if n == 0:\n' +
//     '        return 0\n' +
//     '    elif n == 1:\n' +
//     '        return 1\n' +
//     '    else:\n' +
//     '        return fib(n-1) + fib(n-2)\n'
// }]

类型pipelines 的静态类


new TextGenerationPipeline(options)

创建一个新的 TextGenerationPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


textGenerationPipeline._call() : <code> TextGenerationPipelineCallback </code>

类型TextGenerationPipeline 的实例方法


pipelines.ZeroShotClassificationPipeline

基于自然语言推理(NLI)的零样本分类管道,使用在 NLI 任务上训练的 ModelForSequenceClassification。等同于 text-classification 管道,但这些模型不需要硬编码的潜在类别数量,可以在运行时选择。这通常意味着它速度较慢,但灵活性要强得多

示例:使用 Xenova/mobilebert-uncased-mnli 进行零样本分类。

const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');
const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.';
const labels = [ 'mobile', 'billing', 'website', 'account access' ];
const output = await classifier(text, labels);
// {
//   sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.',
//   labels: [ 'mobile', 'website', 'billing', 'account access' ],
//   scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]
// }

示例:使用 Xenova/nli-deberta-v3-xsmall 进行零样本分类(多标签)。

const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');
const text = 'I have a problem with my iphone that needs to be resolved asap!';
const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ];
const output = await classifier(text, labels, { multi_label: true });
// {
//   sequence: 'I have a problem with my iphone that needs to be resolved asap!',
//   labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ],
//   scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ]
// }

类型pipelines 的静态类


new ZeroShotClassificationPipeline(options)

创建一个新的 ZeroShotClassificationPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


zeroShotClassificationPipeline.model : <code> any </code>

类型ZeroShotClassificationPipeline 的实例属性


zeroShotClassificationPipeline._call() : <code> ZeroShotClassificationPipelineCallback </code>

类型ZeroShotClassificationPipeline 的实例方法


pipelines.FeatureExtractionPipeline

不使用模型头的特征提取管道。此管道从基础 Transformer 中提取隐藏状态,这些状态可用作下游任务的特征。

示例:使用 bert-base-uncased 运行特征提取(无池化/归一化)。

const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
const output = await extractor('This is a simple test.');
// Tensor {
//   type: 'float32',
//   data: Float32Array [0.05939924716949463, 0.021655935794115067, ...],
//   dims: [1, 8, 768]
// }

示例:使用 bert-base-uncased 运行特征提取(有池化/归一化)。

const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });
// Tensor {
//   type: 'float32',
//   data: Float32Array [0.03373778983950615, -0.010106077417731285, ...],
//   dims: [1, 768]
// }

示例:使用 sentence-transformers 模型计算嵌入。

const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });
// Tensor {
//   type: 'float32',
//   data: Float32Array [0.09094982594251633, -0.014774246141314507, ...],
//   dims: [1, 384]
// }

示例:使用 sentence-transformers 模型计算二元嵌入。

const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' });
// Tensor {
//   type: 'int8',
//   data: Int8Array [49, 108, 24, ...],
//   dims: [1, 48]
// }

类型pipelines 的静态类


new FeatureExtractionPipeline(options)

创建一个新的 FeatureExtractionPipeline。

参数量类型描述
选项TextPipelineConstructorArgs

用于实例化管道的对象。


featureExtractionPipeline._call() : <code> FeatureExtractionPipelineCallback </code>

类型FeatureExtractionPipeline 的实例方法


pipelines.ImageFeatureExtractionPipeline

不使用模型头的图像特征提取管道。此管道从基础 Transformer 中提取隐藏状态,这些状态可用作下游任务的特征。

示例:使用 Xenova/vit-base-patch16-224-in21k 进行图像特征提取。

const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k');
const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';
const features = await image_feature_extractor(url);
// Tensor {
//   dims: [ 1, 197, 768 ],
//   type: 'float32',
//   data: Float32Array(151296) [ ... ],
//   size: 151296
// }

示例:使用 Xenova/clip-vit-base-patch32 计算图像嵌入。

const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32');
const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';
const features = await image_feature_extractor(url);
// Tensor {
//   dims: [ 1, 512 ],
//   type: 'float32',
//   data: Float32Array(512) [ ... ],
//   size: 512
// }

类型pipelines 的静态类


new ImageFeatureExtractionPipeline(options)

创建一个新的 ImageFeatureExtractionPipeline。

参数量类型描述
选项ImagePipelineConstructorArgs

用于实例化管道的对象。


imageFeatureExtractionPipeline._call() : <code> ImageFeatureExtractionPipelineCallback </code>

类型ImageFeatureExtractionPipeline 的实例方法


pipelines.AudioClassificationPipeline

使用任何 AutoModelForAudioClassification 的音频分类管道。此管道预测原始波形或音频文件的类别。

示例:使用 Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech 进行音频分类。

const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
const output = await classifier(url);
// [
//   { label: 'male', score: 0.9981542229652405 },
//   { label: 'female', score: 0.001845747814513743 }
// ]

示例:使用 Xenova/ast-finetuned-audioset-10-10-0.4593 进行音频分类并返回前 4 个结果。

const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav';
const output = await classifier(url, { top_k: 4 });
// [
//   { label: 'Meow', score: 0.5617874264717102 },
//   { label: 'Cat', score: 0.22365376353263855 },
//   { label: 'Domestic animals, pets', score: 0.1141069084405899 },
//   { label: 'Animal', score: 0.08985692262649536 },
// ]

类型pipelines 的静态类


new AudioClassificationPipeline(options)

创建一个新的 AudioClassificationPipeline。

参数量类型描述
选项AudioPipelineConstructorArgs

用于实例化管道的对象。


audioClassificationPipeline._call() : <code> AudioClassificationPipelineCallback </code>

类型AudioClassificationPipeline 的实例方法


pipelines.ZeroShotAudioClassificationPipeline

使用 ClapModel 的零样本音频分类管道。当你提供一个音频和一组 candidate_labels 时,此管道会预测音频的类别。

示例:使用 Xenova/clap-htsat-unfused 进行零样本音频分类。

const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');
const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav';
const candidate_labels = ['dog', 'vaccum cleaner'];
const scores = await classifier(audio, candidate_labels);
// [
//   { score: 0.9993992447853088, label: 'dog' },
//   { score: 0.0006007603369653225, label: 'vaccum cleaner' }
// ]

类型pipelines 的静态类


new ZeroShotAudioClassificationPipeline(options)

创建一个新的 ZeroShotAudioClassificationPipeline。

参数量类型描述
选项TextAudioPipelineConstructorArgs

用于实例化管道的对象。


zeroShotAudioClassificationPipeline._call() : <code> ZeroShotAudioClassificationPipelineCallback </code>

类型ZeroShotAudioClassificationPipeline 的实例方法


pipelines.AutomaticSpeechRecognitionPipeline

旨在从音频中提取口语文本的管道。

示例:转录英语。

const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
const output = await transcriber(url);
// { text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." }

示例:带时间戳转录英语。

const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
const output = await transcriber(url, { return_timestamps: true });
// {
//   text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country."
//   chunks: [
//     { timestamp: [0, 8],  text: " And so my fellow Americans ask not what your country can do for you" }
//     { timestamp: [8, 11], text: " ask what you can do for your country." }
//   ]
// }

示例:带词级时间戳转录英语。

const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
const output = await transcriber(url, { return_timestamps: 'word' });
// {
//   "text": " And so my fellow Americans ask not what your country can do for you ask what you can do for your country.",
//   "chunks": [
//     { "text": " And", "timestamp": [0, 0.78] },
//     { "text": " so", "timestamp": [0.78, 1.06] },
//     { "text": " my", "timestamp": [1.06, 1.46] },
//     ...
//     { "text": " for", "timestamp": [9.72, 9.92] },
//     { "text": " your", "timestamp": [9.92, 10.22] },
//     { "text": " country.", "timestamp": [10.22, 13.5] }
//   ]
// }

示例:转录法语。

const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';
const output = await transcriber(url, { language: 'french', task: 'transcribe' });
// { text: " J'adore, j'aime, je n'aime pas, je déteste." }

示例:将法语翻译成英语。

const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';
const output = await transcriber(url, { language: 'french', task: 'translate' });
// { text: " I love, I like, I don't like, I hate." }

示例:转录/翻译超过 30 秒的音频。

const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav';
const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 });
// { text: " So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up" }

类型pipelines 的静态类


new AutomaticSpeechRecognitionPipeline(options)

创建一个新的 AutomaticSpeechRecognitionPipeline。

参数量类型描述
选项TextAudioPipelineConstructorArgs

用于实例化管道的对象。


automaticSpeechRecognitionPipeline._call() : <code> AutomaticSpeechRecognitionPipelineCallback </code>

类型AutomaticSpeechRecognitionPipeline 的实例方法


pipelines.ImageToTextPipeline

使用 AutoModelForVision2Seq 的图像到文本管道。此管道为给定图像预测标题。

示例:使用 Xenova/vit-gpt2-image-captioning 为图像生成标题。

const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
const output = await captioner(url);
// [{ generated_text: 'a cat laying on a couch with another cat' }]

示例:使用 Xenova/trocr-small-handwritten 进行光学字符识别(OCR)。

const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg';
const output = await captioner(url);
// [{ generated_text: 'Mr. Brown commented icily.' }]

类型pipelines 的静态类


new ImageToTextPipeline(options)

创建一个新的 ImageToTextPipeline。

参数量类型描述
选项TextImagePipelineConstructorArgs

用于实例化管道的对象。


imageToTextPipeline._call() : <code> ImageToTextPipelineCallback </code>

类型ImageToTextPipeline 的实例方法


pipelines.ImageClassificationPipeline

使用任何 AutoModelForImageClassification 的图像分类管道。此管道预测图像的类别。

示例:对图像进行分类。

const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
const output = await classifier(url);
// [
//   { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
// ]

示例:对图像进行分类并返回前 n 个类别。

const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
const output = await classifier(url, { top_k: 3 });
// [
//   { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
//   { label: 'tiger cat', score: 0.3634825646877289 },
//   { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },
// ]

示例:对图像进行分类并返回所有类别。

const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
const output = await classifier(url, { top_k: 0 });
// [
//   { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
//   { label: 'tiger cat', score: 0.3634825646877289 },
//   { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },
//   { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 },
//   ...
// ]

类型pipelines 的静态类


new ImageClassificationPipeline(options)

创建一个新的 ImageClassificationPipeline。

参数量类型描述
选项ImagePipelineConstructorArgs

用于实例化管道的对象。


imageClassificationPipeline._call() : <code> ImageClassificationPipelineCallback </code>

种类: ImageClassificationPipeline 的实例方法


pipelines.ImageSegmentationPipeline

图像分割流水线,使用任何 AutoModelForXXXSegmentation。此流水线预测物体的掩码及其类别。

示例: 使用 Xenova/detr-resnet-50-panoptic 执行图像分割。

const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
const output = await segmenter(url);
// [
//   { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } },
//   { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } }
// ]

类型pipelines 的静态类


new ImageSegmentationPipeline(options)

创建一个新的 ImageSegmentationPipeline。

参数量类型描述
选项ImagePipelineConstructorArgs

用于实例化管道的对象。


imageSegmentationPipeline._call() : <code> ImageSegmentationPipelineCallback </code>

种类: ImageSegmentationPipeline 的实例方法


pipelines.BackgroundRemovalPipeline

背景移除流水线,使用特定的 AutoModelForXXXSegmentation。此流水线用于移除图像背景。

示例: 使用 Xenova/modnet 执行背景移除。

const segmenter = await pipeline('background-removal', 'Xenova/modnet');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/portrait-of-woman_small.jpg';
const output = await segmenter(url);
// [
//   RawImage { data: Uint8ClampedArray(648000) [ ... ], width: 360, height: 450, channels: 4 }
// ]

类型pipelines 的静态类


new BackgroundRemovalPipeline(options)

创建一个新的 BackgroundRemovalPipeline。

参数量类型描述
选项ImagePipelineConstructorArgs

用于实例化管道的对象。


backgroundRemovalPipeline._call() : <code> BackgroundRemovalPipelineCallback </code>

种类: BackgroundRemovalPipeline 的实例方法


pipelines.ZeroShotImageClassificationPipeline

零样本图像分类流水线。当您提供一张图像和一组 candidate_labels(候选标签)时,此流水线会预测图像的类别。

示例: 使用 Xenova/clip-vit-base-patch32 进行零样本图像分类。

const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
const output = await classifier(url, ['tiger', 'horse', 'dog']);
// [
//   { score: 0.9993917942047119, label: 'tiger' },
//   { score: 0.0003519294841680676, label: 'horse' },
//   { score: 0.0002562698791734874, label: 'dog' }
// ]

类型pipelines 的静态类


new ZeroShotImageClassificationPipeline(options)

创建一个新的 ZeroShotImageClassificationPipeline。

参数量类型描述
选项TextImagePipelineConstructorArgs

用于实例化管道的对象。


zeroShotImageClassificationPipeline._call() : <code> ZeroShotImageClassificationPipelineCallback </code>

种类: ZeroShotImageClassificationPipeline 的实例方法


pipelines.ObjectDetectionPipeline

物体检测流水线,使用任何 AutoModelForObjectDetection。此流水线预测物体的边界框及其类别。

示例: 使用 Xenova/detr-resnet-50 运行物体检测。

const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');
const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
const output = await detector(img, { threshold: 0.9 });
// [{
//   score: 0.9976370930671692,
//   label: "remote",
//   box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 }
// },
// ...
// {
//   score: 0.9984092116355896,
//   label: "cat",
//   box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 }
// }]

类型pipelines 的静态类


new ObjectDetectionPipeline(options)

创建一个新的 ObjectDetectionPipeline。

参数量类型描述
选项ImagePipelineConstructorArgs

用于实例化管道的对象。


objectDetectionPipeline._call() : <code> ObjectDetectionPipelineCallback </code>

种类: ObjectDetectionPipeline 的实例方法


pipelines.ZeroShotObjectDetectionPipeline

零样本物体检测流水线。当您提供一张图像和一组 candidate_labels(候选标签)时,此流水线会预测物体的边界框。

示例: 使用 Xenova/owlvit-base-patch32 进行零样本物体检测。

const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png';
const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag'];
const output = await detector(url, candidate_labels);
// [
//   {
//     score: 0.24392342567443848,
//     label: 'human face',
//     box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 }
//   },
//   {
//     score: 0.15129457414150238,
//     label: 'american flag',
//     box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 }
//   },
//   {
//     score: 0.13649864494800568,
//     label: 'helmet',
//     box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 }
//   },
//   {
//     score: 0.10262022167444229,
//     label: 'rocket',
//     box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 }
//   }
// ]

示例: 使用 Xenova/owlvit-base-patch32 进行零样本物体检测(返回前 4 个匹配项并设置阈值)。

const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png';
const candidate_labels = ['hat', 'book', 'sunglasses', 'camera'];
const output = await detector(url, candidate_labels, { top_k: 4, threshold: 0.05 });
// [
//   {
//     score: 0.1606510728597641,
//     label: 'sunglasses',
//     box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 }
//   },
//   {
//     score: 0.08935828506946564,
//     label: 'hat',
//     box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 }
//   },
//   {
//     score: 0.08530698716640472,
//     label: 'camera',
//     box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 }
//   },
//   {
//     score: 0.08349756896495819,
//     label: 'book',
//     box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 }
//   }
// ]

类型pipelines 的静态类


new ZeroShotObjectDetectionPipeline(options)

创建一个新的 ZeroShotObjectDetectionPipeline。

参数量类型描述
选项TextImagePipelineConstructorArgs

用于实例化管道的对象。


zeroShotObjectDetectionPipeline._call() : <code> ZeroShotObjectDetectionPipelineCallback </code>

种类: ZeroShotObjectDetectionPipeline 的实例方法


pipelines.DocumentQuestionAnsweringPipeline

文档问答流水线,使用任何 AutoModelForDocumentQuestionAnswering。其输入/输出与(抽取式)问答流水线相似;但是,该流水线接受图像(以及可选的 OCR 识别出的单词/边界框)作为输入,而不是文本上下文。

示例: 使用 Xenova/donut-base-finetuned-docvqa 回答关于文档的问题。

const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');
const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';
const question = 'What is the invoice number?';
const output = await qa_pipeline(image, question);
// [{ answer: 'us-001' }]

类型pipelines 的静态类


new DocumentQuestionAnsweringPipeline(options)

创建一个新的 DocumentQuestionAnsweringPipeline。

参数量类型描述
选项TextImagePipelineConstructorArgs

用于实例化管道的对象。


documentQuestionAnsweringPipeline._call() : <code> DocumentQuestionAnsweringPipelineCallback </code>

种类: DocumentQuestionAnsweringPipeline 的实例方法


pipelines.TextToAudioPipeline

文本转音频生成流水线,使用任何 AutoModelForTextToWaveformAutoModelForTextToSpectrogram。此流水线根据输入文本和可选的其他条件输入生成音频文件。

示例: 使用 Xenova/speecht5_tts 从文本生成音频。

const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });
const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin';
const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings });
// RawAudio {
//   audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...],
//   sampling_rate: 16000
// }

然后,您可以使用 wavefile 包将音频保存为 .wav 文件。

import wavefile from 'wavefile';
import fs from 'fs';

const wav = new wavefile.WaveFile();
wav.fromScratch(1, out.sampling_rate, '32f', out.audio);
fs.writeFileSync('out.wav', wav.toBuffer());

示例: 使用 Xenova/mms-tts-fra 进行多语言语音生成。请参阅此处获取可用语言的完整列表(1107种)。

const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');
const out = await synthesizer('Bonjour');
// RawAudio {
//   audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...],
//   sampling_rate: 16000
// }

类型pipelines 的静态类


new TextToAudioPipeline(options)

创建一个新的 TextToAudioPipeline。

参数量类型描述
选项TextToAudioPipelineConstructorArgs

用于实例化管道的对象。


textToAudioPipeline._call() : <code> TextToAudioPipelineCallback </code>

种类: TextToAudioPipeline 的实例方法


pipelines.ImageToImagePipeline

图像到图像流水线,使用任何 AutoModelForImageToImage。此流水线根据先前的图像输入生成新图像。

示例: 使用 Xenova/swin2SR-classical-sr-x2-64 进行超分辨率处理

const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';
const output = await upscaler(url);
// RawImage {
//   data: Uint8Array(786432) [ 41, 31, 24,  43, ... ],
//   width: 512,
//   height: 512,
//   channels: 3
// }

类型pipelines 的静态类


new ImageToImagePipeline(options)

创建一个新的 ImageToImagePipeline。

参数量类型描述
选项ImagePipelineConstructorArgs

用于实例化管道的对象。


imageToImagePipeline._call() : <code> ImageToImagePipelineCallback </code>

种类: ImageToImagePipeline 的实例方法


pipelines.DepthEstimationPipeline

深度估计流水线,使用任何 AutoModelForDepthEstimation。此流水线预测图像的深度。

示例: 使用 Xenova/dpt-hybrid-midas 进行深度估计

const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');
const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
const out = await depth_estimator(url);
// {
//   predicted_depth: Tensor {
//     dims: [ 384, 384 ],
//     type: 'float32',
//     data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ],
//     size: 147456
//   },
//   depth: RawImage {
//     data: Uint8Array(307200) [ 86, 86, 86, ... ],
//     width: 640,
//     height: 480,
//     channels: 1
//   }
// }

类型pipelines 的静态类


new DepthEstimationPipeline(options)

创建一个新的 DepthEstimationPipeline。

参数量类型描述
选项ImagePipelineConstructorArgs

用于实例化管道的对象。


depthEstimationPipeline._call() : <code> DepthEstimationPipelineCallback </code>

种类: DepthEstimationPipeline 的实例方法


pipelines.pipeline(task, [model], [options]) ⇒ <code> * </code>

用于构建 Pipeline 对象的实用工厂方法。

种类: pipelines 的静态方法
返回: * - 针对指定任务的 Pipeline 对象。
抛出:

  • Error 如果请求了不支持的流水线。
参数量类型默认描述
任务任务

定义将返回哪个流水线的任务。当前接受的任务有:

  • "audio-classification": 将返回一个 AudioClassificationPipeline
  • "automatic-speech-recognition": 将返回一个 AutomaticSpeechRecognitionPipeline
  • "depth-estimation": 将返回一个 DepthEstimationPipeline
  • "document-question-answering": 将返回一个 DocumentQuestionAnsweringPipeline
  • "feature-extraction": 将返回一个 FeatureExtractionPipeline
  • "fill-mask": 将返回一个 FillMaskPipeline
  • "image-classification": 将返回一个 ImageClassificationPipeline
  • "image-segmentation": 将返回一个 ImageSegmentationPipeline
  • "image-to-text": 将返回一个 ImageToTextPipeline
  • "object-detection": 将返回一个 ObjectDetectionPipeline
  • "question-answering": 将返回一个 QuestionAnsweringPipeline
  • "summarization": 将返回一个 SummarizationPipeline
  • "text2text-generation": 将返回一个 Text2TextGenerationPipeline
  • "text-classification" (别名 "sentiment-analysis" 可用): 将返回一个 TextClassificationPipeline
  • "text-generation": 将返回一个 TextGenerationPipeline
  • "token-classification" (别名 "ner" 可用): 将返回一个 TokenClassificationPipeline
  • "translation": 将返回一个 TranslationPipeline
  • "translation_xx_to_yy": 将返回一个 TranslationPipeline
  • "zero-shot-classification": 将返回一个 ZeroShotClassificationPipeline
  • "zero-shot-audio-classification": 将返回一个 ZeroShotAudioClassificationPipeline
  • "zero-shot-image-classification": 将返回一个 ZeroShotImageClassificationPipeline
  • "zero-shot-object-detection": 将返回一个 ZeroShotObjectDetectionPipeline
[model]字符串null

要使用的预训练模型的名称。如果未指定,将使用该任务的默认模型。

[options]*

流水线的可选参数。


pipelines~ImagePipelineInputs : <code> string </code> | <code> RawImage </code> | <code> URL </code> | <code> Blob </code> | <code> HTMLCanvasElement </code> | <code> OffscreenCanvas </code>

种类: pipelines 的内部类型定义


pipelines~AudioPipelineInputs : <code> string </code> | <code> URL </code> | <code> Float32Array </code> | <code> Float64Array </code>

种类: pipelines 的内部类型定义


pipelines~BoundingBox : <code> Object </code>

种类: pipelines 的内部类型定义
属性

名称类型描述
xmin数字

边界框的最小 x 坐标。

ymin数字

边界框的最小 y 坐标。

xmax数字

边界框的最大 x 坐标。

ymax数字

边界框的最大 y 坐标。


pipelines~Disposable ⇒ <code> Promise. < void > </code>

种类: pipelines 的内部类型定义
返回: Promise.<void> - 一个在项目被释放时解析的 Promise。
属性

名称类型描述
disposeDisposeType

一个在流水线被释放时解析的 Promise。


pipelines~TextPipelineConstructorArgs : <code> Object </code>

用于实例化基于文本的流水线的对象。

种类: pipelines 的内部类型定义
属性

名称类型描述
任务字符串

管道的任务。用于指定子任务。

模型PreTrainedModel

管道使用的模型。

tokenizerPreTrainedTokenizer

流水线使用的分词器。


pipelines~ImagePipelineConstructorArgs : <code> Object </code>

用于实例化基于音频的流水线的对象。

种类: pipelines 的内部类型定义
属性

名称类型描述
任务字符串

管道的任务。用于指定子任务。

模型PreTrainedModel

管道使用的模型。

processor处理器

流水线使用的处理器。


pipelines~TextImagePipelineConstructorArgs : <code> Object </code>

用于实例化基于文本和音频的流水线的对象。

种类: pipelines 的内部类型定义
属性

名称类型描述
任务字符串

管道的任务。用于指定子任务。

模型PreTrainedModel

管道使用的模型。

tokenizerPreTrainedTokenizer

流水线使用的分词器。

processor处理器

流水线使用的处理器。


pipelines~TextClassificationPipelineType ⇒ <code> Promise. < (TextClassificationOutput|Array < TextClassificationOutput > ) > </code>

特定于文本分类流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(TextClassificationOutput|Array<TextClassificationOutput>)> - 包含预测标签和分数的数组或对象。

参数量类型描述
textsstring | Array<string>

要分类的输入文本。

[options]TextClassificationPipelineOptions

用于文本分类的选项。

属性

名称类型默认描述
label字符串

预测的标签。

score数字

对应的概率。

[top_k]数字1

要返回的最高预测数量。


pipelines~TokenClassificationPipelineType ⇒ <code> Promise. < (TokenClassificationOutput|Array < TokenClassificationOutput > ) > </code>

特定于词元分类流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(TokenClassificationOutput|Array<TokenClassificationOutput>)> - 结果。

参数量类型描述
textsstring | Array<string>

一个或多个用于词元分类的文本(或一个文本列表)。

[options]TokenClassificationPipelineOptions

用于词元分类的选项。

属性

名称类型描述
word字符串

被分类的词元/单词。这是通过解码所选词元获得的。

score数字

entity 对应的概率。

entity字符串

为该词元/单词预测的实体。

索引数字

相应词元在句子中的索引。

[start]数字

相应实体在句子中的起始索引。

[end]数字

相应实体在句子中的结束索引。

[ignore_labels]Array.<string>

要忽略的标签列表。


pipelines~QuestionAnsweringPipelineType ⇒ <code> Promise. < (QuestionAnsweringOutput|Array < QuestionAnsweringOutput > ) > </code>

特定于问答流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(QuestionAnsweringOutput|Array<QuestionAnsweringOutput>)> - 包含预测答案和分数的数组或对象。

参数量类型描述
questionstring | Array<string>

一个或多个问题(必须与 context 参数一起使用)。

contextstring | Array<string>

与问题相关联的一个或多个上下文(必须与 question 参数一起使用)。

[options]QuestionAnsweringPipelineOptions

用于问答的选项。

属性

名称类型默认描述
score数字

与答案相关的概率。

[start]数字

答案的字符起始索引(在输入的词元化版本中)。

[end]数字

答案的字符结束索引(在输入的词元化版本中)。

答案字符串

问题的答案。

[top_k]数字1

要返回的最高答案预测数量。


pipelines~FillMaskPipelineType ⇒ <code> Promise. < (FillMaskOutput|Array < FillMaskOutput > ) > </code>

特定于填空流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(FillMaskOutput|Array<FillMaskOutput>)> - 一个包含分数、预测词元、预测词元字符串和已填充预测词元序列的对象数组,或者此类数组的数组(每个输入文本一个)。如果只给出一个输入文本,输出将是一个对象数组。
抛出:

  • Error 当在输入文本中找不到掩码词元时。
参数量类型描述
textsstring | Array<string>

一个或多个带有掩码词元的文本(或一个提示列表)。

[options]FillMaskPipelineOptions

用于掩码语言建模的选项。

属性

名称类型默认描述
sequence字符串

带有掩码词元预测的相应输入。

score数字

对应的概率。

token数字

预测的词元ID(用于替换掩码词元)。

token_str字符串

预测的词元(用于替换掩码词元)。

[top_k]数字5

当传递时,覆盖要返回的预测数量。


pipelines~Text2TextGenerationPipelineType ⇒ <code> Promise. < (Text2TextGenerationOutput|Array < Text2TextGenerationOutput > ) > </code>

种类: pipelines 的内部类型定义

参数量类型描述
textsstring | Array<string>

编码器的输入文本。

[options]*

传递给模型 generate 方法的其他关键字参数。

属性

名称类型描述
generated_text字符串

生成的文本。


pipelines~SummarizationPipelineType ⇒ <code> Promise. < (SummarizationOutput|Array < SummarizationOutput > ) > </code>

种类: pipelines 的内部类型定义

参数量类型描述
textsstring | Array<string>

要摘要的一篇或多篇文章(或一个文章列表)。

[options]*

传递给模型 generate 方法的其他关键字参数。

属性

名称类型描述
summary_text字符串

摘要文本。


pipelines~TranslationPipelineType ⇒ <code> Promise. < (TranslationOutput|Array < TranslationOutput > ) > </code>

种类: pipelines 的内部类型定义

参数量类型描述
textsstring | Array<string>

待翻译的文本。

[options]*

传递给模型 generate 方法的其他关键字参数。

属性

名称类型描述
translation_text字符串

翻译后的文本。


pipelines~TextGenerationPipelineType ⇒ <code> Promise. < (TextGenerationOutput|Array < TextGenerationOutput > ) > </code>

特定于文本生成流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(TextGenerationOutput|Array<TextGenerationOutput>)> - 包含生成文本的数组或对象。

参数量类型描述
textsstring | Array<string> | Chat | Array<Chat>

一个或多个待补全的提示(或一个提示列表)。

[options]Partial.<TextGenerationConfig>

传递给模型 generate 方法的其他关键字参数。

属性

名称类型默认描述
generated_textstring | Chat

生成的文本。

[add_special_tokens]boolean

在对序列进行词元化时是否添加特殊词元。

[return_full_text]booleantrue

如果设置为 false,则仅返回新增的文本,否则返回全文。


pipelines~ZeroShotClassificationPipelineType ⇒ <code> Promise. < (ZeroShotClassificationOutput|Array < ZeroShotClassificationOutput > ) > </code>

特定于零样本分类流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(ZeroShotClassificationOutput|Array<ZeroShotClassificationOutput>)> - 包含预测标签和分数的数组或对象。

参数量类型描述
textsstring | Array<string>

要分类的序列,如果模型输入过大,将被截断。

candidate_labelsstring | Array<string>

用于将每个序列分类的可能类别标签集合。可以是一个标签、一个逗号分隔的标签字符串或一个标签列表。

[options]ZeroShotClassificationPipelineOptions

用于零样本分类的选项。

属性

名称类型默认描述
sequence字符串

此输出对应的序列。

labelsArray.<string>

按可能性顺序排序的标签。

scoresArray.<number>

每个标签的概率。

[hypothesis_template]字符串""这个例子是{}。""

用于将每个候选标签转换为 NLI 风格假设的模板。候选标签将替换 &#123;} 占位符。

[multi_label]booleanfalse

是否可以有多个候选标签为真。如果为 false,则分数将被归一化,使得每个序列的标签似然总和为1。如果为 true,则标签被视为独立的,并通过对蕴含分数与矛盾分数进行 softmax 来为每个候选标签归一化概率。


pipelines~FeatureExtractionPipelineType ⇒ <code> Promise. < Tensor > </code>

特定于特征提取流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<Tensor> - 模型计算出的特征。

参数量类型描述
textsstring | Array<string>

一个或多个要提取特征的文本(或一个文本列表)。

[options]FeatureExtractionPipelineOptions

用于特征提取的选项。

属性

名称类型默认描述
[pooling]'none' | 'mean' | 'cls' | 'first_token' | 'eos' | 'last_token'"none"

要使用的池化方法。

[normalize]booleanfalse

是否在最后一个维度上对嵌入进行归一化。

[quantize]booleanfalse

是否对嵌入进行量化。

[precision]'binary' | 'ubinary''binary'

用于量化的精度。


pipelines~ImageFeatureExtractionPipelineType ⇒ <code> Promise. < Tensor > </code>

特定于图像特征提取流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<Tensor> - 模型计算出的图像特征。

参数量类型描述
imagesImagePipelineInputs

一个或多个要提取特征的图像(或一个图像列表)。

[options]ImageFeatureExtractionPipelineOptions

用于图像特征提取的选项。

属性

名称类型默认描述
[pool]boolean

是否返回池化后的输出。如果设置为 false,模型将返回原始的隐藏状态。


pipelines~AudioClassificationPipelineType ⇒ <code> Promise. < (AudioClassificationOutput|Array < AudioClassificationOutput > ) > </code>

特定于音频分类流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(AudioClassificationOutput|Array<AudioClassificationOutput>)> - 包含预测标签和分数的数组或对象。

参数量类型描述
音频AudioPipelineInputs

要分类的输入音频文件。输入可以是

  • stringURL,即音频文件的文件名/URL,文件将以处理器的采样率读取,使用 AudioContext API 获取波形。如果 AudioContext 不可用,您应以形状为 (n, ) 的 Float32Array 形式传入原始波形。
  • 形状为 (n, )Float32ArrayFloat64Array,表示正确采样率下的原始音频(不会进行进一步检查)。
[options]AudioClassificationPipelineOptions

用于音频分类的选项。

属性

名称类型默认描述
label字符串

预测的标签。

score数字

对应的概率。

[top_k]数字5

流水线将返回的最高标签数量。如果提供的数量为 null 或高于模型配置中可用的标签数量,则将默认为标签数量。


pipelines~ZeroShotAudioClassificationPipelineType ⇒ <code> Promise. < (Array < ZeroShotAudioClassificationOutput > |Array < Array < ZeroShotAudioClassificationOutput > > ) > </code>

特定于零样本音频分类流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(Array<ZeroShotAudioClassificationOutput>|Array<Array<ZeroShotAudioClassificationOutput>>)> - 包含预测标签和分数的对象数组。

参数量类型描述
音频AudioPipelineInputs

要分类的输入音频文件。输入可以是

  • stringURL,即音频文件的文件名/URL,文件将以处理器的采样率读取,使用 AudioContext API 获取波形。如果 AudioContext 不可用,您应以形状为 (n, ) 的 Float32Array 形式传入原始波形。
  • 形状为 (n, )Float32ArrayFloat64Array,表示正确采样率下的原始音频(不会进行进一步检查)。
candidate_labelsArray.<string>

此音频的候选标签。

[options]ZeroShotAudioClassificationPipelineOptions

用于零样本音频分类的选项。

属性

名称类型默认描述
label字符串

模型识别的标签。它是建议的 candidate_label 之一。

score数字

模型为该标签赋予的分数(介于0和1之间)。

[hypothesis_template]字符串""这是一个{}的声音。""

candidate_labels 结合使用的句子,通过用候选标签替换占位符来尝试进行音频分类。然后使用 logits_per_audio 估计可能性。


pipelines~Chunk : <code> Object </code>

种类: pipelines 的内部类型定义
属性

名称类型描述
时间戳*

块的开始和结束时间戳(以秒为单位)。

text字符串

识别出的文本。


pipelines~AutomaticSpeechRecognitionPipelineType ⇒ <code> Promise. < (AutomaticSpeechRecognitionOutput|Array < AutomaticSpeechRecognitionOutput > ) > </code>

特定于自动语音识别流水线的参数。

种类: pipelines 的内部类型定义
返回: Promise.<(AutomaticSpeechRecognitionOutput|Array<AutomaticSpeechRecognitionOutput>)> - 包含转录文本的对象,如果 return_timestampstrue,则还包含时间戳。

参数量类型描述
音频AudioPipelineInputs

待转录的输入音频文件。

  • stringURL,即音频文件的文件名/URL,文件将以处理器的采样率读取,使用 AudioContext API 获取波形。如果 AudioContext 不可用,您应以形状为 (n, ) 的 Float32Array 形式传入原始波形。
  • 形状为 (n, )Float32ArrayFloat64Array,表示正确采样率下的原始音频(不会进行进一步检查)。
[options]Partial.<AutomaticSpeechRecognitionConfig>

传递给模型 generate 方法的其他关键字参数。

属性

名称类型描述
text字符串

识别出的文本。

[chunks]Array.<Chunk>

当使用 return_timestamps 时,chunks 将成为一个包含模型识别出的所有不同文本块的列表。

[return_timestamps]boolean | 'word'

是否返回时间戳。默认为 false

[chunk_length_s]数字

要处理的音频块的长度(以秒为单位)。默认为 0(不分块)。

[stride_length_s]数字

连续音频块之间的重叠长度(以秒为单位)。如果未提供,则默认为 chunk_length_s / 6

[force_full_sequences]boolean

是否强制输出完整序列。默认为 false

[language]字符串

源语言。默认为 null,表示应自动检测。如果源语言已知,使用此选项可能会提高性能。

[task]字符串

要执行的任务。默认为 null,表示应自动检测。

[num_frames]数字

输入音频中的帧数。


pipelines~ImageToTextPipelineType ⇒ <code> Promise. < (ImageToTextOutput|Array < ImageToTextOutput > ) > </code>

种类: pipelines 的内部类型定义
返回: Promise.<(ImageToTextOutput|Array<ImageToTextOutput>)> - 包含生成文本的对象(或对象数组)。

参数量类型描述
textsImagePipelineInputs

待加标题的图像。

[options]*

传递给模型 generate 方法的其他关键字参数。

属性

名称类型描述
generated_text字符串

生成的文本。


pipelines~ImageClassificationPipelineType ⇒ <code> Promise. < (ImageClassificationOutput|Array < ImageClassificationOutput > ) > </code>

特定于图像分类管道的参数。

种类: pipelines 的内部类型定义
返回Promise.<(ImageClassificationOutput|Array<ImageClassificationOutput>)> - 包含预测标签和分数的数组或对象。

参数量类型描述
imagesImagePipelineInputs

要分类的输入图像。

[options]ImageClassificationPipelineOptions

用于图像分类的选项。

属性

名称类型默认描述
label字符串

模型识别的标签。

score数字

模型为该标签赋予的分数。

[top_k]数字1

管道将返回的排名靠前的标签数量。


pipelines~ImageSegmentationPipelineType ⇒ <code> Promise. < Array < ImageSegmentationPipelineOutput > > </code>

特定于图像分割管道的参数。

种类: pipelines 的内部类型定义
返回Promise.<Array<ImageSegmentationPipelineOutput>> - 带标注的分割区域。

参数量类型描述
imagesImagePipelineInputs

输入图像。

[options]ImageSegmentationPipelineOptions

用于图像分割的选项。

属性

名称类型默认描述
labelstring | null

分割区域的标签。

scorenumber | null

分割区域的分数。

蒙版RawImage

分割区域的掩码。

[threshold]数字0.5

用于过滤预测掩码的概率阈值。

[mask_threshold]数字0.5

将预测掩码转换为二进制值时使用的阈值。

[overlap_mask_area_threshold]数字0.8

用于消除小的、不连通分割区域的掩码重叠阈值。

[subtask]null | string

要执行的分割任务。根据模型的能力,可以是 [panopticinstancesemantic] 中的一种。如果未设置,管道将按此顺序尝试解析。

[label_ids_to_fuse]Array.<number>

要融合的标签 ID 列表。如果未设置,则不融合任何标签。

[target_sizes]Array.<Array<number>>

输入图像的目标尺寸列表。如果未设置,则使用原始图像尺寸。


pipelines~BackgroundRemovalPipelineType ⇒ <code> Promise. < Array < RawImage > > </code>

特定于图像分割管道的参数。

种类: pipelines 的内部类型定义
返回Promise.<Array<RawImage>> - 已移除背景的图像。

参数量类型描述
imagesImagePipelineInputs

输入图像。

[options]BackgroundRemovalPipelineOptions

用于图像分割的选项。


pipelines~ZeroShotImageClassificationPipelineType ⇒ <code> Promise. < (Array < ZeroShotImageClassificationOutput > |Array < Array < ZeroShotImageClassificationOutput > > ) > </code>

特定于零样本图像分类管道的参数。

种类: pipelines 的内部类型定义
返回Promise.<(Array<ZeroShotImageClassificationOutput>|Array<Array<ZeroShotImageClassificationOutput>>)> - 包含预测标签和分数的对象数组。

参数量类型描述
imagesImagePipelineInputs

输入图像。

candidate_labelsArray.<string>

此图像的候选标签。

[options]ZeroShotImageClassificationPipelineOptions

用于零样本图像分类的选项。

属性

名称类型默认描述
label字符串

模型识别的标签。它是建议的 candidate_label 之一。

score数字

模型为该标签赋予的分数(介于0和1之间)。

[hypothesis_template]字符串""这是一张{}的照片""

candidate_labels 结合使用的句子,通过将占位符替换为候选标签来尝试进行图像分类。然后使用 logits_per_image 估计可能性。


pipelines~ObjectDetectionPipelineType ⇒ <code> Promise. < (ObjectDetectionPipelineOutput|Array < ObjectDetectionPipelineOutput > ) > </code>

特定于目标检测管道的参数。

种类: pipelines 的内部类型定义
返回Promise.<(ObjectDetectionPipelineOutput|Array<ObjectDetectionPipelineOutput>)> - 对象列表或对象列表的列表。

参数量类型描述
imagesImagePipelineInputs

输入图像。

[options]ObjectDetectionPipelineOptions

用于目标检测的选项。

属性

名称类型默认描述
label字符串

模型识别的类别标签。

score数字

模型为该标签赋予的分数。

boxBoundingBox

检测到的对象在图像原始尺寸中的边界框,如果 percentage 设置为 true,则为百分比。

[threshold]数字0.9

用于按分数筛选边界框的阈值。

[percentage]booleanfalse

是否以百分比(true)或像素(false)返回边界框坐标。


pipelines~ZeroShotObjectDetectionPipelineType ⇒ <code> Promise. < (Array < ZeroShotObjectDetectionOutput > |Array < Array < ZeroShotObjectDetectionOutput > > ) > </code>

特定于零样本目标检测管道的参数。

种类: pipelines 的内部类型定义
返回Promise.<(Array<ZeroShotObjectDetectionOutput>|Array<Array<ZeroShotObjectDetectionOutput>>)> - 包含预测标签、分数和边界框的对象数组。

参数量类型描述
imagesImagePipelineInputs

输入图像。

candidate_labelsArray.<string>

模型应在图像中识别的内容。

[options]ZeroShotObjectDetectionPipelineOptions

用于零样本目标检测的选项。

属性

名称类型默认描述
label字符串

与找到的对象对应的文本查询。

score数字

与对象对应的分数(介于 0 和 1 之间)。

boxBoundingBox

检测到的对象在图像原始尺寸中的边界框,如果 percentage 设置为 true,则为百分比。

[threshold]数字0.1

做出预测所需的概率。

[top_k]数字

管道将返回的排名靠前的预测数量。如果提供的数字为 null 或高于可用预测的数量,则将默认为预测的总数。

[percentage]booleanfalse

是否以百分比(true)或像素(false)返回边界框坐标。


pipelines~DocumentQuestionAnsweringPipelineType ⇒ <code> Promise. < (DocumentQuestionAnsweringOutput|Array < DocumentQuestionAnsweringOutput > ) > </code>

种类: pipelines 的内部类型定义
返回Promise.<(DocumentQuestionAnsweringOutput|Array<DocumentQuestionAnsweringOutput>)> - 包含答案的对象(或对象数组)。

参数量类型描述
imageImageInput

要使用的文档图像。

question字符串

要对文档提出的问题。

[options]*

传递给模型 generate 方法的其他关键字参数。

属性

名称类型描述
答案字符串

生成的文本。


pipelines~TextToAudioPipelineConstructorArgs : <code> Object </code>

种类: pipelines 的内部类型定义
属性

名称类型描述
[vocoder]PreTrainedModel

管道使用的声码器(如果模型使用)。如果未提供,则使用默认的 HifiGan 声码器。


pipelines~TextToAudioPipelineType ⇒ <code> Promise. < TextToAudioOutput > </code>

特定于文本到音频管道的参数。

种类: pipelines 的内部类型定义
返回Promise.<TextToAudioOutput> - 包含生成的音频和采样率的对象。

参数量类型描述
textsstring | Array<string>

要生成的文本。

选项TextToAudioPipelineOptions

传递给模型生成/前向方法的参数。

属性

名称类型默认描述
音频Float32Array

生成的音频波形。

sampling_rate数字

生成的音频波形的采样率。

[speaker_embeddings]Tensor | Float32Array | string | URL

说话人嵌入(如果模型需要)。


pipelines~ImageToImagePipelineType ⇒ <code> Promise. < (RawImage|Array < RawImage > ) > </code>

种类: pipelines 的内部类型定义
返回Promise.<(RawImage|Array<RawImage>)> - 转换后的图像或图像列表。

参数量类型描述
imagesImagePipelineInputs

要转换的图像。


pipelines~DepthEstimationPipelineType ⇒ <code> Promise. < (DepthEstimationPipelineOutput|Array < DepthEstimationPipelineOutput > ) > </code>

种类: pipelines 的内部类型定义
返回Promise.<(DepthEstimationPipelineOutput|Array<DepthEstimationPipelineOutput>)> - 包含结果的图像或图像列表。

参数量类型描述
imagesImagePipelineInputs

要计算深度的图像。

属性

名称类型描述
predicted_depth张量

模型预测的原始深度图。

depthRawImage

处理后的深度图,作为图像(与输入图像大小相同)。


pipelines~AllTasks : <code> * </code>

所有可能的管道类型。

种类: pipelines 的内部类型定义


< > 在 GitHub 上更新