@huggingface/transformers 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +376 -0
  3. package/dist/ort-wasm-simd-threaded.jsep.wasm +0 -0
  4. package/dist/transformers.cjs +30741 -0
  5. package/dist/transformers.cjs.map +1 -0
  6. package/dist/transformers.js +33858 -0
  7. package/dist/transformers.js.map +1 -0
  8. package/dist/transformers.min.cjs +173 -0
  9. package/dist/transformers.min.cjs.map +1 -0
  10. package/dist/transformers.min.js +231 -0
  11. package/dist/transformers.min.js.map +1 -0
  12. package/package.json +92 -0
  13. package/src/backends/onnx.js +151 -0
  14. package/src/configs.js +360 -0
  15. package/src/env.js +152 -0
  16. package/src/generation/configuration_utils.js +381 -0
  17. package/src/generation/logits_process.js +716 -0
  18. package/src/generation/logits_sampler.js +204 -0
  19. package/src/generation/parameters.js +35 -0
  20. package/src/generation/stopping_criteria.js +156 -0
  21. package/src/generation/streamers.js +212 -0
  22. package/src/models/whisper/common_whisper.js +151 -0
  23. package/src/models/whisper/generation_whisper.js +89 -0
  24. package/src/models.js +7028 -0
  25. package/src/ops/registry.js +92 -0
  26. package/src/pipelines.js +3341 -0
  27. package/src/processors.js +2614 -0
  28. package/src/tokenizers.js +4395 -0
  29. package/src/transformers.js +28 -0
  30. package/src/utils/audio.js +704 -0
  31. package/src/utils/constants.js +2 -0
  32. package/src/utils/core.js +149 -0
  33. package/src/utils/data-structures.js +445 -0
  34. package/src/utils/devices.js +11 -0
  35. package/src/utils/dtypes.js +62 -0
  36. package/src/utils/generic.js +35 -0
  37. package/src/utils/hub.js +671 -0
  38. package/src/utils/image.js +745 -0
  39. package/src/utils/maths.js +1050 -0
  40. package/src/utils/tensor.js +1378 -0
  41. package/types/backends/onnx.d.ts +26 -0
  42. package/types/backends/onnx.d.ts.map +1 -0
  43. package/types/configs.d.ts +59 -0
  44. package/types/configs.d.ts.map +1 -0
  45. package/types/env.d.ts +106 -0
  46. package/types/env.d.ts.map +1 -0
  47. package/types/generation/configuration_utils.d.ts +320 -0
  48. package/types/generation/configuration_utils.d.ts.map +1 -0
  49. package/types/generation/logits_process.d.ts +354 -0
  50. package/types/generation/logits_process.d.ts.map +1 -0
  51. package/types/generation/logits_sampler.d.ts +51 -0
  52. package/types/generation/logits_sampler.d.ts.map +1 -0
  53. package/types/generation/parameters.d.ts +47 -0
  54. package/types/generation/parameters.d.ts.map +1 -0
  55. package/types/generation/stopping_criteria.d.ts +81 -0
  56. package/types/generation/stopping_criteria.d.ts.map +1 -0
  57. package/types/generation/streamers.d.ts +81 -0
  58. package/types/generation/streamers.d.ts.map +1 -0
  59. package/types/models/whisper/common_whisper.d.ts +8 -0
  60. package/types/models/whisper/common_whisper.d.ts.map +1 -0
  61. package/types/models/whisper/generation_whisper.d.ts +76 -0
  62. package/types/models/whisper/generation_whisper.d.ts.map +1 -0
  63. package/types/models.d.ts +3845 -0
  64. package/types/models.d.ts.map +1 -0
  65. package/types/ops/registry.d.ts +11 -0
  66. package/types/ops/registry.d.ts.map +1 -0
  67. package/types/pipelines.d.ts +2403 -0
  68. package/types/pipelines.d.ts.map +1 -0
  69. package/types/processors.d.ts +917 -0
  70. package/types/processors.d.ts.map +1 -0
  71. package/types/tokenizers.d.ts +999 -0
  72. package/types/tokenizers.d.ts.map +1 -0
  73. package/types/transformers.d.ts +13 -0
  74. package/types/transformers.d.ts.map +1 -0
  75. package/types/utils/audio.d.ts +130 -0
  76. package/types/utils/audio.d.ts.map +1 -0
  77. package/types/utils/constants.d.ts +2 -0
  78. package/types/utils/constants.d.ts.map +1 -0
  79. package/types/utils/core.d.ts +91 -0
  80. package/types/utils/core.d.ts.map +1 -0
  81. package/types/utils/data-structures.d.ts +236 -0
  82. package/types/utils/data-structures.d.ts.map +1 -0
  83. package/types/utils/devices.d.ts +8 -0
  84. package/types/utils/devices.d.ts.map +1 -0
  85. package/types/utils/dtypes.d.ts +22 -0
  86. package/types/utils/dtypes.d.ts.map +1 -0
  87. package/types/utils/generic.d.ts +11 -0
  88. package/types/utils/generic.d.ts.map +1 -0
  89. package/types/utils/hub.d.ts +191 -0
  90. package/types/utils/hub.d.ts.map +1 -0
  91. package/types/utils/image.d.ts +119 -0
  92. package/types/utils/image.d.ts.map +1 -0
  93. package/types/utils/maths.d.ts +280 -0
  94. package/types/utils/maths.d.ts.map +1 -0
  95. package/types/utils/tensor.d.ts +392 -0
  96. package/types/utils/tensor.d.ts.map +1 -0
@@ -0,0 +1,3341 @@
1
+ /**
2
+ * @file Pipelines provide a high-level, easy to use, API for running machine learning models.
3
+ *
4
+ * **Example:** Instantiate pipeline using the `pipeline` function.
5
+ * ```javascript
6
+ * import { pipeline } from '@huggingface/transformers';
7
+ *
8
+ * const classifier = await pipeline('sentiment-analysis');
9
+ * const output = await classifier('I love transformers!');
10
+ * // [{'label': 'POSITIVE', 'score': 0.999817686}]
11
+ * ```
12
+ *
13
+ * @module pipelines
14
+ */
15
+
16
+ import {
17
+ AutoTokenizer,
18
+ PreTrainedTokenizer,
19
+ } from './tokenizers.js';
20
+ import {
21
+ AutoModel,
22
+ AutoModelForSequenceClassification,
23
+ AutoModelForAudioClassification,
24
+ AutoModelForTokenClassification,
25
+ AutoModelForQuestionAnswering,
26
+ AutoModelForMaskedLM,
27
+ AutoModelForSeq2SeqLM,
28
+ AutoModelForSpeechSeq2Seq,
29
+ AutoModelForTextToWaveform,
30
+ AutoModelForTextToSpectrogram,
31
+ AutoModelForCTC,
32
+ AutoModelForCausalLM,
33
+ AutoModelForVision2Seq,
34
+ AutoModelForImageClassification,
35
+ AutoModelForImageSegmentation,
36
+ AutoModelForSemanticSegmentation,
37
+ AutoModelForObjectDetection,
38
+ AutoModelForZeroShotObjectDetection,
39
+ AutoModelForDocumentQuestionAnswering,
40
+ AutoModelForImageToImage,
41
+ AutoModelForDepthEstimation,
42
+ AutoModelForImageFeatureExtraction,
43
+ PreTrainedModel,
44
+ } from './models.js';
45
+ import {
46
+ AutoProcessor,
47
+ Processor
48
+ } from './processors.js';
49
+
50
+ import {
51
+ Callable,
52
+ } from './utils/generic.js';
53
+
54
+ import {
55
+ dispatchCallback,
56
+ pop,
57
+ product,
58
+ } from './utils/core.js';
59
+ import {
60
+ softmax,
61
+ max,
62
+ round,
63
+ } from './utils/maths.js';
64
+ import {
65
+ read_audio
66
+ } from './utils/audio.js';
67
+ import {
68
+ Tensor,
69
+ mean_pooling,
70
+ interpolate,
71
+ quantize_embeddings,
72
+ topk,
73
+ } from './utils/tensor.js';
74
+ import { RawImage } from './utils/image.js';
75
+
76
+
77
+ /**
78
+ * @typedef {string | RawImage | URL} ImageInput
79
+ * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs
80
+ */
81
+
82
+ /**
83
+ * Prepare images for further tasks.
84
+ * @param {ImagePipelineInputs} images images to prepare.
85
+ * @returns {Promise<RawImage[]>} returns processed images.
86
+ * @private
87
+ */
88
+ async function prepareImages(images) {
89
+ if (!Array.isArray(images)) {
90
+ images = [images];
91
+ }
92
+
93
+ // Possibly convert any non-images to images
94
+ return await Promise.all(images.map(x => RawImage.read(x)));
95
+ }
96
+
97
+ /**
98
+ * @typedef {string | URL | Float32Array | Float64Array} AudioInput
99
+ * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs
100
+ */
101
+
102
+ /**
103
+ * Prepare audios for further tasks.
104
+ * @param {AudioPipelineInputs} audios audios to prepare.
105
+ * @param {number} sampling_rate sampling rate of the audios.
106
+ * @returns {Promise<Float32Array[]>} The preprocessed audio data.
107
+ * @private
108
+ */
109
+ async function prepareAudios(audios, sampling_rate) {
110
+ if (!Array.isArray(audios)) {
111
+ audios = [audios];
112
+ }
113
+
114
+ return await Promise.all(audios.map(x => {
115
+ if (typeof x === 'string' || x instanceof URL) {
116
+ return read_audio(x, sampling_rate);
117
+ } else if (x instanceof Float64Array) {
118
+ return new Float32Array(x);
119
+ }
120
+ return x;
121
+ }));
122
+ }
123
+
124
+ /**
125
+ * @typedef {Object} BoundingBox
126
+ * @property {number} xmin The minimum x coordinate of the bounding box.
127
+ * @property {number} ymin The minimum y coordinate of the bounding box.
128
+ * @property {number} xmax The maximum x coordinate of the bounding box.
129
+ * @property {number} ymax The maximum y coordinate of the bounding box.
130
+ */
131
+
132
+ /**
133
+ * Helper function to convert list [xmin, xmax, ymin, ymax] into object { "xmin": xmin, ... }
134
+ * @param {number[]} box The bounding box as a list.
135
+ * @param {boolean} asInteger Whether to cast to integers.
136
+ * @returns {BoundingBox} The bounding box as an object.
137
+ * @private
138
+ */
139
+ function get_bounding_box(box, asInteger) {
140
+ if (asInteger) {
141
+ box = box.map(x => x | 0);
142
+ }
143
+ const [xmin, ymin, xmax, ymax] = box;
144
+
145
+ return { xmin, ymin, xmax, ymax };
146
+ }
147
+
148
+
149
+ /**
150
+ * @callback DisposeType Disposes the item.
151
+ * @returns {Promise<void>} A promise that resolves when the item has been disposed.
152
+ *
153
+ * @typedef {Object} Disposable
154
+ * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed.
155
+ */
156
+
157
+ /**
158
+ * The Pipeline class is the class from which all pipelines inherit.
159
+ * Refer to this class for methods shared across different pipelines.
160
+ * @extends Callable
161
+ */
162
+ export class Pipeline extends Callable {
163
+ /**
164
+ * Create a new Pipeline.
165
+ * @param {Object} options An object containing the following properties:
166
+ * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.
167
+ * @param {PreTrainedModel} [options.model] The model used by the pipeline.
168
+ * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).
169
+ * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).
170
+ */
171
+ constructor({ task, model, tokenizer = null, processor = null }) {
172
+ super();
173
+ this.task = task;
174
+ this.model = model;
175
+ this.tokenizer = tokenizer;
176
+ this.processor = processor;
177
+ }
178
+
179
+ /** @type {DisposeType} */
180
+ async dispose() {
181
+ await this.model.dispose();
182
+ }
183
+ }
184
+
185
+ /**
186
+ * @typedef {Object} ModelTokenizerConstructorArgs
187
+ * @property {string} task The task of the pipeline. Useful for specifying subtasks.
188
+ * @property {PreTrainedModel} model The model used by the pipeline.
189
+ * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.
190
+ *
191
+ * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline.
192
+ */
193
+
194
+ /**
195
+ * @typedef {Object} ModelProcessorConstructorArgs
196
+ * @property {string} task The task of the pipeline. Useful for specifying subtasks.
197
+ * @property {PreTrainedModel} model The model used by the pipeline.
198
+ * @property {Processor} processor The processor used by the pipeline.
199
+ *
200
+ * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline.
201
+ * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline.
202
+ */
203
+
204
+
205
+ /**
206
+ * @typedef {Object} ModelTokenizerProcessorConstructorArgs
207
+ * @property {string} task The task of the pipeline. Useful for specifying subtasks.
208
+ * @property {PreTrainedModel} model The model used by the pipeline.
209
+ * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.
210
+ * @property {Processor} processor The processor used by the pipeline.
211
+ *
212
+ * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline.
213
+ * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline.
214
+ */
215
+
216
+ /**
217
+ * @typedef {Object} TextClassificationSingle
218
+ * @property {string} label The label predicted.
219
+ * @property {number} score The corresponding probability.
220
+ * @typedef {TextClassificationSingle[]} TextClassificationOutput
221
+ *
222
+ * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines.
223
+ * @property {number} [top_k=1] The number of top predictions to be returned.
224
+ *
225
+ * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs.
226
+ * @param {string|string[]} texts The input text(s) to be classified.
227
+ * @param {TextClassificationPipelineOptions} [options] The options to use for text classification.
228
+ * @returns {Promise<TextClassificationOutput|TextClassificationOutput[]>} An array or object containing the predicted labels and scores.
229
+ *
230
+ * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType
231
+ */
232
+
233
+ /**
234
+ * Text classification pipeline using any `ModelForSequenceClassification`.
235
+ *
236
+ * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`.
237
+ * ```javascript
238
+ * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');
239
+ * const output = await classifier('I love transformers!');
240
+ * // [{ label: 'POSITIVE', score: 0.999788761138916 }]
241
+ * ```
242
+ *
243
+ * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes).
244
+ * ```javascript
245
+ * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');
246
+ * const output = await classifier('Le meilleur film de tous les temps.', { top_k: 5 });
247
+ * // [
248
+ * // { label: '5 stars', score: 0.9610759615898132 },
249
+ * // { label: '4 stars', score: 0.03323351591825485 },
250
+ * // { label: '3 stars', score: 0.0036155181005597115 },
251
+ * // { label: '1 star', score: 0.0011325967498123646 },
252
+ * // { label: '2 stars', score: 0.0009423971059732139 }
253
+ * // ]
254
+ * ```
255
+ *
256
+ * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes).
257
+ * ```javascript
258
+ * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');
259
+ * const output = await classifier('I hate you!', { top_k: null });
260
+ * // [
261
+ * // { label: 'toxic', score: 0.9593140482902527 },
262
+ * // { label: 'insult', score: 0.16187334060668945 },
263
+ * // { label: 'obscene', score: 0.03452680632472038 },
264
+ * // { label: 'identity_hate', score: 0.0223250575363636 },
265
+ * // { label: 'threat', score: 0.019197041168808937 },
266
+ * // { label: 'severe_toxic', score: 0.005651099607348442 }
267
+ * // ]
268
+ * ```
269
+ */
270
+ export class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) {
271
+
272
+ /**
273
+ * Create a new TextClassificationPipeline.
274
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
275
+ */
276
+ constructor(options) {
277
+ super(options);
278
+ }
279
+
280
+ /** @type {TextClassificationPipelineCallback} */
281
+ async _call(texts, {
282
+ top_k = 1
283
+ } = {}) {
284
+
285
+ // Run tokenization
286
+ const model_inputs = this.tokenizer(texts, {
287
+ padding: true,
288
+ truncation: true,
289
+ });
290
+
291
+ // Run model
292
+ const outputs = await this.model(model_inputs)
293
+
294
+ // TODO: Use softmax tensor function
295
+ const function_to_apply =
296
+ this.model.config.problem_type === 'multi_label_classification'
297
+ ? batch => batch.sigmoid()
298
+ : batch => new Tensor(
299
+ 'float32',
300
+ softmax(batch.data),
301
+ batch.dims,
302
+ ); // single_label_classification (default)
303
+
304
+ const id2label = this.model.config.id2label;
305
+
306
+ const toReturn = [];
307
+ for (const batch of outputs.logits) {
308
+ const output = function_to_apply(batch);
309
+
310
+ const scores = await topk(output, top_k);
311
+
312
+ const values = scores[0].tolist();
313
+ const indices = scores[1].tolist();
314
+ const vals = indices.map((x, i) => ({
315
+ label: id2label ? id2label[x] : `LABEL_${x}`,
316
+ score: values[i],
317
+ }));
318
+ if (top_k === 1) {
319
+ toReturn.push(...vals);
320
+ } else {
321
+ toReturn.push(vals);
322
+ }
323
+ }
324
+
325
+ return Array.isArray(texts) || top_k === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0];
326
+ }
327
+ }
328
+
329
+ /**
330
+ * @typedef {Object} TokenClassificationSingle
331
+ * @property {string} word The token/word classified. This is obtained by decoding the selected tokens.
332
+ * @property {number} score The corresponding probability for `entity`.
333
+ * @property {string} entity The entity predicted for that token/word.
334
+ * @property {number} index The index of the corresponding token in the sentence.
335
+ * @property {number} [start] The index of the start of the corresponding entity in the sentence.
336
+ * @property {number} [end] The index of the end of the corresponding entity in the sentence.
337
+ * @typedef {TokenClassificationSingle[]} TokenClassificationOutput
338
+ *
339
+ * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines.
340
+ * @property {string[]} [ignore_labels] A list of labels to ignore.
341
+ *
342
+ * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs.
343
+ * @param {string|string[]} texts One or several texts (or one list of texts) for token classification.
344
+ * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification.
345
+ * @returns {Promise<TokenClassificationOutput|TokenClassificationOutput[]>} The result.
346
+ *
347
+ * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType
348
+ */
349
+
350
+ /**
351
+ * Named Entity Recognition pipeline using any `ModelForTokenClassification`.
352
+ *
353
+ * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`.
354
+ * ```javascript
355
+ * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
356
+ * const output = await classifier('My name is Sarah and I live in London');
357
+ * // [
358
+ * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' },
359
+ * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }
360
+ * // ]
361
+ * ```
362
+ *
363
+ * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels).
364
+ * ```javascript
365
+ * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
366
+ * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] });
367
+ * // [
368
+ * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' },
369
+ * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' },
370
+ * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' },
371
+ * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' },
372
+ * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' },
373
+ * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' },
374
+ * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' },
375
+ * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' }
376
+ * // ]
377
+ * ```
378
+ */
379
+ export class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) {
380
+
381
+ /**
382
+ * Create a new TokenClassificationPipeline.
383
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
384
+ */
385
+ constructor(options) {
386
+ super(options);
387
+ }
388
+
389
+ /** @type {TokenClassificationPipelineCallback} */
390
+ async _call(texts, {
391
+ ignore_labels = ['O'],
392
+ } = {}) {
393
+
394
+ const isBatched = Array.isArray(texts);
395
+
396
+ // Run tokenization
397
+ const model_inputs = this.tokenizer(isBatched ? texts : [texts], {
398
+ padding: true,
399
+ truncation: true,
400
+ });
401
+
402
+ // Run model
403
+ const outputs = await this.model(model_inputs)
404
+
405
+ const logits = outputs.logits;
406
+ const id2label = this.model.config.id2label;
407
+
408
+ const toReturn = [];
409
+ for (let i = 0; i < logits.dims[0]; ++i) {
410
+ const ids = model_inputs.input_ids[i];
411
+ const batch = logits[i];
412
+
413
+ // List of tokens that aren't ignored
414
+ const tokens = [];
415
+ for (let j = 0; j < batch.dims[0]; ++j) {
416
+ const tokenData = batch[j];
417
+ const topScoreIndex = max(tokenData.data)[1];
418
+
419
+ const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;
420
+ if (ignore_labels.includes(entity)) {
421
+ // We predicted a token that should be ignored. So, we skip it.
422
+ continue;
423
+ }
424
+
425
+ // TODO add option to keep special tokens?
426
+ const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });
427
+ if (word === '') {
428
+ // Was a special token. So, we skip it.
429
+ continue;
430
+ }
431
+
432
+ const scores = softmax(tokenData.data);
433
+
434
+ tokens.push({
435
+ entity: entity,
436
+ score: scores[topScoreIndex],
437
+ index: j,
438
+ word: word,
439
+
440
+ // TODO: Add support for start and end
441
+ // start: null,
442
+ // end: null,
443
+ });
444
+ }
445
+ toReturn.push(tokens);
446
+ }
447
+ return isBatched ? toReturn : toReturn[0];
448
+ }
449
+ }
450
+
451
+ /**
452
+ * @typedef {Object} QuestionAnsweringOutput
453
+ * @property {number} score The probability associated to the answer.
454
+ * @property {number} [start] The character start index of the answer (in the tokenized version of the input).
455
+ * @property {number} [end] The character end index of the answer (in the tokenized version of the input).
456
+ * @property {string} answer The answer to the question.
457
+ *
458
+ * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines.
459
+ * @property {number} [top_k=1] The number of top answer predictions to be returned.
460
+ *
461
+ * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s).
462
+ * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument).
463
+ * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument).
464
+ * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering.
465
+ * @returns {Promise<QuestionAnsweringOutput|QuestionAnsweringOutput[]>} An array or object containing the predicted answers and scores.
466
+ *
467
+ * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType
468
+ */
469
+
470
+ /**
471
+ * Question Answering pipeline using any `ModelForQuestionAnswering`.
472
+ *
473
+ * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`.
474
+ * ```javascript
475
+ * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');
476
+ * const question = 'Who was Jim Henson?';
477
+ * const context = 'Jim Henson was a nice puppet.';
478
+ * const output = await answerer(question, context);
479
+ * // {
480
+ * // answer: "a nice puppet",
481
+ * // score: 0.5768911502526741
482
+ * // }
483
+ * ```
484
+ */
485
+ export class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) {
486
+
487
+ /**
488
+ * Create a new QuestionAnsweringPipeline.
489
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
490
+ */
491
+ constructor(options) {
492
+ super(options);
493
+ }
494
+
495
+ /** @type {QuestionAnsweringPipelineCallback} */
496
+ async _call(question, context, {
497
+ top_k = 1
498
+ } = {}) {
499
+
500
+ // Run tokenization
501
+ const inputs = this.tokenizer(question, {
502
+ text_pair: context,
503
+ padding: true,
504
+ truncation: true,
505
+ });
506
+
507
+ const { start_logits, end_logits } = await this.model(inputs);
508
+ const input_ids = inputs.input_ids.tolist();
509
+ const attention_mask = inputs.attention_mask.tolist();
510
+
511
+ // TODO: add support for `return_special_tokens_mask`
512
+ const special_tokens = this.tokenizer.all_special_ids;
513
+
514
+ /** @type {QuestionAnsweringOutput[]} */
515
+ const toReturn = [];
516
+ for (let j = 0; j < start_logits.dims[0]; ++j) {
517
+ const ids = input_ids[j];
518
+ const sepIndex = ids.findIndex(x =>
519
+ // We use == to match bigint with number
520
+ // @ts-ignore
521
+ x == this.tokenizer.sep_token_id
522
+ );
523
+
524
+
525
+ const valid_mask = attention_mask[j].map((y, ix) => (
526
+ y == 1
527
+ && (
528
+ ix === 0 // is cls_token
529
+ || (
530
+ ix > sepIndex
531
+ && special_tokens.findIndex(x => x == ids[ix]) === -1 // token is not a special token (special_tokens_mask == 0)
532
+ )
533
+ )
534
+ ));
535
+
536
+ const start = start_logits[j].tolist();
537
+ const end = end_logits[j].tolist();
538
+
539
+ // Now, we mask out values that can't be in the answer
540
+ // NOTE: We keep the cls_token unmasked (some models use it to indicate unanswerable questions)
541
+ for (let i = 1; i < start.length; ++i) {
542
+ if (
543
+ attention_mask[j] == 0 // is part of padding
544
+ || i <= sepIndex // is before the sep_token
545
+ || special_tokens.findIndex(x => x == ids[i]) !== -1 // Is a special token
546
+ ) {
547
+ // Make sure non-context indexes in the tensor cannot contribute to the softmax
548
+ start[i] = -Infinity;
549
+ end[i] = -Infinity;
550
+ }
551
+ }
552
+
553
+ // Normalize logits and spans to retrieve the answer
554
+ const start_scores = softmax(start).map((x, i) => [x, i]);
555
+ const end_scores = softmax(end).map((x, i) => [x, i]);
556
+
557
+ // Mask CLS
558
+ start_scores[0][0] = 0;
559
+ end_scores[0][0] = 0;
560
+
561
+ // Generate all valid spans and select best ones
562
+ const options = product(start_scores, end_scores)
563
+ .filter(x => x[0][1] <= x[1][1])
564
+ .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]])
565
+ .sort((a, b) => b[2] - a[2]);
566
+
567
+ for (let k = 0; k < Math.min(options.length, top_k); ++k) {
568
+ const [start, end, score] = options[k];
569
+
570
+ const answer_tokens = ids.slice(start, end + 1)
571
+
572
+ const answer = this.tokenizer.decode(answer_tokens, {
573
+ skip_special_tokens: true,
574
+ });
575
+
576
+ // TODO add start and end?
577
+ // NOTE: HF returns character index
578
+ toReturn.push({
579
+ answer, score
580
+ });
581
+ }
582
+ }
583
+
584
+ // Mimic HF's return type based on top_k
585
+ return (top_k === 1) ? toReturn[0] : toReturn;
586
+ }
587
+ }
588
+
589
+
590
+ /**
591
+ * @typedef {Object} FillMaskSingle
592
+ * @property {string} sequence The corresponding input with the mask token prediction.
593
+ * @property {number} score The corresponding probability.
594
+ * @property {number} token The predicted token id (to replace the masked one).
595
+ * @property {string} token_str The predicted token (to replace the masked one).
596
+ * @typedef {FillMaskSingle[]} FillMaskOutput
597
+ *
598
+ * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines.
599
+ * @property {number} [top_k=5] When passed, overrides the number of predictions to return.
600
+ *
601
+ * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs.
602
+ * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens.
603
+ * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling.
604
+ * @returns {Promise<FillMaskOutput|FillMaskOutput[]>} An array of objects containing the score, predicted token, predicted token string,
605
+ * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text).
606
+ * If only one input text is given, the output will be an array of objects.
607
+ * @throws {Error} When the mask token is not found in the input text.
608
+ *
609
+ * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType
610
+ */
611
+
612
+ /**
613
+ * Masked language modeling prediction pipeline using any `ModelWithLMHead`.
614
+ *
615
+ * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-uncased`.
616
+ * ```javascript
617
+ * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
618
+ * const output = await unmasker('The goal of life is [MASK].');
619
+ * // [
620
+ * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' },
621
+ * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' },
622
+ * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' },
623
+ * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' },
624
+ * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }
625
+ * // ]
626
+ * ```
627
+ *
628
+ * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-cased` (and return top result).
629
+ * ```javascript
630
+ * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
631
+ * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { top_k: 1 });
632
+ * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]
633
+ * ```
634
+ */
635
+ export class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) {
636
+
637
+ /**
638
+ * Create a new FillMaskPipeline.
639
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
640
+ */
641
+ constructor(options) {
642
+ super(options);
643
+ }
644
+
645
+ /** @type {FillMaskPipelineCallback} */
646
+ async _call(texts, {
647
+ top_k = 5
648
+ } = {}) {
649
+
650
+ // Run tokenization
651
+ const model_inputs = this.tokenizer(texts, {
652
+ padding: true,
653
+ truncation: true,
654
+ });
655
+
656
+ // Run model
657
+ const { logits } = await this.model(model_inputs)
658
+
659
+ const toReturn = [];
660
+
661
+ /** @type {bigint[][]} */
662
+ const input_ids = model_inputs.input_ids.tolist();
663
+ for (let i = 0; i < input_ids.length; ++i) {
664
+ const ids = input_ids[i];
665
+ const mask_token_index = ids.findIndex(x =>
666
+ // We use == to match bigint with number
667
+ // @ts-ignore
668
+ x == this.tokenizer.mask_token_id
669
+ );
670
+ if (mask_token_index === -1) {
671
+ throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)
672
+ }
673
+ const itemLogits = logits[i][mask_token_index];
674
+
675
+ const scores = await topk(new Tensor(
676
+ 'float32',
677
+ softmax(itemLogits.data),
678
+ itemLogits.dims,
679
+ ), top_k);
680
+ const values = scores[0].tolist();
681
+ const indices = scores[1].tolist();
682
+
683
+ toReturn.push(indices.map((x, i) => {
684
+ const sequence = ids.slice();
685
+ sequence[mask_token_index] = x;
686
+
687
+ return {
688
+ score: values[i],
689
+ token: Number(x),
690
+ token_str: this.tokenizer.model.vocab[x],
691
+ sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }),
692
+ }
693
+ }));
694
+ }
695
+ return Array.isArray(texts) ? toReturn : toReturn[0];
696
+ }
697
+ }
698
+
699
+
700
+ /**
701
+ * @typedef {Object} Text2TextGenerationSingle
702
+ * @property {string} generated_text The generated text.
703
+ * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput
704
+ *
705
+ * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs.
706
+ * @param {string|string[]} texts Input text for the encoder.
707
+ * @param {Partial<import('./generation/configuration_utils.js').GenerationConfig>} [options] Additional keyword arguments to pass along to the generate method of the model.
708
+ * @returns {Promise<Text2TextGenerationOutput|Text2TextGenerationOutput[]>}
709
+ *
710
+ * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType
711
+ */
712
+
713
+ /**
714
+ * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks.
715
+ *
716
+ * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`.
717
+ * ```javascript
718
+ * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');
719
+ * const output = await generator('how can I become more healthy?', {
720
+ * max_new_tokens: 100,
721
+ * });
722
+ * // [{ 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." }]
723
+ * ```
724
+ */
725
+ export class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) {
726
+ /** @type {'generated_text'} */
727
+ _key = 'generated_text';
728
+
729
+ /**
730
+ * Create a new Text2TextGenerationPipeline.
731
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
732
+ */
733
+ constructor(options) {
734
+ super(options);
735
+ }
736
+
737
+ /** @type {Text2TextGenerationPipelineCallback} */
738
+ async _call(texts, generate_kwargs = {}) {
739
+ if (!Array.isArray(texts)) {
740
+ texts = [texts];
741
+ }
742
+
743
+
744
+ // Add global prefix, if present
745
+ if (this.model.config.prefix) {
746
+ texts = texts.map(x => this.model.config.prefix + x)
747
+ }
748
+
749
+ // Handle task specific params:
750
+ const task_specific_params = this.model.config.task_specific_params
751
+ if (task_specific_params && task_specific_params[this.task]) {
752
+ // Add prefixes, if present
753
+ if (task_specific_params[this.task].prefix) {
754
+ texts = texts.map(x => task_specific_params[this.task].prefix + x)
755
+ }
756
+
757
+ // TODO update generation config
758
+ }
759
+
760
+ const tokenizer = this.tokenizer;
761
+ const tokenizer_options = {
762
+ padding: true,
763
+ truncation: true,
764
+ }
765
+ let inputs;
766
+ if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) {
767
+ // TODO: move to Translation pipeline?
768
+ // Currently put here to avoid code duplication
769
+ // @ts-ignore
770
+ inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs);
771
+
772
+ } else {
773
+ inputs = tokenizer(texts, tokenizer_options);
774
+ }
775
+
776
+ const outputTokenIds = await this.model.generate({ ...inputs, ...generate_kwargs });
777
+ return tokenizer.batch_decode(/** @type {Tensor} */(outputTokenIds), {
778
+ skip_special_tokens: true,
779
+ }).map(text => ({ [this._key]: text }));
780
+ }
781
+ }
782
+
783
+
784
+ /**
785
+ * @typedef {Object} SummarizationSingle
786
+ * @property {string} summary_text The summary text.
787
+ * @typedef {SummarizationSingle[]} SummarizationOutput
788
+ *
789
+ * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs.
790
+ * @param {string|string[]} texts One or several articles (or one list of articles) to summarize.
791
+ * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.
792
+ * @returns {Promise<SummarizationOutput|SummarizationOutput[]>}
793
+ *
794
+ * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType
795
+ */
796
+
797
+ /**
798
+ * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline.
799
+ *
800
+ * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`.
801
+ * ```javascript
802
+ * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');
803
+ * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' +
804
+ * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' +
805
+ * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' +
806
+ * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' +
807
+ * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' +
808
+ * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' +
809
+ * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' +
810
+ * 'tallest free-standing structure in France after the Millau Viaduct.';
811
+ * const output = await generator(text, {
812
+ * max_new_tokens: 100,
813
+ * });
814
+ * // [{ 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.' }]
815
+ * ```
816
+ */
817
+ export class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {
818
+ /** @type {'summary_text'} */
819
+ _key = 'summary_text';
820
+
821
+ /**
822
+ * Create a new SummarizationPipeline.
823
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
824
+ */
825
+ constructor(options) {
826
+ super(options);
827
+ }
828
+ }
829
+
830
+
831
+ /**
832
+ * @typedef {Object} TranslationSingle
833
+ * @property {string} translation_text The translated text.
834
+ * @typedef {TranslationSingle[]} TranslationOutput
835
+ *
836
+ * @callback TranslationPipelineCallback Translate the text(s) given as inputs.
837
+ * @param {string|string[]} texts Texts to be translated.
838
+ * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.
839
+ * @returns {Promise<TranslationOutput|TranslationOutput[]>}
840
+ *
841
+ * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType
842
+ */
843
+
844
+ /**
845
+ * Translates text from one language to another.
846
+ *
847
+ * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`.
848
+ *
849
+ * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200)
850
+ * for the full list of languages and their corresponding codes.
851
+ *
852
+ * ```javascript
853
+ * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
854
+ * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {
855
+ * src_lang: 'hin_Deva', // Hindi
856
+ * tgt_lang: 'fra_Latn', // French
857
+ * });
858
+ * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }]
859
+ * ```
860
+ *
861
+ * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`.
862
+ *
863
+ * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered)
864
+ * for the full list of languages and their corresponding codes.
865
+ *
866
+ * ```javascript
867
+ * const translator = await pipeline('translation', 'Xenova/m2m100_418M');
868
+ * const output = await translator('生活就像一盒巧克力。', {
869
+ * src_lang: 'zh', // Chinese
870
+ * tgt_lang: 'en', // English
871
+ * });
872
+ * // [{ translation_text: 'Life is like a box of chocolate.' }]
873
+ * ```
874
+ *
875
+ * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`.
876
+ *
877
+ * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered)
878
+ * for the full list of languages and their corresponding codes.
879
+ *
880
+ * ```javascript
881
+ * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');
882
+ * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {
883
+ * src_lang: 'hi_IN', // Hindi
884
+ * tgt_lang: 'fr_XX', // French
885
+ * });
886
+ * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]
887
+ * ```
888
+ */
889
+ export class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {
890
+ /** @type {'translation_text'} */
891
+ _key = 'translation_text';
892
+
893
+ /**
894
+ * Create a new TranslationPipeline.
895
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
896
+ */
897
+ constructor(options) {
898
+ super(options);
899
+ }
900
+ }
901
+
902
+ function isChat(x) {
903
+ return Array.isArray(x) && x.every(x => 'role' in x && 'content' in x);
904
+ }
905
+
906
+ /**
907
+ * @typedef {import('./tokenizers.js').Message[]} Chat
908
+ *
909
+ * @typedef {Object} TextGenerationSingle
910
+ * @property {string|Chat} generated_text The generated text.
911
+ * @typedef {TextGenerationSingle[]} TextGenerationOutput
912
+ *
913
+ * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines.
914
+ * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences.
915
+ * @property {boolean} [return_full_text=true] If set to `false` only added text is returned, otherwise the full text is returned.
916
+ * @typedef {import('./generation/configuration_utils.js').GenerationConfig & TextGenerationSpecificParams} TextGenerationConfig
917
+ *
918
+ * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs.
919
+ * @param {string|string[]|Chat|Chat[]} texts One or several prompts (or one list of prompts) to complete.
920
+ * @param {Partial<TextGenerationConfig>} [options] Additional keyword arguments to pass along to the generate method of the model.
921
+ * @returns {Promise<TextGenerationOutput|TextGenerationOutput[]>} An array or object containing the generated texts.
922
+ *
923
+ * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType
924
+ */
925
+
926
+ /**
927
+ * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`.
928
+ * This pipeline predicts the words that will follow a specified text prompt.
929
+ * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig).
930
+ *
931
+ * **Example:** Text generation with `Xenova/distilgpt2` (default settings).
932
+ * ```javascript
933
+ * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
934
+ * const text = 'I enjoy walking with my cute dog,';
935
+ * const output = await generator(text);
936
+ * // [{ generated_text: "I enjoy walking with my cute dog, and I love to play with the other dogs." }]
937
+ * ```
938
+ *
939
+ * **Example:** Text generation with `Xenova/distilgpt2` (custom settings).
940
+ * ```javascript
941
+ * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
942
+ * const text = 'Once upon a time, there was';
943
+ * const output = await generator(text, {
944
+ * temperature: 2,
945
+ * max_new_tokens: 10,
946
+ * repetition_penalty: 1.5,
947
+ * no_repeat_ngram_size: 2,
948
+ * num_beams: 2,
949
+ * num_return_sequences: 2,
950
+ * });
951
+ * // [{
952
+ * // "generated_text": "Once upon a time, there was an abundance of information about the history and activities that"
953
+ * // }, {
954
+ * // "generated_text": "Once upon a time, there was an abundance of information about the most important and influential"
955
+ * // }]
956
+ * ```
957
+ *
958
+ * **Example:** Run code generation with `Xenova/codegen-350M-mono`.
959
+ * ```javascript
960
+ * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');
961
+ * const text = 'def fib(n):';
962
+ * const output = await generator(text, {
963
+ * max_new_tokens: 44,
964
+ * });
965
+ * // [{
966
+ * // generated_text: 'def fib(n):\n' +
967
+ * // ' if n == 0:\n' +
968
+ * // ' return 0\n' +
969
+ * // ' elif n == 1:\n' +
970
+ * // ' return 1\n' +
971
+ * // ' else:\n' +
972
+ * // ' return fib(n-1) + fib(n-2)\n'
973
+ * // }]
974
+ * ```
975
+ */
976
+ export class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) {
977
+
978
+ /**
979
+ * Create a new TextGenerationPipeline.
980
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
981
+ */
982
+ constructor(options) {
983
+ super(options);
984
+ }
985
+
986
+ /** @type {TextGenerationPipelineCallback} */
987
+ async _call(texts, generate_kwargs = {}) {
988
+ let isBatched = false;
989
+ let isChatInput = false;
990
+
991
+ // Normalize inputs
992
+ /** @type {string[]} */
993
+ let inputs;
994
+ if (typeof texts === 'string') {
995
+ inputs = texts = [texts];
996
+ } else if (Array.isArray(texts) && texts.every(x => typeof x === 'string')) {
997
+ isBatched = true;
998
+ inputs = /** @type {string[]} */(texts);
999
+ } else {
1000
+ if (isChat(texts)) {
1001
+ texts = [/** @type {Chat} */(texts)];
1002
+ } else if (Array.isArray(texts) && texts.every(isChat)) {
1003
+ isBatched = true;
1004
+ } else {
1005
+ throw new Error('Input must be a string, an array of strings, a Chat, or an array of Chats');
1006
+ }
1007
+ isChatInput = true;
1008
+
1009
+ // If the input is a chat, we need to apply the chat template
1010
+ inputs = /** @type {string[]} */(/** @type {Chat[]} */ (texts).map(
1011
+ x => this.tokenizer.apply_chat_template(x, {
1012
+ tokenize: false,
1013
+ add_generation_prompt: true,
1014
+ })
1015
+ ));
1016
+ }
1017
+
1018
+ // By default, do not add special tokens
1019
+ const add_special_tokens = generate_kwargs.add_special_tokens ?? false;
1020
+
1021
+ // By default, return full text
1022
+ const return_full_text = isChatInput
1023
+ ? false
1024
+ : generate_kwargs.return_full_text ?? true;
1025
+
1026
+ this.tokenizer.padding_side = 'left';
1027
+ const text_inputs = this.tokenizer(inputs, {
1028
+ add_special_tokens,
1029
+ padding: true,
1030
+ truncation: true,
1031
+ });
1032
+
1033
+ const outputTokenIds = /** @type {Tensor} */(await this.model.generate({
1034
+ ...text_inputs,
1035
+ ...generate_kwargs
1036
+ }));
1037
+
1038
+ const decoded = this.tokenizer.batch_decode(outputTokenIds, {
1039
+ skip_special_tokens: true,
1040
+ });
1041
+
1042
+ let promptLengths;
1043
+ if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) {
1044
+ promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, {
1045
+ skip_special_tokens: true,
1046
+ }).map(x => x.length);
1047
+ }
1048
+
1049
+ /** @type {TextGenerationOutput[]} */
1050
+ const toReturn = Array.from({ length: texts.length }, _ => []);
1051
+ for (let i = 0; i < decoded.length; ++i) {
1052
+ const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length);
1053
+
1054
+ if (promptLengths) {
1055
+ // Trim the decoded text to only include the generated part
1056
+ decoded[i] = decoded[i].slice(promptLengths[textIndex]);
1057
+ }
1058
+ toReturn[textIndex].push({
1059
+ generated_text: isChatInput
1060
+ ? [
1061
+ ...((/** @type {Chat[]} */(texts)[textIndex])),
1062
+ { role: 'assistant', content: decoded[i] },
1063
+ ]
1064
+ : decoded[i]
1065
+ });
1066
+ }
1067
+ return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn;
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * @typedef {Object} ZeroShotClassificationOutput
1073
+ * @property {string} sequence The sequence for which this is the output.
1074
+ * @property {string[]} labels The labels sorted by order of likelihood.
1075
+ * @property {number[]} scores The probabilities for each of the labels.
1076
+ *
1077
+ * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines.
1078
+ * @property {string} [hypothesis_template="This example is {}."] The template used to turn each
1079
+ * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.
1080
+ * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true.
1081
+ * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence
1082
+ * is 1. If `true`, the labels are considered independent and probabilities are normalized for each
1083
+ * candidate by doing a softmax of the entailment score vs. the contradiction score.
1084
+ *
1085
+ * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs.
1086
+ * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large.
1087
+ * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into.
1088
+ * Can be a single label, a string of comma-separated labels, or a list of labels.
1089
+ * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification.
1090
+ * @returns {Promise<ZeroShotClassificationOutput|ZeroShotClassificationOutput[]>} An array or object containing the predicted labels and scores.
1091
+ *
1092
+ * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType
1093
+ */
1094
+
1095
+ /**
1096
+ * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification`
1097
+ * trained on NLI (natural language inference) tasks. Equivalent of `text-classification`
1098
+ * pipelines, but these models don't require a hardcoded number of potential classes, they
1099
+ * can be chosen at runtime. It usually means it's slower but it is **much** more flexible.
1100
+ *
1101
+ * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`.
1102
+ * ```javascript
1103
+ * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');
1104
+ * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.';
1105
+ * const labels = [ 'mobile', 'billing', 'website', 'account access' ];
1106
+ * const output = await classifier(text, labels);
1107
+ * // {
1108
+ * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.',
1109
+ * // labels: [ 'mobile', 'website', 'billing', 'account access' ],
1110
+ * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]
1111
+ * // }
1112
+ * ```
1113
+ *
1114
+ * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label).
1115
+ * ```javascript
1116
+ * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');
1117
+ * const text = 'I have a problem with my iphone that needs to be resolved asap!';
1118
+ * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ];
1119
+ * const output = await classifier(text, labels, { multi_label: true });
1120
+ * // {
1121
+ * // sequence: 'I have a problem with my iphone that needs to be resolved asap!',
1122
+ * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ],
1123
+ * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ]
1124
+ * // }
1125
+ * ```
1126
+ */
1127
+ export class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) {
1128
+ /**
1129
+ * Create a new ZeroShotClassificationPipeline.
1130
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
1131
+ */
1132
+ constructor(options) {
1133
+ super(options);
1134
+
1135
+ // Use model config to get label2id mapping
1136
+ this.label2id = Object.fromEntries(
1137
+ Object.entries((/** @type {any} */(this).model).config.label2id).map(
1138
+ ([k, v]) => [k.toLowerCase(), v]
1139
+ )
1140
+ );
1141
+
1142
+ this.entailment_id = this.label2id['entailment'];
1143
+ if (this.entailment_id === undefined) {
1144
+ console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.");
1145
+ this.entailment_id = 2;
1146
+ }
1147
+
1148
+ this.contradiction_id = this.label2id['contradiction'] ?? this.label2id['not_entailment'];
1149
+ if (this.contradiction_id === undefined) {
1150
+ console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.");
1151
+ this.contradiction_id = 0;
1152
+ }
1153
+ }
1154
+
1155
+ /** @type {ZeroShotClassificationPipelineCallback} */
1156
+ async _call(texts, candidate_labels, {
1157
+ hypothesis_template = "This example is {}.",
1158
+ multi_label = false,
1159
+ } = {}) {
1160
+
1161
+ const isBatched = Array.isArray(texts);
1162
+ if (!isBatched) {
1163
+ texts = [/** @type {string} */ (texts)];
1164
+ }
1165
+ if (!Array.isArray(candidate_labels)) {
1166
+ candidate_labels = [candidate_labels];
1167
+ }
1168
+
1169
+ // Insert labels into hypothesis template
1170
+ const hypotheses = candidate_labels.map(
1171
+ x => hypothesis_template.replace('{}', x)
1172
+ );
1173
+
1174
+ // How to perform the softmax over the logits:
1175
+ // - true: softmax over the entailment vs. contradiction dim for each label independently
1176
+ // - false: softmax the "entailment" logits over all candidate labels
1177
+ const softmaxEach = multi_label || candidate_labels.length === 1;
1178
+
1179
+ /** @type {ZeroShotClassificationOutput[]} */
1180
+ const toReturn = [];
1181
+ for (const premise of texts) {
1182
+ const entails_logits = [];
1183
+
1184
+ for (const hypothesis of hypotheses) {
1185
+ const inputs = this.tokenizer(premise, {
1186
+ text_pair: hypothesis,
1187
+ padding: true,
1188
+ truncation: true,
1189
+ })
1190
+ const outputs = await this.model(inputs)
1191
+
1192
+ if (softmaxEach) {
1193
+ entails_logits.push([
1194
+ outputs.logits.data[this.contradiction_id],
1195
+ outputs.logits.data[this.entailment_id]
1196
+ ])
1197
+ } else {
1198
+ entails_logits.push(outputs.logits.data[this.entailment_id])
1199
+ }
1200
+ }
1201
+
1202
+ /** @type {number[]} */
1203
+ const scores = softmaxEach
1204
+ ? entails_logits.map(x => softmax(x)[1])
1205
+ : softmax(entails_logits);
1206
+
1207
+ // Sort by scores (desc) and return scores with indices
1208
+ const scores_sorted = scores
1209
+ .map((x, i) => [x, i])
1210
+ .sort((a, b) => (b[0] - a[0]));
1211
+
1212
+ toReturn.push({
1213
+ sequence: premise,
1214
+ labels: scores_sorted.map(x => candidate_labels[x[1]]),
1215
+ scores: scores_sorted.map(x => x[0]),
1216
+ });
1217
+ }
1218
+ return isBatched ? toReturn : toReturn[0];
1219
+ }
1220
+ }
1221
+
1222
+ /**
1223
+ * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.
1224
+ * @property {'none'|'mean'|'cls'} [pooling="none"] The pooling method to use.
1225
+ * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension.
1226
+ * @property {boolean} [quantize=false] Whether or not to quantize the embeddings.
1227
+ * @property {'binary'|'ubinary'} [precision='binary'] The precision to use for quantization.
1228
+ *
1229
+ * @callback FeatureExtractionPipelineCallback Extract the features of the input(s).
1230
+ * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of.
1231
+ * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction.
1232
+ * @returns {Promise<Tensor>} The features computed by the model.
1233
+ *
1234
+ * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType
1235
+ */
1236
+
1237
+ /**
1238
+ * Feature extraction pipeline using no model head. This pipeline extracts the hidden
1239
+ * states from the base transformer, which can be used as features in downstream tasks.
1240
+ *
1241
+ * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization).
1242
+ * ```javascript
1243
+ * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
1244
+ * const output = await extractor('This is a simple test.');
1245
+ * // Tensor {
1246
+ * // type: 'float32',
1247
+ * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...],
1248
+ * // dims: [1, 8, 768]
1249
+ * // }
1250
+ * ```
1251
+ *
1252
+ * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization).
1253
+ * ```javascript
1254
+ * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
1255
+ * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });
1256
+ * // Tensor {
1257
+ * // type: 'float32',
1258
+ * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...],
1259
+ * // dims: [1, 768]
1260
+ * // }
1261
+ * ```
1262
+ *
1263
+ * **Example:** Calculating embeddings with `sentence-transformers` models.
1264
+ * ```javascript
1265
+ * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
1266
+ * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });
1267
+ * // Tensor {
1268
+ * // type: 'float32',
1269
+ * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...],
1270
+ * // dims: [1, 384]
1271
+ * // }
1272
+ * ```
1273
+ * **Example:** Calculating binary embeddings with `sentence-transformers` models.
1274
+ * ```javascript
1275
+ * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
1276
+ * const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' });
1277
+ * // Tensor {
1278
+ * // type: 'int8',
1279
+ * // data: Int8Array [49, 108, 24, ...],
1280
+ * // dims: [1, 48]
1281
+ * // }
1282
+ * ```
1283
+ */
1284
+ export class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) {
1285
+ /**
1286
+ * Create a new FeatureExtractionPipeline.
1287
+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
1288
+ */
1289
+ constructor(options) {
1290
+ super(options);
1291
+ }
1292
+
1293
+ /** @type {FeatureExtractionPipelineCallback} */
1294
+ async _call(texts, {
1295
+ pooling = /** @type {'none'} */('none'),
1296
+ normalize = false,
1297
+ quantize = false,
1298
+ precision = /** @type {'binary'} */('binary'),
1299
+ } = {}) {
1300
+
1301
+ // Run tokenization
1302
+ const model_inputs = this.tokenizer(texts, {
1303
+ padding: true,
1304
+ truncation: true,
1305
+ });
1306
+
1307
+ // Run model
1308
+ const outputs = await this.model(model_inputs)
1309
+
1310
+ // TODO: Provide warning to the user that they might be using model which was not exported
1311
+ // specifically for feature extraction
1312
+ // console.log(this.model.config)
1313
+ // console.log(outputs)
1314
+
1315
+ /** @type {Tensor} */
1316
+ let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings;
1317
+ if (pooling === 'none') {
1318
+ // Skip pooling
1319
+ } else if (pooling === 'mean') {
1320
+ result = mean_pooling(result, model_inputs.attention_mask);
1321
+ } else if (pooling === 'cls') {
1322
+ result = result.slice(null, 0);
1323
+ } else {
1324
+ throw Error(`Pooling method '${pooling}' not supported.`);
1325
+ }
1326
+
1327
+ if (normalize) {
1328
+ result = result.normalize(2, -1);
1329
+ }
1330
+
1331
+ if (quantize) {
1332
+ result = quantize_embeddings(result, precision);
1333
+ }
1334
+
1335
+ return result;
1336
+ }
1337
+ }
1338
+
1339
+
1340
+ /**
1341
+ * @typedef {Object} ImageFeatureExtractionPipelineOptions Parameters specific to image feature extraction pipelines.
1342
+ * @property {boolean} [pool=null] Whether or not to return the pooled output. If set to `false`, the model will return the raw hidden states.
1343
+ *
1344
+ * @callback ImageFeatureExtractionPipelineCallback Extract the features of the input(s).
1345
+ * @param {ImagePipelineInputs} images One or several images (or one list of images) to get the features of.
1346
+ * @param {ImageFeatureExtractionPipelineOptions} [options] The options to use for image feature extraction.
1347
+ * @returns {Promise<Tensor>} The image features computed by the model.
1348
+ *
1349
+ * @typedef {ImagePipelineConstructorArgs & ImageFeatureExtractionPipelineCallback & Disposable} ImageFeatureExtractionPipelineType
1350
+ */
1351
+
1352
+ /**
1353
+ * Image feature extraction pipeline using no model head. This pipeline extracts the hidden
1354
+ * states from the base transformer, which can be used as features in downstream tasks.
1355
+ *
1356
+ * **Example:** Perform image feature extraction with `Xenova/vit-base-patch16-224-in21k`.
1357
+ * ```javascript
1358
+ * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k');
1359
+ * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';
1360
+ * const features = await image_feature_extractor(url);
1361
+ * // Tensor {
1362
+ * // dims: [ 1, 197, 768 ],
1363
+ * // type: 'float32',
1364
+ * // data: Float32Array(151296) [ ... ],
1365
+ * // size: 151296
1366
+ * // }
1367
+ * ```
1368
+ *
1369
+ * **Example:** Compute image embeddings with `Xenova/clip-vit-base-patch32`.
1370
+ * ```javascript
1371
+ * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32');
1372
+ * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';
1373
+ * const features = await image_feature_extractor(url);
1374
+ * // Tensor {
1375
+ * // dims: [ 1, 512 ],
1376
+ * // type: 'float32',
1377
+ * // data: Float32Array(512) [ ... ],
1378
+ * // size: 512
1379
+ * // }
1380
+ * ```
1381
+ */
1382
+ export class ImageFeatureExtractionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ (Pipeline)) {
1383
+ /**
1384
+ * Create a new ImageFeatureExtractionPipeline.
1385
+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1386
+ */
1387
+ constructor(options) {
1388
+ super(options);
1389
+ }
1390
+
1391
+ /** @type {ImageFeatureExtractionPipelineCallback} */
1392
+ async _call(images, {
1393
+ pool = null,
1394
+ } = {}) {
1395
+
1396
+ const preparedImages = await prepareImages(images);
1397
+ const { pixel_values } = await this.processor(preparedImages);
1398
+ const outputs = await this.model({ pixel_values });
1399
+
1400
+ /** @type {Tensor} */
1401
+ let result;
1402
+ if (pool) {
1403
+ if (!('pooler_output' in outputs)) {
1404
+ throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);
1405
+ }
1406
+ result = outputs.pooler_output;
1407
+
1408
+ } else {
1409
+ result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds;
1410
+ }
1411
+ return result;
1412
+ }
1413
+ }
1414
+
1415
+ // TODO
1416
+ // export class SentenceSimilarityPipeline extends Pipeline {
1417
+ // }
1418
+
1419
+ /**
1420
+ * @typedef {Object} AudioClassificationSingle
1421
+ * @property {string} label The label predicted.
1422
+ * @property {number} score The corresponding probability.
1423
+ * @typedef {AudioClassificationSingle[]} AudioClassificationOutput
1424
+ *
1425
+ * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines.
1426
+ * @property {number} [top_k=5] The number of top labels that will be returned by the pipeline.
1427
+ * If the provided number is `null` or higher than the number of labels available in the model configuration,
1428
+ * it will default to the number of labels.
1429
+ *
1430
+ * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs.
1431
+ * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:
1432
+ * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
1433
+ * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.
1434
+ * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.
1435
+ * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
1436
+ * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification.
1437
+ * @returns {Promise<AudioClassificationOutput|AudioClassificationOutput[]>} An array or object containing the predicted labels and scores.
1438
+ *
1439
+ * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType
1440
+ */
1441
+
1442
+ /**
1443
+ * Audio classification pipeline using any `AutoModelForAudioClassification`.
1444
+ * This pipeline predicts the class of a raw waveform or an audio file.
1445
+ *
1446
+ * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`.
1447
+ * ```javascript
1448
+ * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');
1449
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
1450
+ * const output = await classifier(url);
1451
+ * // [
1452
+ * // { label: 'male', score: 0.9981542229652405 },
1453
+ * // { label: 'female', score: 0.001845747814513743 }
1454
+ * // ]
1455
+ * ```
1456
+ *
1457
+ * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results.
1458
+ * ```javascript
1459
+ * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');
1460
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav';
1461
+ * const output = await classifier(url, { top_k: 4 });
1462
+ * // [
1463
+ * // { label: 'Meow', score: 0.5617874264717102 },
1464
+ * // { label: 'Cat', score: 0.22365376353263855 },
1465
+ * // { label: 'Domestic animals, pets', score: 0.1141069084405899 },
1466
+ * // { label: 'Animal', score: 0.08985692262649536 },
1467
+ * // ]
1468
+ * ```
1469
+ */
1470
+ export class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) {
1471
+
1472
+ /**
1473
+ * Create a new AudioClassificationPipeline.
1474
+ * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1475
+ */
1476
+ constructor(options) {
1477
+ super(options);
1478
+ }
1479
+
1480
+ /** @type {AudioClassificationPipelineCallback} */
1481
+ async _call(audio, {
1482
+ top_k = 5
1483
+ } = {}) {
1484
+
1485
+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1486
+ const preparedAudios = await prepareAudios(audio, sampling_rate);
1487
+
1488
+ const id2label = this.model.config.id2label;
1489
+
1490
+ const toReturn = [];
1491
+ for (const aud of preparedAudios) {
1492
+ const inputs = await this.processor(aud);
1493
+ const output = await this.model(inputs);
1494
+ const logits = output.logits[0];
1495
+
1496
+ const scores = await topk(new Tensor(
1497
+ 'float32',
1498
+ softmax(logits.data),
1499
+ logits.dims,
1500
+ ), top_k);
1501
+
1502
+ const values = scores[0].tolist();
1503
+ const indices = scores[1].tolist();
1504
+
1505
+ const vals = indices.map((x, i) => ({
1506
+ label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),
1507
+ score: /** @type {number} */ (values[i]),
1508
+ }));
1509
+
1510
+ toReturn.push(vals);
1511
+ };
1512
+ return Array.isArray(audio) ? toReturn : toReturn[0];
1513
+ }
1514
+ }
1515
+
1516
+ /**
1517
+ * @typedef {Object} ZeroShotAudioClassificationOutput
1518
+ * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
1519
+ * @property {number} score The score attributed by the model for that label (between 0 and 1).
1520
+ *
1521
+ * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines.
1522
+ * @property {string} [hypothesis_template="This is a sound of {}."] The sentence used in conjunction with `candidate_labels`
1523
+ * to attempt the audio classification by replacing the placeholder with the candidate_labels.
1524
+ * Then likelihood is estimated by using `logits_per_audio`.
1525
+ *
1526
+ * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs.
1527
+ * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:
1528
+ * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
1529
+ * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.
1530
+ * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.
1531
+ * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
1532
+ * @param {string[]} candidate_labels The candidate labels for this audio.
1533
+ * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification.
1534
+ * @returns {Promise<ZeroShotAudioClassificationOutput[]|ZeroShotAudioClassificationOutput[][]>} An array of objects containing the predicted labels and scores.
1535
+ *
1536
+ * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType
1537
+ */
1538
+
1539
+ /**
1540
+ * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
1541
+ * provide an audio and a set of `candidate_labels`.
1542
+ *
1543
+ * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`.
1544
+ * ```javascript
1545
+ * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');
1546
+ * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav';
1547
+ * const candidate_labels = ['dog', 'vaccum cleaner'];
1548
+ * const scores = await classifier(audio, candidate_labels);
1549
+ * // [
1550
+ * // { score: 0.9993992447853088, label: 'dog' },
1551
+ * // { score: 0.0006007603369653225, label: 'vaccum cleaner' }
1552
+ * // ]
1553
+ * ```
1554
+ */
1555
+ export class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) {
1556
+
1557
+ /**
1558
+ * Create a new ZeroShotAudioClassificationPipeline.
1559
+ * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1560
+ */
1561
+ constructor(options) {
1562
+ super(options);
1563
+ }
1564
+
1565
+ /** @type {ZeroShotAudioClassificationPipelineCallback} */
1566
+ async _call(audio, candidate_labels, {
1567
+ hypothesis_template = "This is a sound of {}."
1568
+ } = {}) {
1569
+
1570
+ const single = !Array.isArray(audio);
1571
+ if (single) {
1572
+ audio = [/** @type {AudioInput} */ (audio)];
1573
+ }
1574
+
1575
+ // Insert label into hypothesis template
1576
+ const texts = candidate_labels.map(
1577
+ x => hypothesis_template.replace('{}', x)
1578
+ );
1579
+
1580
+ // Run tokenization
1581
+ const text_inputs = this.tokenizer(texts, {
1582
+ padding: true,
1583
+ truncation: true,
1584
+ });
1585
+
1586
+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1587
+ const preparedAudios = await prepareAudios(audio, sampling_rate);
1588
+
1589
+ const toReturn = [];
1590
+ for (const aud of preparedAudios) {
1591
+ const audio_inputs = await this.processor(aud);
1592
+
1593
+ // Run model with both text and audio inputs
1594
+ const output = await this.model({ ...text_inputs, ...audio_inputs });
1595
+
1596
+ // Compute softmax per audio
1597
+ const probs = softmax(output.logits_per_audio.data);
1598
+
1599
+ toReturn.push([...probs].map((x, i) => ({
1600
+ score: x,
1601
+ label: candidate_labels[i]
1602
+ })));
1603
+ }
1604
+ return single ? toReturn[0] : toReturn;
1605
+ }
1606
+ }
1607
+
1608
+ /**
1609
+ * @typedef {Object} Chunk
1610
+ * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds.
1611
+ * @property {string} text The recognized text.
1612
+ */
1613
+
1614
+ /**
1615
+ * @typedef {Object} AutomaticSpeechRecognitionOutput
1616
+ * @property {string} text The recognized text.
1617
+ * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list
1618
+ * containing all the various text chunks identified by the model.
1619
+ *
1620
+ * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines.
1621
+ * @property {boolean|'word'} [return_timestamps] Whether to return timestamps or not. Default is `false`.
1622
+ * @property {number} [chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking).
1623
+ * @property {number} [stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.
1624
+ * @property {boolean} [force_full_sequences] Whether to force outputting full sequences or not. Default is `false`.
1625
+ * @property {string} [language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.
1626
+ * @property {string} [task] The task to perform. Default is `null`, meaning it should be auto-detected.
1627
+ * @property {number} [num_frames] The number of frames in the input audio.
1628
+ * @typedef {import('./generation/configuration_utils.js').GenerationConfig & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig
1629
+ *
1630
+ * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text.
1631
+ * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either:
1632
+ * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
1633
+ * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.
1634
+ * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.
1635
+ * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
1636
+ * @param {Partial<AutomaticSpeechRecognitionConfig>} [options] Additional keyword arguments to pass along to the generate method of the model.
1637
+ * @returns {Promise<AutomaticSpeechRecognitionOutput|AutomaticSpeechRecognitionOutput[]>} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`.
1638
+ *
1639
+ * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType
1640
+ */
1641
+
1642
+ /**
1643
+ * Pipeline that aims at extracting spoken text contained within some audio.
1644
+ *
1645
+ * **Example:** Transcribe English.
1646
+ * ```javascript
1647
+ * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
1648
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
1649
+ * const output = await transcriber(url);
1650
+ * // { text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." }
1651
+ * ```
1652
+ *
1653
+ * **Example:** Transcribe English w/ timestamps.
1654
+ * ```javascript
1655
+ * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
1656
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
1657
+ * const output = await transcriber(url, { return_timestamps: true });
1658
+ * // {
1659
+ * // text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country."
1660
+ * // chunks: [
1661
+ * // { timestamp: [0, 8], text: " And so my fellow Americans ask not what your country can do for you" }
1662
+ * // { timestamp: [8, 11], text: " ask what you can do for your country." }
1663
+ * // ]
1664
+ * // }
1665
+ * ```
1666
+ *
1667
+ * **Example:** Transcribe English w/ word-level timestamps.
1668
+ * ```javascript
1669
+ * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
1670
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';
1671
+ * const output = await transcriber(url, { return_timestamps: 'word' });
1672
+ * // {
1673
+ * // "text": " And so my fellow Americans ask not what your country can do for you ask what you can do for your country.",
1674
+ * // "chunks": [
1675
+ * // { "text": " And", "timestamp": [0, 0.78] },
1676
+ * // { "text": " so", "timestamp": [0.78, 1.06] },
1677
+ * // { "text": " my", "timestamp": [1.06, 1.46] },
1678
+ * // ...
1679
+ * // { "text": " for", "timestamp": [9.72, 9.92] },
1680
+ * // { "text": " your", "timestamp": [9.92, 10.22] },
1681
+ * // { "text": " country.", "timestamp": [10.22, 13.5] }
1682
+ * // ]
1683
+ * // }
1684
+ * ```
1685
+ *
1686
+ * **Example:** Transcribe French.
1687
+ * ```javascript
1688
+ * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
1689
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';
1690
+ * const output = await transcriber(url, { language: 'french', task: 'transcribe' });
1691
+ * // { text: " J'adore, j'aime, je n'aime pas, je déteste." }
1692
+ * ```
1693
+ *
1694
+ * **Example:** Translate French to English.
1695
+ * ```javascript
1696
+ * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
1697
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';
1698
+ * const output = await transcriber(url, { language: 'french', task: 'translate' });
1699
+ * // { text: " I love, I like, I don't like, I hate." }
1700
+ * ```
1701
+ *
1702
+ * **Example:** Transcribe/translate audio longer than 30 seconds.
1703
+ * ```javascript
1704
+ * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
1705
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav';
1706
+ * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 });
1707
+ * // { text: " So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up" }
1708
+ * ```
1709
+ */
1710
+ export class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) {
1711
+
1712
+ /**
1713
+ * Create a new AutomaticSpeechRecognitionPipeline.
1714
+ * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1715
+ */
1716
+ constructor(options) {
1717
+ super(options);
1718
+ }
1719
+
1720
+ /** @type {AutomaticSpeechRecognitionPipelineCallback} */
1721
+ async _call(audio, kwargs = {}) {
1722
+ switch (this.model.config.model_type) {
1723
+ case 'whisper':
1724
+ return this._call_whisper(audio, kwargs)
1725
+ case 'wav2vec2':
1726
+ case 'wav2vec2-bert':
1727
+ case 'unispeech':
1728
+ case 'unispeech-sat':
1729
+ case 'hubert':
1730
+ return this._call_wav2vec2(audio, kwargs)
1731
+ default:
1732
+ throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)
1733
+ }
1734
+ }
1735
+
1736
+ /**
1737
+ * @type {AutomaticSpeechRecognitionPipelineCallback}
1738
+ * @private
1739
+ */
1740
+ async _call_wav2vec2(audio, kwargs) {
1741
+ // TODO use kwargs
1742
+
1743
+ if (kwargs.language) {
1744
+ console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".');
1745
+ }
1746
+ if (kwargs.task) {
1747
+ console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');
1748
+ }
1749
+
1750
+ const single = !Array.isArray(audio);
1751
+ if (single) {
1752
+ audio = [/** @type {AudioInput} */ (audio)];
1753
+ }
1754
+
1755
+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1756
+ const preparedAudios = await prepareAudios(audio, sampling_rate);
1757
+
1758
+ const toReturn = [];
1759
+ for (const aud of preparedAudios) {
1760
+ const inputs = await this.processor(aud);
1761
+ const output = await this.model(inputs);
1762
+ const logits = output.logits[0];
1763
+
1764
+ const predicted_ids = [];
1765
+ for (const item of logits) {
1766
+ predicted_ids.push(max(item.data)[1])
1767
+ }
1768
+ const predicted_sentences = this.tokenizer.decode(predicted_ids)
1769
+ toReturn.push({ text: predicted_sentences })
1770
+ }
1771
+ return single ? toReturn[0] : toReturn;
1772
+ }
1773
+
1774
+ /**
1775
+ * @type {AutomaticSpeechRecognitionPipelineCallback}
1776
+ * @private
1777
+ */
1778
+ async _call_whisper(audio, kwargs) {
1779
+ const return_timestamps = kwargs.return_timestamps ?? false;
1780
+ const chunk_length_s = kwargs.chunk_length_s ?? 0;
1781
+ const force_full_sequences = kwargs.force_full_sequences ?? false;
1782
+ let stride_length_s = kwargs.stride_length_s ?? null;
1783
+
1784
+ const generation_config = { ...kwargs }
1785
+
1786
+ if (return_timestamps === 'word') {
1787
+ generation_config['return_token_timestamps'] = true;
1788
+ generation_config['return_timestamps'] = false; // Do not predict timestamp tokens
1789
+ }
1790
+
1791
+ const single = !Array.isArray(audio);
1792
+ if (single) {
1793
+ audio = [/** @type {AudioInput} */ (audio)];
1794
+ }
1795
+
1796
+ const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions;
1797
+ const hop_length = this.processor.feature_extractor.config.hop_length;
1798
+
1799
+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1800
+ const preparedAudios = await prepareAudios(audio, sampling_rate);
1801
+
1802
+ const toReturn = [];
1803
+ for (const aud of preparedAudios) {
1804
+ /** @type {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: bigint[], token_timestamps?: number[]}[]} */
1805
+ let chunks = [];
1806
+ if (chunk_length_s > 0) {
1807
+ if (stride_length_s === null) {
1808
+ stride_length_s = chunk_length_s / 6;
1809
+ } else if (chunk_length_s <= stride_length_s) {
1810
+ throw Error("`chunk_length_s` must be larger than `stride_length_s`.")
1811
+ }
1812
+
1813
+ // TODO support different stride_length_s (for left and right)
1814
+
1815
+ const window = sampling_rate * chunk_length_s;
1816
+ const stride = sampling_rate * stride_length_s;
1817
+ const jump = window - 2 * stride;
1818
+ let offset = 0;
1819
+
1820
+ // Create subarrays of audio with overlaps
1821
+ while (true) {
1822
+ const offset_end = offset + window;
1823
+ const subarr = aud.subarray(offset, offset_end);
1824
+ const feature = await this.processor(subarr);
1825
+
1826
+ const is_first = offset === 0;
1827
+ const is_last = offset_end >= aud.length;
1828
+ chunks.push({
1829
+ stride: [
1830
+ subarr.length,
1831
+ is_first ? 0 : stride,
1832
+ is_last ? 0 : stride
1833
+ ],
1834
+ input_features: feature.input_features,
1835
+ is_last,
1836
+ })
1837
+ if (is_last) break;
1838
+ offset += jump;
1839
+ }
1840
+
1841
+ } else {
1842
+ chunks = [{
1843
+ stride: [aud.length, 0, 0],
1844
+ input_features: (await this.processor(aud)).input_features,
1845
+ is_last: true
1846
+ }]
1847
+ }
1848
+
1849
+ // Generate for each set of input features
1850
+ for (const chunk of chunks) {
1851
+ generation_config.num_frames = Math.floor(chunk.stride[0] / hop_length);
1852
+
1853
+ // NOTE: doing sequentially for now
1854
+ const data = await this.model.generate({
1855
+ inputs: chunk.input_features,
1856
+ ...generation_config
1857
+ });
1858
+
1859
+ // TODO: Right now we only get top beam
1860
+ if (return_timestamps === 'word') {
1861
+ chunk.tokens = data.sequences.tolist()[0];
1862
+ chunk.token_timestamps = data.token_timestamps.tolist()[0].map(
1863
+ (/** @type {number} */ x) => round(x, 2)
1864
+ );
1865
+
1866
+ } else {
1867
+ chunk.tokens = (/** @type {Tensor} */(data))[0].tolist();
1868
+ }
1869
+
1870
+ // convert stride to seconds
1871
+ chunk.stride = chunk.stride.map(x => x / sampling_rate);
1872
+ }
1873
+
1874
+ // Merge text chunks
1875
+ // @ts-ignore
1876
+ const [full_text, optional] = this.tokenizer._decode_asr(chunks, {
1877
+ time_precision, return_timestamps, force_full_sequences
1878
+ });
1879
+
1880
+ toReturn.push({ text: full_text, ...optional })
1881
+ }
1882
+ return single ? toReturn[0] : toReturn;
1883
+ }
1884
+ }
1885
+
1886
+ /**
1887
+ * @typedef {Object} ImageToTextSingle
1888
+ * @property {string} generated_text The generated text.
1889
+ * @typedef {ImageToTextSingle[]} ImageToTextOutput
1890
+ *
1891
+ * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs.
1892
+ * @param {ImagePipelineInputs} texts The images to be captioned.
1893
+ * @param {Partial<import('./generation/configuration_utils.js').GenerationConfig>} [options] Additional keyword arguments to pass along to the generate method of the model.
1894
+ * @returns {Promise<ImageToTextOutput|ImageToTextOutput[]>} An object (or array of objects) containing the generated text(s).
1895
+ *
1896
+ * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType
1897
+ */
1898
+
1899
+ /**
1900
+ * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.
1901
+ *
1902
+ * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`.
1903
+ * ```javascript
1904
+ * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');
1905
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
1906
+ * const output = await captioner(url);
1907
+ * // [{ generated_text: 'a cat laying on a couch with another cat' }]
1908
+ * ```
1909
+ *
1910
+ * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`.
1911
+ * ```javascript
1912
+ * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');
1913
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg';
1914
+ * const output = await captioner(url);
1915
+ * // [{ generated_text: 'Mr. Brown commented icily.' }]
1916
+ * ```
1917
+ */
1918
+ export class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) {
1919
+
1920
+ /**
1921
+ * Create a new ImageToTextPipeline.
1922
+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1923
+ */
1924
+ constructor(options) {
1925
+ super(options);
1926
+ }
1927
+
1928
+ /** @type {ImageToTextPipelineCallback} */
1929
+ async _call(images, generate_kwargs = {}) {
1930
+
1931
+ const isBatched = Array.isArray(images);
1932
+ const preparedImages = await prepareImages(images);
1933
+
1934
+ const { pixel_values } = await this.processor(preparedImages);
1935
+
1936
+ const toReturn = [];
1937
+ for (const batch of pixel_values) {
1938
+ batch.dims = [1, ...batch.dims]
1939
+ const output = await this.model.generate({ inputs: batch, ...generate_kwargs });
1940
+ const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output), {
1941
+ skip_special_tokens: true,
1942
+ }).map(x => ({ generated_text: x.trim() }))
1943
+ toReturn.push(decoded);
1944
+ }
1945
+
1946
+ return isBatched ? toReturn : toReturn[0];
1947
+ }
1948
+ }
1949
+
1950
+ /**
1951
+ * @typedef {Object} ImageClassificationSingle
1952
+ * @property {string} label The label identified by the model.
1953
+ * @property {number} score The score attributed by the model for that label.
1954
+ * @typedef {ImageClassificationSingle[]} ImageClassificationOutput
1955
+ *
1956
+ * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines.
1957
+ * @property {number} [top_k=1] The number of top labels that will be returned by the pipeline.
1958
+ *
1959
+ * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.
1960
+ * @param {ImagePipelineInputs} images The input images(s) to be classified.
1961
+ * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification.
1962
+ * @returns {Promise<ImageClassificationOutput|ImageClassificationOutput[]>} An array or object containing the predicted labels and scores.
1963
+ *
1964
+ * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType
1965
+ */
1966
+
1967
+ /**
1968
+ * Image classification pipeline using any `AutoModelForImageClassification`.
1969
+ * This pipeline predicts the class of an image.
1970
+ *
1971
+ * **Example:** Classify an image.
1972
+ * ```javascript
1973
+ * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
1974
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
1975
+ * const output = await classifier(url);
1976
+ * // [
1977
+ * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
1978
+ * // ]
1979
+ * ```
1980
+ *
1981
+ * **Example:** Classify an image and return top `n` classes.
1982
+ * ```javascript
1983
+ * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
1984
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
1985
+ * const output = await classifier(url, { top_k: 3 });
1986
+ * // [
1987
+ * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
1988
+ * // { label: 'tiger cat', score: 0.3634825646877289 },
1989
+ * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },
1990
+ * // ]
1991
+ * ```
1992
+ *
1993
+ * **Example:** Classify an image and return all classes.
1994
+ * ```javascript
1995
+ * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
1996
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
1997
+ * const output = await classifier(url, { top_k: 0 });
1998
+ * // [
1999
+ * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
2000
+ * // { label: 'tiger cat', score: 0.3634825646877289 },
2001
+ * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },
2002
+ * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 },
2003
+ * // ...
2004
+ * // ]
2005
+ * ```
2006
+ */
2007
+ export class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) {
2008
+
2009
+ /**
2010
+ * Create a new ImageClassificationPipeline.
2011
+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2012
+ */
2013
+ constructor(options) {
2014
+ super(options);
2015
+ }
2016
+
2017
+ /** @type {ImageClassificationPipelineCallback} */
2018
+ async _call(images, {
2019
+ top_k = 5
2020
+ } = {}) {
2021
+
2022
+ const preparedImages = await prepareImages(images);
2023
+
2024
+ const { pixel_values } = await this.processor(preparedImages);
2025
+ const output = await this.model({ pixel_values });
2026
+
2027
+ const id2label = this.model.config.id2label;
2028
+
2029
+ /** @type {ImageClassificationOutput[]} */
2030
+ const toReturn = [];
2031
+ for (const batch of output.logits) {
2032
+ const scores = await topk(new Tensor(
2033
+ 'float32',
2034
+ softmax(batch.data),
2035
+ batch.dims,
2036
+ ), top_k);
2037
+
2038
+ const values = scores[0].tolist();
2039
+ const indices = scores[1].tolist();
2040
+
2041
+ const vals = indices.map((x, i) => ({
2042
+ label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),
2043
+ score: /** @type {number} */ (values[i]),
2044
+ }));
2045
+ toReturn.push(vals);
2046
+ }
2047
+
2048
+ return Array.isArray(images) ? toReturn : toReturn[0];
2049
+ }
2050
+
2051
+ }
2052
+
2053
+ /**
2054
+ * @typedef {Object} ImageSegmentationPipelineOutput
2055
+ * @property {string} label The label of the segment.
2056
+ * @property {number|null} score The score of the segment.
2057
+ * @property {RawImage} mask The mask of the segment.
2058
+ *
2059
+ * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines.
2060
+ * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks.
2061
+ * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
2062
+ * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments.
2063
+ * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],
2064
+ * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).
2065
+ * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels.
2066
+ * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes.
2067
+ *
2068
+ * @callback ImageSegmentationPipelineCallback Segment the input images.
2069
+ * @param {ImagePipelineInputs} images The input images.
2070
+ * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation.
2071
+ * @returns {Promise<ImageSegmentationPipelineOutput[]>} The annotated segments.
2072
+ *
2073
+ * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType
2074
+ */
2075
+
2076
+ /**
2077
+ * Image segmentation pipeline using any `AutoModelForXXXSegmentation`.
2078
+ * This pipeline predicts masks of objects and their classes.
2079
+ *
2080
+ * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`.
2081
+ * ```javascript
2082
+ * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');
2083
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
2084
+ * const output = await segmenter(url);
2085
+ * // [
2086
+ * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } },
2087
+ * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } }
2088
+ * // ]
2089
+ * ```
2090
+ */
2091
+ export class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) {
2092
+ /**
2093
+ * Create a new ImageSegmentationPipeline.
2094
+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2095
+ */
2096
+ constructor(options) {
2097
+ super(options);
2098
+
2099
+ this.subtasks_mapping = {
2100
+ // Mapping of subtasks to their corresponding post-processing function names.
2101
+ panoptic: 'post_process_panoptic_segmentation',
2102
+ instance: 'post_process_instance_segmentation',
2103
+ semantic: 'post_process_semantic_segmentation'
2104
+ }
2105
+ }
2106
+
2107
+ /** @type {ImageSegmentationPipelineCallback} */
2108
+ async _call(images, {
2109
+ threshold = 0.5,
2110
+ mask_threshold = 0.5,
2111
+ overlap_mask_area_threshold = 0.8,
2112
+ label_ids_to_fuse = null,
2113
+ target_sizes = null,
2114
+ subtask = null,
2115
+ } = {}) {
2116
+ const isBatched = Array.isArray(images);
2117
+
2118
+ if (isBatched && images.length !== 1) {
2119
+ throw Error("Image segmentation pipeline currently only supports a batch size of 1.");
2120
+ }
2121
+
2122
+ const preparedImages = await prepareImages(images);
2123
+ const imageSizes = preparedImages.map(x => [x.height, x.width]);
2124
+
2125
+ const { pixel_values, pixel_mask } = await this.processor(preparedImages);
2126
+ const output = await this.model({ pixel_values, pixel_mask });
2127
+
2128
+ let fn = null;
2129
+ if (subtask !== null) {
2130
+ fn = this.subtasks_mapping[subtask];
2131
+ } else {
2132
+ for (let [task, func] of Object.entries(this.subtasks_mapping)) {
2133
+ if (func in this.processor.feature_extractor) {
2134
+ fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor);
2135
+ subtask = task;
2136
+ break;
2137
+ }
2138
+ }
2139
+ }
2140
+
2141
+ const id2label = this.model.config.id2label;
2142
+
2143
+ /** @type {ImageSegmentationPipelineOutput[]} */
2144
+ const annotation = [];
2145
+ if (subtask === 'panoptic' || subtask === 'instance') {
2146
+ const processed = fn(
2147
+ output,
2148
+ threshold,
2149
+ mask_threshold,
2150
+ overlap_mask_area_threshold,
2151
+ label_ids_to_fuse,
2152
+ target_sizes ?? imageSizes, // TODO FIX?
2153
+ )[0];
2154
+
2155
+ const segmentation = processed.segmentation;
2156
+
2157
+ for (const segment of processed.segments_info) {
2158
+ const maskData = new Uint8ClampedArray(segmentation.data.length);
2159
+ for (let i = 0; i < segmentation.data.length; ++i) {
2160
+ if (segmentation.data[i] === segment.id) {
2161
+ maskData[i] = 255;
2162
+ }
2163
+ }
2164
+
2165
+ const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)
2166
+
2167
+ annotation.push({
2168
+ score: segment.score,
2169
+ label: id2label[segment.label_id],
2170
+ mask: mask
2171
+ })
2172
+ }
2173
+
2174
+ } else if (subtask === 'semantic') {
2175
+ const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0];
2176
+
2177
+ for (const label of labels) {
2178
+ const maskData = new Uint8ClampedArray(segmentation.data.length);
2179
+ for (let i = 0; i < segmentation.data.length; ++i) {
2180
+ if (segmentation.data[i] === label) {
2181
+ maskData[i] = 255;
2182
+ }
2183
+ }
2184
+
2185
+ const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);
2186
+
2187
+ annotation.push({
2188
+ score: null,
2189
+ label: id2label[label],
2190
+ mask: mask
2191
+ });
2192
+ }
2193
+ } else {
2194
+ throw Error(`Subtask ${subtask} not supported.`);
2195
+ }
2196
+
2197
+ return annotation;
2198
+ }
2199
+ }
2200
+
2201
+ /**
2202
+ * @typedef {Object} ZeroShotImageClassificationOutput
2203
+ * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
2204
+ * @property {number} score The score attributed by the model for that label (between 0 and 1).
2205
+ *
2206
+ * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines.
2207
+ * @property {string} [hypothesis_template="This is a photo of {}"] The sentence used in conjunction with `candidate_labels`
2208
+ * to attempt the image classification by replacing the placeholder with the candidate_labels.
2209
+ * Then likelihood is estimated by using `logits_per_image`.
2210
+ *
2211
+ * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.
2212
+ * @param {ImagePipelineInputs} images The input images.
2213
+ * @param {string[]} candidate_labels The candidate labels for this image.
2214
+ * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification.
2215
+ * @returns {Promise<ZeroShotImageClassificationOutput[]|ZeroShotImageClassificationOutput[][]>} An array of objects containing the predicted labels and scores.
2216
+ *
2217
+ * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType
2218
+ */
2219
+
2220
+ /**
2221
+ * Zero shot image classification pipeline. This pipeline predicts the class of
2222
+ * an image when you provide an image and a set of `candidate_labels`.
2223
+ *
2224
+ * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`.
2225
+ * ```javascript
2226
+ * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');
2227
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';
2228
+ * const output = await classifier(url, ['tiger', 'horse', 'dog']);
2229
+ * // [
2230
+ * // { score: 0.9993917942047119, label: 'tiger' },
2231
+ * // { score: 0.0003519294841680676, label: 'horse' },
2232
+ * // { score: 0.0002562698791734874, label: 'dog' }
2233
+ * // ]
2234
+ * ```
2235
+ */
2236
+ export class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) {
2237
+ /**
2238
+ * Create a new ZeroShotImageClassificationPipeline.
2239
+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2240
+ */
2241
+ constructor(options) {
2242
+ super(options);
2243
+ }
2244
+
2245
+ /** @type {ZeroShotImageClassificationPipelineCallback} */
2246
+ async _call(images, candidate_labels, {
2247
+ hypothesis_template = "This is a photo of {}"
2248
+ } = {}) {
2249
+
2250
+ const isBatched = Array.isArray(images);
2251
+ const preparedImages = await prepareImages(images);
2252
+
2253
+ // Insert label into hypothesis template
2254
+ const texts = candidate_labels.map(
2255
+ x => hypothesis_template.replace('{}', x)
2256
+ );
2257
+
2258
+ // Run tokenization
2259
+ const text_inputs = this.tokenizer(texts, {
2260
+ padding: this.model.config.model_type === 'siglip' ? 'max_length' : true,
2261
+ truncation: true,
2262
+ });
2263
+
2264
+ // Run processor
2265
+ const { pixel_values } = await this.processor(preparedImages);
2266
+
2267
+ // Run model with both text and pixel inputs
2268
+ const output = await this.model({ ...text_inputs, pixel_values });
2269
+
2270
+ const function_to_apply =
2271
+ this.model.config.model_type === 'siglip'
2272
+ ? batch => batch.sigmoid().data
2273
+ : batch => softmax(batch.data);
2274
+
2275
+ // Compare each image with each candidate label
2276
+ const toReturn = [];
2277
+ for (const batch of output.logits_per_image) {
2278
+ // Compute softmax per image
2279
+ const probs = function_to_apply(batch);
2280
+
2281
+ const result = [...probs].map((x, i) => ({
2282
+ score: x,
2283
+ label: candidate_labels[i]
2284
+ }));
2285
+ result.sort((a, b) => b.score - a.score); // sort by score in descending order
2286
+ toReturn.push(result);
2287
+ }
2288
+
2289
+ return isBatched ? toReturn : toReturn[0];
2290
+ }
2291
+ }
2292
+
2293
+
2294
+ /**
2295
+ * @typedef {Object} ObjectDetectionPipelineSingle
2296
+ * @property {string} label The class label identified by the model.
2297
+ * @property {number} score The score attributed by the model for that label.
2298
+ * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.
2299
+ * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput
2300
+ *
2301
+ * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines.
2302
+ * @property {number} [threshold=0.9] The threshold used to filter boxes by score.
2303
+ * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).
2304
+ *
2305
+ * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
2306
+ * @param {ImagePipelineInputs} images The input images.
2307
+ * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection.
2308
+ * @returns {Promise<ObjectDetectionPipelineOutput|ObjectDetectionPipelineOutput[]>} A list of objects or a list of list of objects.
2309
+ *
2310
+ * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType
2311
+ */
2312
+
2313
+ /**
2314
+ * Object detection pipeline using any `AutoModelForObjectDetection`.
2315
+ * This pipeline predicts bounding boxes of objects and their classes.
2316
+ *
2317
+ * **Example:** Run object-detection with `Xenova/detr-resnet-50`.
2318
+ * ```javascript
2319
+ * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');
2320
+ * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
2321
+ * const output = await detector(img, { threshold: 0.9 });
2322
+ * // [{
2323
+ * // score: 0.9976370930671692,
2324
+ * // label: "remote",
2325
+ * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 }
2326
+ * // },
2327
+ * // ...
2328
+ * // {
2329
+ * // score: 0.9984092116355896,
2330
+ * // label: "cat",
2331
+ * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 }
2332
+ * // }]
2333
+ * ```
2334
+ */
2335
+ export class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) {
2336
+
2337
+ /**
2338
+ * Create a new ObjectDetectionPipeline.
2339
+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2340
+ */
2341
+ constructor(options) {
2342
+ super(options);
2343
+ }
2344
+
2345
+ /** @type {ObjectDetectionPipelineCallback} */
2346
+ async _call(images, {
2347
+ threshold = 0.9,
2348
+ percentage = false,
2349
+ } = {}) {
2350
+
2351
+ const isBatched = Array.isArray(images);
2352
+
2353
+ if (isBatched && images.length !== 1) {
2354
+ throw Error("Object detection pipeline currently only supports a batch size of 1.");
2355
+ }
2356
+ const preparedImages = await prepareImages(images);
2357
+
2358
+ const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]);
2359
+
2360
+ const { pixel_values, pixel_mask } = await this.processor(preparedImages);
2361
+ const output = await this.model({ pixel_values, pixel_mask });
2362
+
2363
+ // @ts-ignore
2364
+ const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);
2365
+
2366
+ // Add labels
2367
+ const id2label = this.model.config.id2label;
2368
+
2369
+ // Format output
2370
+ /** @type {ObjectDetectionPipelineOutput[]} */
2371
+ const result = processed.map(batch => (
2372
+ batch.boxes.map((box, i) => ({
2373
+ score: batch.scores[i],
2374
+ label: id2label[batch.classes[i]],
2375
+ box: get_bounding_box(box, !percentage),
2376
+ }))
2377
+ ))
2378
+
2379
+ return isBatched ? result : result[0];
2380
+ }
2381
+ }
2382
+
2383
+
2384
+ /**
2385
+ * @typedef {Object} ZeroShotObjectDetectionOutput
2386
+ * @property {string} label Text query corresponding to the found object.
2387
+ * @property {number} score Score corresponding to the object (between 0 and 1).
2388
+ * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.
2389
+ *
2390
+ * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines.
2391
+ * @property {number} [threshold=0.1] The probability necessary to make a prediction.
2392
+ * @property {number} [top_k=null] The number of top predictions that will be returned by the pipeline.
2393
+ * If the provided number is `null` or higher than the number of predictions available, it will default
2394
+ * to the number of predictions.
2395
+ * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).
2396
+ *
2397
+ * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
2398
+ * @param {ImagePipelineInputs} images The input images.
2399
+ * @param {string[]} candidate_labels What the model should recognize in the image.
2400
+ * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection.
2401
+ * @returns {Promise<ZeroShotObjectDetectionOutput[]|ZeroShotObjectDetectionOutput[][]>} An array of objects containing the predicted labels, scores, and bounding boxes.
2402
+ *
2403
+ * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType
2404
+ */
2405
+
2406
+ /**
2407
+ * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of
2408
+ * objects when you provide an image and a set of `candidate_labels`.
2409
+ *
2410
+ * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`.
2411
+ * ```javascript
2412
+ * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
2413
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png';
2414
+ * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag'];
2415
+ * const output = await detector(url, candidate_labels);
2416
+ * // [
2417
+ * // {
2418
+ * // score: 0.24392342567443848,
2419
+ * // label: 'human face',
2420
+ * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 }
2421
+ * // },
2422
+ * // {
2423
+ * // score: 0.15129457414150238,
2424
+ * // label: 'american flag',
2425
+ * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 }
2426
+ * // },
2427
+ * // {
2428
+ * // score: 0.13649864494800568,
2429
+ * // label: 'helmet',
2430
+ * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 }
2431
+ * // },
2432
+ * // {
2433
+ * // score: 0.10262022167444229,
2434
+ * // label: 'rocket',
2435
+ * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 }
2436
+ * // }
2437
+ * // ]
2438
+ * ```
2439
+ *
2440
+ * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold).
2441
+ * ```javascript
2442
+ * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
2443
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png';
2444
+ * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera'];
2445
+ * const output = await detector(url, candidate_labels, { top_k: 4, threshold: 0.05 });
2446
+ * // [
2447
+ * // {
2448
+ * // score: 0.1606510728597641,
2449
+ * // label: 'sunglasses',
2450
+ * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 }
2451
+ * // },
2452
+ * // {
2453
+ * // score: 0.08935828506946564,
2454
+ * // label: 'hat',
2455
+ * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 }
2456
+ * // },
2457
+ * // {
2458
+ * // score: 0.08530698716640472,
2459
+ * // label: 'camera',
2460
+ * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 }
2461
+ * // },
2462
+ * // {
2463
+ * // score: 0.08349756896495819,
2464
+ * // label: 'book',
2465
+ * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 }
2466
+ * // }
2467
+ * // ]
2468
+ * ```
2469
+ */
2470
+ export class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) {
2471
+
2472
+ /**
2473
+ * Create a new ZeroShotObjectDetectionPipeline.
2474
+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2475
+ */
2476
+ constructor(options) {
2477
+ super(options);
2478
+ }
2479
+
2480
+ /** @type {ZeroShotObjectDetectionPipelineCallback} */
2481
+ async _call(images, candidate_labels, {
2482
+ threshold = 0.1,
2483
+ top_k = null,
2484
+ percentage = false,
2485
+ } = {}) {
2486
+
2487
+ const isBatched = Array.isArray(images);
2488
+ const preparedImages = await prepareImages(images);
2489
+
2490
+ // Run tokenization
2491
+ const text_inputs = this.tokenizer(candidate_labels, {
2492
+ padding: true,
2493
+ truncation: true,
2494
+ });
2495
+
2496
+ // Run processor
2497
+ const model_inputs = await this.processor(preparedImages);
2498
+
2499
+ // Since non-maximum suppression is performed for exporting, we need to
2500
+ // process each image separately. For more information, see:
2501
+ // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032
2502
+ const toReturn = [];
2503
+ for (let i = 0; i < preparedImages.length; ++i) {
2504
+ const image = preparedImages[i];
2505
+ const imageSize = percentage ? null : [[image.height, image.width]];
2506
+ const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);
2507
+
2508
+ // Run model with both text and pixel inputs
2509
+ const output = await this.model({ ...text_inputs, pixel_values });
2510
+
2511
+ // @ts-ignore
2512
+ const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];
2513
+ let result = processed.boxes.map((box, i) => ({
2514
+ score: processed.scores[i],
2515
+ label: candidate_labels[processed.classes[i]],
2516
+ box: get_bounding_box(box, !percentage),
2517
+ })).sort((a, b) => b.score - a.score);
2518
+ if (top_k !== null) {
2519
+ result = result.slice(0, top_k);
2520
+ }
2521
+ toReturn.push(result)
2522
+ }
2523
+
2524
+ return isBatched ? toReturn : toReturn[0];
2525
+ }
2526
+ }
2527
+
2528
+ /**
2529
+ * @typedef {Object} DocumentQuestionAnsweringSingle
2530
+ * @property {string} answer The generated text.
2531
+ * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput
2532
+ *
2533
+ * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document.
2534
+ * @param {ImageInput} image The image of the document to use.
2535
+ * @param {string} question A question to ask of the document.
2536
+ * @param {Partial<import('./generation/configuration_utils.js').GenerationConfig>} [options] Additional keyword arguments to pass along to the generate method of the model.
2537
+ * @returns {Promise<DocumentQuestionAnsweringOutput|DocumentQuestionAnsweringOutput[]>} An object (or array of objects) containing the answer(s).
2538
+ *
2539
+ * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType
2540
+ */
2541
+
2542
+ /**
2543
+ * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`.
2544
+ * The inputs/outputs are similar to the (extractive) question answering pipeline; however,
2545
+ * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context.
2546
+ *
2547
+ * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`.
2548
+ * ```javascript
2549
+ * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');
2550
+ * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';
2551
+ * const question = 'What is the invoice number?';
2552
+ * const output = await qa_pipeline(image, question);
2553
+ * // [{ answer: 'us-001' }]
2554
+ * ```
2555
+ */
2556
+ export class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) {
2557
+
2558
+ /**
2559
+ * Create a new DocumentQuestionAnsweringPipeline.
2560
+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2561
+ */
2562
+ constructor(options) {
2563
+ super(options);
2564
+ }
2565
+
2566
+ /** @type {DocumentQuestionAnsweringPipelineCallback} */
2567
+ async _call(image, question, generate_kwargs = {}) {
2568
+ throw new Error('This pipeline is not yet supported in Transformers.js v3.'); // TODO: Remove when implemented
2569
+
2570
+ // NOTE: For now, we only support a batch size of 1
2571
+
2572
+ // Preprocess image
2573
+ const preparedImage = (await prepareImages(image))[0];
2574
+ const { pixel_values } = await this.processor(preparedImage);
2575
+
2576
+ // Run tokenization
2577
+ const task_prompt = `<s_docvqa><s_question>${question}</s_question><s_answer>`;
2578
+ const decoder_input_ids = this.tokenizer(task_prompt, {
2579
+ add_special_tokens: false,
2580
+ padding: true,
2581
+ truncation: true,
2582
+ }).input_ids;
2583
+
2584
+ // Run model
2585
+ const output = await this.model.generate({
2586
+ inputs: pixel_values,
2587
+ max_length: this.model.config.decoder.max_position_embeddings,
2588
+ decoder_input_ids,
2589
+ ...generate_kwargs,
2590
+ });
2591
+
2592
+ // Decode output
2593
+ const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output))[0];
2594
+
2595
+ // Parse answer
2596
+ const match = decoded.match(/<s_answer>(.*?)<\/s_answer>/);
2597
+ let answer = null;
2598
+ if (match && match.length >= 2) {
2599
+ answer = match[1].trim();
2600
+ }
2601
+ return [{ answer }];
2602
+ }
2603
+ }
2604
+
2605
+
2606
+ /**
2607
+ * @typedef {Object} VocoderOptions
2608
+ * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.
2609
+ * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs
2610
+ */
2611
+
2612
+ /**
2613
+ * @typedef {Object} TextToAudioOutput
2614
+ * @property {Float32Array} audio The generated audio waveform.
2615
+ * @property {number} sampling_rate The sampling rate of the generated audio waveform.
2616
+ *
2617
+ * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines.
2618
+ * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it).
2619
+ *
2620
+ * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs.
2621
+ * @param {string|string[]} texts The text(s) to generate.
2622
+ * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method.
2623
+ * @returns {Promise<TextToAudioOutput>} An object containing the generated audio and sampling rate.
2624
+ *
2625
+ * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType
2626
+ */
2627
+
2628
+ /**
2629
+ * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`.
2630
+ * This pipeline generates an audio file from an input text and optional other conditional inputs.
2631
+ *
2632
+ * **Example:** Generate audio from text with `Xenova/speecht5_tts`.
2633
+ * ```javascript
2634
+ * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });
2635
+ * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin';
2636
+ * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings });
2637
+ * // {
2638
+ * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...],
2639
+ * // sampling_rate: 16000
2640
+ * // }
2641
+ * ```
2642
+ *
2643
+ * You can then save the audio to a .wav file with the `wavefile` package:
2644
+ * ```javascript
2645
+ * import wavefile from 'wavefile';
2646
+ * import fs from 'fs';
2647
+ *
2648
+ * const wav = new wavefile.WaveFile();
2649
+ * wav.fromScratch(1, out.sampling_rate, '32f', out.audio);
2650
+ * fs.writeFileSync('out.wav', wav.toBuffer());
2651
+ * ```
2652
+ *
2653
+ * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107).
2654
+ * ```javascript
2655
+ * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');
2656
+ * const out = await synthesizer('Bonjour');
2657
+ * // {
2658
+ * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...],
2659
+ * // sampling_rate: 16000
2660
+ * // }
2661
+ * ```
2662
+ */
2663
+ export class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) {
2664
+ DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"
2665
+
2666
+ /**
2667
+ * Create a new TextToAudioPipeline.
2668
+ * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
2669
+ */
2670
+ constructor(options) {
2671
+ super(options);
2672
+
2673
+ // TODO: Find a better way for `pipeline` to set the default vocoder
2674
+ this.vocoder = options.vocoder ?? null;
2675
+ }
2676
+
2677
+
2678
+ /** @type {TextToAudioPipelineCallback} */
2679
+ async _call(text_inputs, {
2680
+ speaker_embeddings = null,
2681
+ } = {}) {
2682
+
2683
+ // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model
2684
+ if (this.processor) {
2685
+ return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings });
2686
+ } else {
2687
+ return this._call_text_to_waveform(text_inputs);
2688
+ }
2689
+ }
2690
+
2691
+ async _call_text_to_waveform(text_inputs) {
2692
+
2693
+ // Run tokenization
2694
+ const inputs = this.tokenizer(text_inputs, {
2695
+ padding: true,
2696
+ truncation: true,
2697
+ });
2698
+
2699
+ // Generate waveform
2700
+ const { waveform } = await this.model(inputs);
2701
+
2702
+ const sampling_rate = this.model.config.sampling_rate;
2703
+ return {
2704
+ audio: waveform.data,
2705
+ sampling_rate,
2706
+ }
2707
+ }
2708
+
2709
+ async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {
2710
+
2711
+ // Load vocoder, if not provided
2712
+ if (!this.vocoder) {
2713
+ console.log('No vocoder specified, using default HifiGan vocoder.');
2714
+ this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: 'fp32' });
2715
+ }
2716
+
2717
+ // Load speaker embeddings as Float32Array from path/URL
2718
+ if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {
2719
+ // Load from URL with fetch
2720
+ speaker_embeddings = new Float32Array(
2721
+ await (await fetch(speaker_embeddings)).arrayBuffer()
2722
+ );
2723
+ }
2724
+
2725
+ if (speaker_embeddings instanceof Float32Array) {
2726
+ speaker_embeddings = new Tensor(
2727
+ 'float32',
2728
+ speaker_embeddings,
2729
+ [1, speaker_embeddings.length]
2730
+ )
2731
+ } else if (!(speaker_embeddings instanceof Tensor)) {
2732
+ throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.")
2733
+ }
2734
+
2735
+ // Run tokenization
2736
+ const { input_ids } = this.tokenizer(text_inputs, {
2737
+ padding: true,
2738
+ truncation: true,
2739
+ });
2740
+
2741
+ // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`
2742
+ // @ts-ignore
2743
+ const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder });
2744
+
2745
+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
2746
+ return {
2747
+ audio: waveform.data,
2748
+ sampling_rate,
2749
+ }
2750
+ }
2751
+ }
2752
+
2753
+ /**
2754
+ * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.
2755
+ * @param {ImagePipelineInputs} images The images to transform.
2756
+ * @returns {Promise<RawImage|RawImage[]>} The transformed image or list of images.
2757
+ *
2758
+ * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType
2759
+ */
2760
+
2761
+ /**
2762
+ * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.
2763
+ *
2764
+ * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`
2765
+ * ```javascript
2766
+ * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');
2767
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';
2768
+ * const output = await upscaler(url);
2769
+ * // RawImage {
2770
+ * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ],
2771
+ * // width: 512,
2772
+ * // height: 512,
2773
+ * // channels: 3
2774
+ * // }
2775
+ * ```
2776
+ */
2777
+ export class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) {
2778
+ /**
2779
+ * Create a new ImageToImagePipeline.
2780
+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2781
+ */
2782
+ constructor(options) {
2783
+ super(options);
2784
+ }
2785
+
2786
+ /** @type {ImageToImagePipelineCallback} */
2787
+ async _call(images) {
2788
+
2789
+ const preparedImages = await prepareImages(images);
2790
+ const inputs = await this.processor(preparedImages);
2791
+ const outputs = await this.model(inputs);
2792
+
2793
+ /** @type {RawImage[]} */
2794
+ const toReturn = [];
2795
+ for (const batch of outputs.reconstruction) {
2796
+ const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');
2797
+ toReturn.push(RawImage.fromTensor(output));
2798
+ }
2799
+
2800
+ return toReturn.length > 1 ? toReturn : toReturn[0];
2801
+ }
2802
+ }
2803
+
2804
+ /**
2805
+ * @typedef {Object} DepthEstimationPipelineOutput
2806
+ * @property {Tensor} predicted_depth The raw depth map predicted by the model.
2807
+ * @property {RawImage} depth The processed depth map as an image (with the same size as the input image).
2808
+ *
2809
+ * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs.
2810
+ * @param {ImagePipelineInputs} images The images to compute depth for.
2811
+ * @returns {Promise<DepthEstimationPipelineOutput|DepthEstimationPipelineOutput[]>} An image or a list of images containing result(s).
2812
+ *
2813
+ * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType
2814
+ */
2815
+
2816
+ /**
2817
+ * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
2818
+ *
2819
+ * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`
2820
+ * ```javascript
2821
+ * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');
2822
+ * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
2823
+ * const out = await depth_estimator(url);
2824
+ * // {
2825
+ * // predicted_depth: Tensor {
2826
+ * // dims: [ 384, 384 ],
2827
+ * // type: 'float32',
2828
+ * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ],
2829
+ * // size: 147456
2830
+ * // },
2831
+ * // depth: RawImage {
2832
+ * // data: Uint8Array(307200) [ 86, 86, 86, ... ],
2833
+ * // width: 640,
2834
+ * // height: 480,
2835
+ * // channels: 1
2836
+ * // }
2837
+ * // }
2838
+ * ```
2839
+ */
2840
+ export class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) {
2841
+ /**
2842
+ * Create a new DepthEstimationPipeline.
2843
+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2844
+ */
2845
+ constructor(options) {
2846
+ super(options);
2847
+ }
2848
+
2849
+ /** @type {DepthEstimationPipelineCallback} */
2850
+ async _call(images) {
2851
+
2852
+ const preparedImages = await prepareImages(images);
2853
+
2854
+ const inputs = await this.processor(preparedImages);
2855
+ const { predicted_depth } = await this.model(inputs);
2856
+
2857
+ const toReturn = [];
2858
+ for (let i = 0; i < preparedImages.length; ++i) {
2859
+ const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false);
2860
+ const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');
2861
+ toReturn.push({
2862
+ predicted_depth: predicted_depth[i],
2863
+ depth: RawImage.fromTensor(formatted),
2864
+ });
2865
+ }
2866
+
2867
+ return toReturn.length > 1 ? toReturn : toReturn[0];
2868
+ }
2869
+ }
2870
+
2871
+ const SUPPORTED_TASKS = Object.freeze({
2872
+ "text-classification": {
2873
+ "tokenizer": AutoTokenizer,
2874
+ "pipeline": TextClassificationPipeline,
2875
+ "model": AutoModelForSequenceClassification,
2876
+ "default": {
2877
+ // TODO: replace with original
2878
+ // "model": "distilbert-base-uncased-finetuned-sst-2-english",
2879
+ "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english",
2880
+ },
2881
+ "type": "text",
2882
+ },
2883
+ "token-classification": {
2884
+ "tokenizer": AutoTokenizer,
2885
+ "pipeline": TokenClassificationPipeline,
2886
+ "model": AutoModelForTokenClassification,
2887
+ "default": {
2888
+ // TODO: replace with original
2889
+ // "model": "Davlan/bert-base-multilingual-cased-ner-hrl",
2890
+ "model": "Xenova/bert-base-multilingual-cased-ner-hrl",
2891
+ },
2892
+ "type": "text",
2893
+ },
2894
+ "question-answering": {
2895
+ "tokenizer": AutoTokenizer,
2896
+ "pipeline": QuestionAnsweringPipeline,
2897
+ "model": AutoModelForQuestionAnswering,
2898
+ "default": {
2899
+ // TODO: replace with original
2900
+ // "model": "distilbert-base-cased-distilled-squad",
2901
+ "model": "Xenova/distilbert-base-cased-distilled-squad",
2902
+ },
2903
+ "type": "text",
2904
+ },
2905
+
2906
+ "fill-mask": {
2907
+ "tokenizer": AutoTokenizer,
2908
+ "pipeline": FillMaskPipeline,
2909
+ "model": AutoModelForMaskedLM,
2910
+ "default": {
2911
+ // TODO: replace with original
2912
+ // "model": "bert-base-uncased",
2913
+ "model": "Xenova/bert-base-uncased",
2914
+ },
2915
+ "type": "text",
2916
+ },
2917
+ "summarization": {
2918
+ "tokenizer": AutoTokenizer,
2919
+ "pipeline": SummarizationPipeline,
2920
+ "model": AutoModelForSeq2SeqLM,
2921
+ "default": {
2922
+ // TODO: replace with original
2923
+ // "model": "sshleifer/distilbart-cnn-6-6",
2924
+ "model": "Xenova/distilbart-cnn-6-6",
2925
+ },
2926
+ "type": "text",
2927
+ },
2928
+ "translation": {
2929
+ "tokenizer": AutoTokenizer,
2930
+ "pipeline": TranslationPipeline,
2931
+ "model": AutoModelForSeq2SeqLM,
2932
+ "default": {
2933
+ // TODO: replace with original
2934
+ // "model": "t5-small",
2935
+ "model": "Xenova/t5-small",
2936
+ },
2937
+ "type": "text",
2938
+ },
2939
+ "text2text-generation": {
2940
+ "tokenizer": AutoTokenizer,
2941
+ "pipeline": Text2TextGenerationPipeline,
2942
+ "model": AutoModelForSeq2SeqLM,
2943
+ "default": {
2944
+ // TODO: replace with original
2945
+ // "model": "google/flan-t5-small",
2946
+ "model": "Xenova/flan-t5-small",
2947
+ },
2948
+ "type": "text",
2949
+ },
2950
+ "text-generation": {
2951
+ "tokenizer": AutoTokenizer,
2952
+ "pipeline": TextGenerationPipeline,
2953
+ "model": AutoModelForCausalLM,
2954
+ "default": {
2955
+ // TODO: replace with original
2956
+ // "model": "gpt2",
2957
+ "model": "Xenova/gpt2",
2958
+ },
2959
+ "type": "text",
2960
+ },
2961
+ "zero-shot-classification": {
2962
+ "tokenizer": AutoTokenizer,
2963
+ "pipeline": ZeroShotClassificationPipeline,
2964
+ "model": AutoModelForSequenceClassification,
2965
+ "default": {
2966
+ // TODO: replace with original
2967
+ // "model": "typeform/distilbert-base-uncased-mnli",
2968
+ "model": "Xenova/distilbert-base-uncased-mnli",
2969
+ },
2970
+ "type": "text",
2971
+ },
2972
+ "audio-classification": {
2973
+ "pipeline": AudioClassificationPipeline,
2974
+ "model": AutoModelForAudioClassification,
2975
+ "processor": AutoProcessor,
2976
+ "default": {
2977
+ // TODO: replace with original
2978
+ // "model": "superb/wav2vec2-base-superb-ks",
2979
+ "model": "Xenova/wav2vec2-base-superb-ks",
2980
+ },
2981
+ "type": "audio",
2982
+ },
2983
+ "zero-shot-audio-classification": {
2984
+ "tokenizer": AutoTokenizer,
2985
+ "pipeline": ZeroShotAudioClassificationPipeline,
2986
+ "model": AutoModel,
2987
+ "processor": AutoProcessor,
2988
+ "default": {
2989
+ // TODO: replace with original
2990
+ // "model": "laion/clap-htsat-fused",
2991
+ "model": "Xenova/clap-htsat-unfused",
2992
+ },
2993
+ "type": "multimodal",
2994
+ },
2995
+ "automatic-speech-recognition": {
2996
+ "tokenizer": AutoTokenizer,
2997
+ "pipeline": AutomaticSpeechRecognitionPipeline,
2998
+ "model": [AutoModelForSpeechSeq2Seq, AutoModelForCTC],
2999
+ "processor": AutoProcessor,
3000
+ "default": {
3001
+ // TODO: replace with original
3002
+ // "model": "openai/whisper-tiny.en",
3003
+ "model": "Xenova/whisper-tiny.en",
3004
+ },
3005
+ "type": "multimodal",
3006
+ },
3007
+ "text-to-audio": {
3008
+ "tokenizer": AutoTokenizer,
3009
+ "pipeline": TextToAudioPipeline,
3010
+ "model": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],
3011
+ "processor": [AutoProcessor, /* Some don't use a processor */ null],
3012
+ "default": {
3013
+ // TODO: replace with original
3014
+ // "model": "microsoft/speecht5_tts",
3015
+ "model": "Xenova/speecht5_tts",
3016
+ },
3017
+ "type": "text",
3018
+ },
3019
+ "image-to-text": {
3020
+ "tokenizer": AutoTokenizer,
3021
+ "pipeline": ImageToTextPipeline,
3022
+ "model": AutoModelForVision2Seq,
3023
+ "processor": AutoProcessor,
3024
+ "default": {
3025
+ // TODO: replace with original
3026
+ // "model": "nlpconnect/vit-gpt2-image-captioning",
3027
+ "model": "Xenova/vit-gpt2-image-captioning",
3028
+ },
3029
+ "type": "multimodal",
3030
+ },
3031
+
3032
+ "image-classification": {
3033
+ // no tokenizer
3034
+ "pipeline": ImageClassificationPipeline,
3035
+ "model": AutoModelForImageClassification,
3036
+ "processor": AutoProcessor,
3037
+ "default": {
3038
+ // TODO: replace with original
3039
+ // "model": "google/vit-base-patch16-224",
3040
+ "model": "Xenova/vit-base-patch16-224",
3041
+ },
3042
+ "type": "multimodal",
3043
+ },
3044
+
3045
+ "image-segmentation": {
3046
+ // no tokenizer
3047
+ "pipeline": ImageSegmentationPipeline,
3048
+ "model": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation],
3049
+ "processor": AutoProcessor,
3050
+ "default": {
3051
+ // TODO: replace with original
3052
+ // "model": "facebook/detr-resnet-50-panoptic",
3053
+ "model": "Xenova/detr-resnet-50-panoptic",
3054
+ },
3055
+ "type": "multimodal",
3056
+ },
3057
+
3058
+ "zero-shot-image-classification": {
3059
+ "tokenizer": AutoTokenizer,
3060
+ "pipeline": ZeroShotImageClassificationPipeline,
3061
+ "model": AutoModel,
3062
+ "processor": AutoProcessor,
3063
+ "default": {
3064
+ // TODO: replace with original
3065
+ // "model": "openai/clip-vit-base-patch32",
3066
+ "model": "Xenova/clip-vit-base-patch32",
3067
+ },
3068
+ "type": "multimodal",
3069
+ },
3070
+
3071
+ "object-detection": {
3072
+ // no tokenizer
3073
+ "pipeline": ObjectDetectionPipeline,
3074
+ "model": AutoModelForObjectDetection,
3075
+ "processor": AutoProcessor,
3076
+ "default": {
3077
+ // TODO: replace with original
3078
+ // "model": "facebook/detr-resnet-50",
3079
+ "model": "Xenova/detr-resnet-50",
3080
+ },
3081
+ "type": "multimodal",
3082
+ },
3083
+ "zero-shot-object-detection": {
3084
+ "tokenizer": AutoTokenizer,
3085
+ "pipeline": ZeroShotObjectDetectionPipeline,
3086
+ "model": AutoModelForZeroShotObjectDetection,
3087
+ "processor": AutoProcessor,
3088
+ "default": {
3089
+ // TODO: replace with original
3090
+ // "model": "google/owlvit-base-patch32",
3091
+ "model": "Xenova/owlvit-base-patch32",
3092
+ },
3093
+ "type": "multimodal",
3094
+ },
3095
+ "document-question-answering": {
3096
+ "tokenizer": AutoTokenizer,
3097
+ "pipeline": DocumentQuestionAnsweringPipeline,
3098
+ "model": AutoModelForDocumentQuestionAnswering,
3099
+ "processor": AutoProcessor,
3100
+ "default": {
3101
+ // TODO: replace with original
3102
+ // "model": "naver-clova-ix/donut-base-finetuned-docvqa",
3103
+ "model": "Xenova/donut-base-finetuned-docvqa",
3104
+ },
3105
+ "type": "multimodal",
3106
+ },
3107
+ "image-to-image": {
3108
+ // no tokenizer
3109
+ "pipeline": ImageToImagePipeline,
3110
+ "model": AutoModelForImageToImage,
3111
+ "processor": AutoProcessor,
3112
+ "default": {
3113
+ // TODO: replace with original
3114
+ // "model": "caidas/swin2SR-classical-sr-x2-64",
3115
+ "model": "Xenova/swin2SR-classical-sr-x2-64",
3116
+ },
3117
+ "type": "image",
3118
+ },
3119
+ "depth-estimation": {
3120
+ // no tokenizer
3121
+ "pipeline": DepthEstimationPipeline,
3122
+ "model": AutoModelForDepthEstimation,
3123
+ "processor": AutoProcessor,
3124
+ "default": {
3125
+ // TODO: replace with original
3126
+ // "model": "Intel/dpt-large",
3127
+ "model": "Xenova/dpt-large",
3128
+ },
3129
+ "type": "image",
3130
+ },
3131
+
3132
+ // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).
3133
+ "feature-extraction": {
3134
+ "tokenizer": AutoTokenizer,
3135
+ "pipeline": FeatureExtractionPipeline,
3136
+ "model": AutoModel,
3137
+ "default": {
3138
+ // TODO: replace with original
3139
+ // "model": "sentence-transformers/all-MiniLM-L6-v2",
3140
+ "model": "Xenova/all-MiniLM-L6-v2",
3141
+ },
3142
+ "type": "text",
3143
+ },
3144
+ "image-feature-extraction": {
3145
+ "processor": AutoProcessor,
3146
+ "pipeline": ImageFeatureExtractionPipeline,
3147
+ "model": [AutoModelForImageFeatureExtraction, AutoModel],
3148
+ "default": {
3149
+ // TODO: replace with original
3150
+ // "model": "google/vit-base-patch16-224",
3151
+ "model": "Xenova/vit-base-patch16-224-in21k",
3152
+ },
3153
+ "type": "image",
3154
+ },
3155
+ })
3156
+
3157
+
3158
+ // TODO: Add types for TASK_ALIASES
3159
+ const TASK_ALIASES = Object.freeze({
3160
+ "sentiment-analysis": "text-classification",
3161
+ "ner": "token-classification",
3162
+ // "vqa": "visual-question-answering", // TODO: Add
3163
+ "asr": "automatic-speech-recognition",
3164
+ "text-to-speech": "text-to-audio",
3165
+
3166
+ // Add for backwards compatibility
3167
+ "embeddings": "feature-extraction",
3168
+ });
3169
+
3170
+ /**
3171
+ * @typedef {keyof typeof SUPPORTED_TASKS} TaskType
3172
+ * @typedef {keyof typeof TASK_ALIASES} AliasType
3173
+ * @typedef {TaskType | AliasType} PipelineType All possible pipeline types.
3174
+ * @typedef {{[K in TaskType]: InstanceType<typeof SUPPORTED_TASKS[K]["pipeline"]>}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes.
3175
+ * @typedef {{[K in AliasType]: InstanceType<typeof SUPPORTED_TASKS[TASK_ALIASES[K]]["pipeline"]>}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes.
3176
+ * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes.
3177
+ */
3178
+
3179
+ /**
3180
+ * Utility factory method to build a `Pipeline` object.
3181
+ *
3182
+ * @template {PipelineType} T The type of pipeline to return.
3183
+ * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are:
3184
+ * - `"audio-classification"`: will return a `AudioClassificationPipeline`.
3185
+ * - `"automatic-speech-recognition"`: will return a `AutomaticSpeechRecognitionPipeline`.
3186
+ * - `"depth-estimation"`: will return a `DepthEstimationPipeline`.
3187
+ * - `"document-question-answering"`: will return a `DocumentQuestionAnsweringPipeline`.
3188
+ * - `"feature-extraction"`: will return a `FeatureExtractionPipeline`.
3189
+ * - `"fill-mask"`: will return a `FillMaskPipeline`.
3190
+ * - `"image-classification"`: will return a `ImageClassificationPipeline`.
3191
+ * - `"image-segmentation"`: will return a `ImageSegmentationPipeline`.
3192
+ * - `"image-to-text"`: will return a `ImageToTextPipeline`.
3193
+ * - `"object-detection"`: will return a `ObjectDetectionPipeline`.
3194
+ * - `"question-answering"`: will return a `QuestionAnsweringPipeline`.
3195
+ * - `"summarization"`: will return a `SummarizationPipeline`.
3196
+ * - `"text2text-generation"`: will return a `Text2TextGenerationPipeline`.
3197
+ * - `"text-classification"` (alias "sentiment-analysis" available): will return a `TextClassificationPipeline`.
3198
+ * - `"text-generation"`: will return a `TextGenerationPipeline`.
3199
+ * - `"token-classification"` (alias "ner" available): will return a `TokenClassificationPipeline`.
3200
+ * - `"translation"`: will return a `TranslationPipeline`.
3201
+ * - `"translation_xx_to_yy"`: will return a `TranslationPipeline`.
3202
+ * - `"zero-shot-classification"`: will return a `ZeroShotClassificationPipeline`.
3203
+ * - `"zero-shot-audio-classification"`: will return a `ZeroShotAudioClassificationPipeline`.
3204
+ * - `"zero-shot-image-classification"`: will return a `ZeroShotImageClassificationPipeline`.
3205
+ * - `"zero-shot-object-detection"`: will return a `ZeroShotObjectDetectionPipeline`.
3206
+ * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used.
3207
+ * @param {import('./utils/hub.js').PretrainedModelOptions} [options] Optional parameters for the pipeline.
3208
+ * @returns {Promise<AllTasks[T]>} A Pipeline object for the specified task.
3209
+ * @throws {Error} If an unsupported pipeline is requested.
3210
+ */
3211
+ export async function pipeline(
3212
+ task,
3213
+ model = null,
3214
+ {
3215
+ progress_callback = null,
3216
+ config = null,
3217
+ cache_dir = null,
3218
+ local_files_only = false,
3219
+ revision = 'main',
3220
+ device = null,
3221
+ dtype = null,
3222
+ model_file_name = null,
3223
+ session_options = {},
3224
+ } = {}
3225
+ ) {
3226
+ // Helper method to construct pipeline
3227
+
3228
+ // Apply aliases
3229
+ // @ts-ignore
3230
+ task = TASK_ALIASES[task] ?? task;
3231
+
3232
+ // Get pipeline info
3233
+ const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];
3234
+ if (!pipelineInfo) {
3235
+ throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)
3236
+ }
3237
+
3238
+ // Use model if specified, otherwise, use default
3239
+ if (!model) {
3240
+ model = pipelineInfo.default.model
3241
+ console.log(`No model specified. Using default model: "${model}".`);
3242
+ }
3243
+
3244
+ const pretrainedOptions = {
3245
+ progress_callback,
3246
+ config,
3247
+ cache_dir,
3248
+ local_files_only,
3249
+ revision,
3250
+ device,
3251
+ dtype,
3252
+ model_file_name,
3253
+ session_options,
3254
+ }
3255
+
3256
+ const classes = new Map([
3257
+ ['tokenizer', pipelineInfo.tokenizer],
3258
+ ['model', pipelineInfo.model],
3259
+ ['processor', pipelineInfo.processor],
3260
+ ]);
3261
+
3262
+ // Load model, tokenizer, and processor (if they exist)
3263
+ const results = await loadItems(classes, model, pretrainedOptions);
3264
+ results.task = task;
3265
+
3266
+ dispatchCallback(progress_callback, {
3267
+ 'status': 'ready',
3268
+ 'task': task,
3269
+ 'model': model,
3270
+ });
3271
+
3272
+ const pipelineClass = pipelineInfo.pipeline;
3273
+ return new pipelineClass(results);
3274
+ }
3275
+
3276
+
3277
+ /**
3278
+ * Helper function to get applicable model, tokenizer, or processor classes for a given model.
3279
+ * @param {Map<string, any>} mapping The mapping of names to classes, arrays of classes, or null.
3280
+ * @param {string} model The name of the model to load.
3281
+ * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method.
3282
+ * @private
3283
+ */
3284
+ async function loadItems(mapping, model, pretrainedOptions) {
3285
+
3286
+ const result = Object.create(null);
3287
+
3288
+ /**@type {Promise[]} */
3289
+ const promises = [];
3290
+ for (let [name, cls] of mapping.entries()) {
3291
+ if (!cls) continue;
3292
+
3293
+ /**@type {Promise} */
3294
+ let promise;
3295
+ if (Array.isArray(cls)) {
3296
+ promise = new Promise(async (resolve, reject) => {
3297
+ let e;
3298
+ for (let c of cls) {
3299
+ if (c === null) {
3300
+ // If null, we resolve it immediately, meaning the relevant
3301
+ // class was not found, but it is optional.
3302
+ resolve(null);
3303
+ return;
3304
+ }
3305
+ try {
3306
+ resolve(await c.from_pretrained(model, pretrainedOptions));
3307
+ return;
3308
+ } catch (err) {
3309
+ if (err.message?.includes('Unsupported model type')) {
3310
+ // If the error is due to an unsupported model type, we
3311
+ // save the error and try the next class.
3312
+ e = err;
3313
+ } else if (err.message?.includes('Could not locate file')) {
3314
+ e = err;
3315
+ } else {
3316
+ reject(err);
3317
+ return;
3318
+ }
3319
+
3320
+ }
3321
+ }
3322
+ reject(e);
3323
+ })
3324
+ } else {
3325
+ promise = cls.from_pretrained(model, pretrainedOptions);
3326
+ }
3327
+
3328
+ result[name] = promise;
3329
+ promises.push(promise);
3330
+ }
3331
+
3332
+ // Wait for all promises to resolve (in parallel)
3333
+ await Promise.all(promises);
3334
+
3335
+ // Then assign to result
3336
+ for (let [name, promise] of Object.entries(result)) {
3337
+ result[name] = await promise;
3338
+ }
3339
+
3340
+ return result;
3341
+ }