spec-cat 0.1.0 → 0.1.2

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 (110) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/_nuxt/{Bqlz6CoK.js → BE_75kPa.js} +1 -1
  3. package/.output/public/_nuxt/{B2wdmh_w.js → BJ7m4fRW.js} +53 -53
  4. package/.output/public/_nuxt/{KNuzSjk0.js → CCNYUZ9m.js} +1 -1
  5. package/.output/public/_nuxt/{BvosqTnx.js → DGtcdWVl.js} +1 -1
  6. package/.output/public/_nuxt/DxEx-kFx.js +1 -0
  7. package/.output/public/_nuxt/{BwcbSlWF.js → DyMq_cQC.js} +2 -2
  8. package/.output/public/_nuxt/{COTT6rNZ.js → _cj5lOdZ.js} +1 -1
  9. package/.output/public/_nuxt/builds/latest.json +1 -1
  10. package/.output/public/_nuxt/builds/meta/3a0aacc1-0bd1-4d15-8b8a-3cee48cbfc69.json +1 -0
  11. package/.output/public/_nuxt/{BUOk7wkI.js → gDut6QrP.js} +1 -1
  12. package/.output/public/_nuxt/{C5wk2twv.js → nJpWpjzg.js} +1 -1
  13. package/.output/public/_nuxt/{DBab5Zcv.js → waQ9fPC1.js} +1 -1
  14. package/.output/server/chunks/_/codexProvider.mjs +64 -18
  15. package/.output/server/chunks/_/codexProvider.mjs.map +1 -1
  16. package/.output/server/chunks/build/client.precomputed.mjs +1 -1
  17. package/.output/server/chunks/build/client.precomputed.mjs.map +1 -1
  18. package/.output/server/chunks/nitro/nitro.mjs +702 -703
  19. package/.output/server/chunks/routes/_ws.mjs +37 -7
  20. package/.output/server/chunks/routes/_ws.mjs.map +1 -1
  21. package/.output/server/node_modules/@huggingface/jinja/dist/index.js +1572 -0
  22. package/.output/server/node_modules/@huggingface/jinja/package.json +55 -0
  23. package/.output/server/node_modules/@xenova/transformers/package.json +84 -0
  24. package/.output/server/node_modules/@xenova/transformers/src/backends/onnx.js +50 -0
  25. package/.output/server/node_modules/@xenova/transformers/src/configs.js +107 -0
  26. package/.output/server/node_modules/@xenova/transformers/src/env.js +128 -0
  27. package/.output/server/node_modules/@xenova/transformers/src/models.js +6267 -0
  28. package/.output/server/node_modules/@xenova/transformers/src/pipelines.js +3287 -0
  29. package/.output/server/node_modules/@xenova/transformers/src/processors.js +2248 -0
  30. package/.output/server/node_modules/@xenova/transformers/src/tokenizers.js +4479 -0
  31. package/.output/server/node_modules/@xenova/transformers/src/transformers.js +24 -0
  32. package/.output/server/node_modules/@xenova/transformers/src/utils/audio.js +672 -0
  33. package/.output/server/node_modules/@xenova/transformers/src/utils/core.js +175 -0
  34. package/.output/server/node_modules/@xenova/transformers/src/utils/data-structures.js +415 -0
  35. package/.output/server/node_modules/@xenova/transformers/src/utils/generation.js +873 -0
  36. package/.output/server/node_modules/@xenova/transformers/src/utils/hub.js +658 -0
  37. package/.output/server/node_modules/@xenova/transformers/src/utils/image.js +731 -0
  38. package/.output/server/node_modules/@xenova/transformers/src/utils/maths.js +985 -0
  39. package/.output/server/node_modules/@xenova/transformers/src/utils/tensor.js +1239 -0
  40. package/.output/server/node_modules/color/index.js +496 -0
  41. package/.output/server/node_modules/color/package.json +47 -0
  42. package/.output/server/node_modules/color-convert/conversions.js +839 -0
  43. package/.output/server/node_modules/color-convert/index.js +81 -0
  44. package/.output/server/node_modules/color-convert/package.json +48 -0
  45. package/.output/server/node_modules/color-convert/route.js +97 -0
  46. package/.output/server/node_modules/color-name/index.js +152 -0
  47. package/.output/server/node_modules/color-name/package.json +28 -0
  48. package/.output/server/node_modules/color-string/index.js +242 -0
  49. package/.output/server/node_modules/color-string/package.json +39 -0
  50. package/.output/server/node_modules/detect-libc/lib/detect-libc.js +313 -0
  51. package/.output/server/node_modules/detect-libc/lib/elf.js +39 -0
  52. package/.output/server/node_modules/detect-libc/lib/filesystem.js +51 -0
  53. package/.output/server/node_modules/detect-libc/lib/process.js +24 -0
  54. package/.output/server/node_modules/detect-libc/package.json +44 -0
  55. package/.output/server/node_modules/is-arrayish/index.js +9 -0
  56. package/.output/server/node_modules/is-arrayish/package.json +45 -0
  57. package/.output/server/node_modules/onnxruntime-common/dist/ort-common.node.js +7 -0
  58. package/.output/server/node_modules/onnxruntime-common/package.json +31 -0
  59. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/darwin/arm64/onnxruntime_binding.node +0 -0
  60. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/darwin/x64/onnxruntime_binding.node +0 -0
  61. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/arm64/libonnxruntime.so.1.14.0 +0 -0
  62. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/arm64/onnxruntime_binding.node +0 -0
  63. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/libonnxruntime.so.1.14.0 +0 -0
  64. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/onnxruntime_binding.node +0 -0
  65. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/win32/arm64/onnxruntime_binding.node +0 -0
  66. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/win32/x64/onnxruntime_binding.node +0 -0
  67. package/.output/server/node_modules/onnxruntime-node/dist/backend.js +75 -0
  68. package/.output/server/node_modules/onnxruntime-node/dist/binding.js +10 -0
  69. package/.output/server/node_modules/onnxruntime-node/dist/index.js +23 -0
  70. package/.output/server/node_modules/onnxruntime-node/package.json +58 -0
  71. package/.output/server/node_modules/onnxruntime-web/dist/ort-web.node.js +7 -0
  72. package/.output/server/node_modules/onnxruntime-web/package.json +84 -0
  73. package/.output/server/node_modules/semver/classes/semver.js +333 -0
  74. package/.output/server/node_modules/semver/functions/coerce.js +62 -0
  75. package/.output/server/node_modules/semver/functions/compare.js +7 -0
  76. package/.output/server/node_modules/semver/functions/gte.js +5 -0
  77. package/.output/server/node_modules/semver/functions/parse.js +18 -0
  78. package/.output/server/node_modules/semver/internal/constants.js +37 -0
  79. package/.output/server/node_modules/semver/internal/debug.js +11 -0
  80. package/.output/server/node_modules/semver/internal/identifiers.js +29 -0
  81. package/.output/server/node_modules/semver/internal/parse-options.js +17 -0
  82. package/.output/server/node_modules/semver/internal/re.js +223 -0
  83. package/.output/server/node_modules/semver/package.json +78 -0
  84. package/.output/server/node_modules/sharp/build/Release/sharp-linux-x64.node +0 -0
  85. package/.output/server/node_modules/sharp/lib/channel.js +174 -0
  86. package/.output/server/node_modules/sharp/lib/colour.js +184 -0
  87. package/.output/server/node_modules/sharp/lib/composite.js +210 -0
  88. package/.output/server/node_modules/sharp/lib/constructor.js +439 -0
  89. package/.output/server/node_modules/sharp/lib/index.js +16 -0
  90. package/.output/server/node_modules/sharp/lib/input.js +631 -0
  91. package/.output/server/node_modules/sharp/lib/is.js +155 -0
  92. package/.output/server/node_modules/sharp/lib/libvips.js +140 -0
  93. package/.output/server/node_modules/sharp/lib/operation.js +919 -0
  94. package/.output/server/node_modules/sharp/lib/output.js +1413 -0
  95. package/.output/server/node_modules/sharp/lib/platform.js +30 -0
  96. package/.output/server/node_modules/sharp/lib/resize.js +582 -0
  97. package/.output/server/node_modules/sharp/lib/sharp.js +38 -0
  98. package/.output/server/node_modules/sharp/lib/utility.js +287 -0
  99. package/.output/server/node_modules/sharp/package.json +204 -0
  100. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/THIRD-PARTY-NOTICES.md +43 -0
  101. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/lib/libvips-cpp.so.42 +0 -0
  102. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/platform.json +1 -0
  103. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/versions.json +31 -0
  104. package/.output/server/node_modules/simple-swizzle/index.js +29 -0
  105. package/.output/server/node_modules/simple-swizzle/package.json +36 -0
  106. package/.output/server/package.json +15 -1
  107. package/README.md +2 -0
  108. package/package.json +12 -19
  109. package/.output/public/_nuxt/5FxpIoe_.js +0 -1
  110. package/.output/public/_nuxt/builds/meta/21578a05-1b7e-4847-a8ff-7480800ea4a6.json +0 -1
@@ -0,0 +1,2248 @@
1
+
2
+ /**
3
+ * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model.
4
+ *
5
+ * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model.
6
+ * ```javascript
7
+ * import { AutoProcessor, read_audio } from '@xenova/transformers';
8
+ *
9
+ * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');
10
+ * let audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);
11
+ * let { input_features } = await processor(audio);
12
+ * // Tensor {
13
+ * // data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...],
14
+ * // dims: [1, 80, 3000],
15
+ * // type: 'float32',
16
+ * // size: 240000,
17
+ * // }
18
+ * ```
19
+ *
20
+ * @module processors
21
+ */
22
+ import {
23
+ Callable,
24
+ calculateDimensions,
25
+ calculateReflectOffset,
26
+ } from './utils/core.js';
27
+
28
+ import {
29
+ getModelJSON,
30
+ } from './utils/hub.js';
31
+
32
+ import {
33
+ min,
34
+ max,
35
+ softmax,
36
+ bankers_round,
37
+ } from './utils/maths.js';
38
+
39
+
40
+ import { Tensor, permute, cat, interpolate, stack } from './utils/tensor.js';
41
+
42
+ import { RawImage } from './utils/image.js';
43
+ import {
44
+ window_function,
45
+ spectrogram,
46
+ mel_filter_bank,
47
+ } from './utils/audio.js';
48
+
49
+
50
+ // Helper functions
51
+
52
+ /**
53
+ * Converts bounding boxes from center format to corners format.
54
+ *
55
+ * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)
56
+ * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
57
+ */
58
+ function center_to_corners_format([centerX, centerY, width, height]) {
59
+ return [
60
+ centerX - width / 2,
61
+ centerY - height / 2,
62
+ centerX + width / 2,
63
+ centerY + height / 2
64
+ ];
65
+ }
66
+
67
+ /**
68
+ * Post-processes the outputs of the model (for object detection).
69
+ * @param {Object} outputs The outputs of the model that must be post-processed
70
+ * @param {Tensor} outputs.logits The logits
71
+ * @param {Tensor} outputs.pred_boxes The predicted boxes.
72
+ * @param {number} [threshold=0.5] The threshold to use for the scores.
73
+ * @param {number[][]} [target_sizes=null] The sizes of the original images.
74
+ * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
75
+ * @return {Object[]} An array of objects containing the post-processed outputs.
76
+ * @private
77
+ */
78
+ function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {
79
+ const out_logits = outputs.logits;
80
+ const out_bbox = outputs.pred_boxes;
81
+ const [batch_size, num_boxes, num_classes] = out_logits.dims;
82
+
83
+ if (target_sizes !== null && target_sizes.length !== batch_size) {
84
+ throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
85
+ }
86
+ let toReturn = [];
87
+ for (let i = 0; i < batch_size; ++i) {
88
+ let target_size = target_sizes !== null ? target_sizes[i] : null;
89
+ let info = {
90
+ boxes: [],
91
+ classes: [],
92
+ scores: []
93
+ }
94
+ let logits = out_logits[i];
95
+ let bbox = out_bbox[i];
96
+
97
+ for (let j = 0; j < num_boxes; ++j) {
98
+ let logit = logits[j];
99
+
100
+ let indices = [];
101
+ let probs;
102
+ if (is_zero_shot) {
103
+ // Get indices of classes with high enough probability
104
+ probs = logit.sigmoid().data;
105
+ for (let k = 0; k < probs.length; ++k) {
106
+ if (probs[k] > threshold) {
107
+ indices.push(k);
108
+ }
109
+ }
110
+
111
+ } else {
112
+ // Get most probable class
113
+ let maxIndex = max(logit.data)[1];
114
+
115
+ if (maxIndex === num_classes - 1) {
116
+ // This is the background class, skip it
117
+ continue;
118
+ }
119
+ indices.push(maxIndex);
120
+
121
+ // Compute softmax over classes
122
+ probs = softmax(logit.data);
123
+ }
124
+
125
+ for (const index of indices) {
126
+
127
+ // Some class has a high enough probability
128
+ /** @type {number[]} */
129
+ let box = bbox[j].data;
130
+
131
+ // convert to [x0, y0, x1, y1] format
132
+ box = center_to_corners_format(box)
133
+ if (target_size !== null) {
134
+ box = box.map((x, i) => x * target_size[(i + 1) % 2])
135
+ }
136
+
137
+ info.boxes.push(box);
138
+ info.classes.push(index);
139
+ info.scores.push(probs[index]);
140
+ }
141
+ }
142
+ toReturn.push(info);
143
+ }
144
+ return toReturn;
145
+ }
146
+
147
+ /**
148
+ * Named tuple to indicate the order we are using is (height x width), even though
149
+ * the Graphics’ industry standard is (width x height).
150
+ * @typedef {[height: number, width: number]} HeightWidth
151
+ */
152
+
153
+ /**
154
+ * Helper function to validate audio inputs.
155
+ * @param {any} audio The audio data.
156
+ * @param {string} feature_extractor The name of the feature extractor.
157
+ * @private
158
+ */
159
+ function validate_audio_inputs(audio, feature_extractor) {
160
+ if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {
161
+ throw new Error(
162
+ `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. ` +
163
+ `If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`
164
+ )
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Helper function to constrain a value to be a multiple of a number.
170
+ * @param {number} val The value to constrain.
171
+ * @param {number} multiple The number to constrain to.
172
+ * @param {number} [minVal=0] The minimum value to constrain to.
173
+ * @param {number} [maxVal=null] The maximum value to constrain to.
174
+ * @returns {number} The constrained value.
175
+ * @private
176
+ */
177
+ function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {
178
+ const a = val / multiple;
179
+ let x = bankers_round(a) * multiple;
180
+
181
+ if (maxVal !== null && x > maxVal) {
182
+ x = Math.floor(a) * multiple;
183
+ }
184
+
185
+ if (x < minVal) {
186
+ x = Math.ceil(a) * multiple;
187
+ }
188
+
189
+ return x;
190
+ }
191
+
192
+ /**
193
+ * Rounds the height and width down to the closest multiple of size_divisibility
194
+ * @param {[number, number]} size The size of the image
195
+ * @param {number} divisor The divisor to use.
196
+ * @returns {[number, number]} The rounded size.
197
+ */
198
+ function enforce_size_divisibility([width, height], divisor) {
199
+ return [
200
+ Math.max(Math.floor(width / divisor), 1) * divisor,
201
+ Math.max(Math.floor(height / divisor), 1) * divisor
202
+ ];
203
+ }
204
+
205
+
206
+ /**
207
+ * Base class for feature extractors.
208
+ *
209
+ * @extends Callable
210
+ */
211
+ export class FeatureExtractor extends Callable {
212
+ /**
213
+ * Constructs a new FeatureExtractor instance.
214
+ *
215
+ * @param {Object} config The configuration for the feature extractor.
216
+ */
217
+ constructor(config) {
218
+ super();
219
+ this.config = config
220
+ }
221
+ }
222
+
223
+ /**
224
+ * @typedef {object} ImageFeatureExtractorResult
225
+ * @property {Tensor} pixel_values The pixel values of the batched preprocessed images.
226
+ * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]].
227
+ * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]].
228
+ */
229
+
230
+ /**
231
+ * Feature extractor for image models.
232
+ *
233
+ * @extends FeatureExtractor
234
+ */
235
+ export class ImageFeatureExtractor extends FeatureExtractor {
236
+
237
+ /**
238
+ * Constructs a new ImageFeatureExtractor instance.
239
+ *
240
+ * @param {Object} config The configuration for the feature extractor.
241
+ * @param {number[]} config.image_mean The mean values for image normalization.
242
+ * @param {number[]} config.image_std The standard deviation values for image normalization.
243
+ * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.
244
+ * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.
245
+ * @param {boolean} config.do_normalize Whether to normalize the image pixel values.
246
+ * @param {boolean} config.do_resize Whether to resize the image.
247
+ * @param {number} config.resample What method to use for resampling.
248
+ * @param {number|Object} config.size The size to resize the image to.
249
+ * @param {boolean} [config.do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR.
250
+ * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method.
251
+ */
252
+ constructor(config) {
253
+ super(config);
254
+
255
+ this.image_mean = this.config.image_mean ?? this.config.mean;
256
+ this.image_std = this.config.image_std ?? this.config.std;
257
+
258
+ this.resample = this.config.resample ?? 2; // 2 => bilinear
259
+ this.do_rescale = this.config.do_rescale ?? true;
260
+ this.rescale_factor = this.config.rescale_factor ?? (1 / 255);
261
+ this.do_normalize = this.config.do_normalize;
262
+
263
+ this.do_resize = this.config.do_resize;
264
+ this.do_thumbnail = this.config.do_thumbnail;
265
+ this.size = this.config.size;
266
+ this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor;
267
+
268
+ this.do_center_crop = this.config.do_center_crop;
269
+ this.crop_size = this.config.crop_size;
270
+ this.do_convert_rgb = this.config.do_convert_rgb ?? true;
271
+ this.do_crop_margin = this.config.do_crop_margin;
272
+
273
+ this.pad_size = this.config.pad_size;
274
+ this.do_pad = this.config.do_pad;
275
+
276
+ if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {
277
+ // Should pad, but no pad size specified
278
+ // We infer the pad size from the resize size
279
+ this.pad_size = this.size
280
+ }
281
+
282
+ this.do_flip_channel_order = this.config.do_flip_channel_order ?? false;
283
+ }
284
+
285
+ /**
286
+ * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
287
+ * corresponding dimension of the specified size.
288
+ * @param {RawImage} image The image to be resized.
289
+ * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
290
+ * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
291
+ * @returns {Promise<RawImage>} The resized image.
292
+ */
293
+ async thumbnail(image, size, resample = 2) {
294
+ const input_height = image.height;
295
+ const input_width = image.width;
296
+
297
+ const output_height = size.height;
298
+ const output_width = size.width;
299
+
300
+ // We always resize to the smallest of either the input or output size.
301
+ let height = Math.min(input_height, output_height)
302
+ let width = Math.min(input_width, output_width)
303
+
304
+ if (height === input_height && width === input_width) {
305
+ return image;
306
+ }
307
+ if (input_height > input_width) {
308
+ width = Math.floor(input_width * height / input_height);
309
+ } else if (input_width > input_height) {
310
+ height = Math.floor(input_height * width / input_width);
311
+ }
312
+ return await image.resize(width, height, { resample });
313
+ }
314
+
315
+
316
+ /**
317
+ * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
318
+ * @param {RawImage} image The image to be cropped.
319
+ * @param {number} gray_threshold Value below which pixels are considered to be gray.
320
+ * @returns {Promise<RawImage>} The cropped image.
321
+ */
322
+ async crop_margin(image, gray_threshold = 200) {
323
+
324
+ const gray_image = image.clone().grayscale();
325
+
326
+ const minValue = min(gray_image.data)[0];
327
+ const maxValue = max(gray_image.data)[0];
328
+ const diff = maxValue - minValue;
329
+
330
+ if (diff === 0) {
331
+ return image;
332
+ }
333
+
334
+ const threshold = gray_threshold / 255;
335
+
336
+ let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;
337
+ for (let j = 0; j < gray_image.height; ++j) {
338
+ const row = j * gray_image.width;
339
+ for (let i = 0; i < gray_image.width; ++i) {
340
+ if ((gray_image.data[row + i] - minValue) / diff < threshold) {
341
+ // We have a non-zero pixel, so we update the min/max values accordingly
342
+ x_min = Math.min(x_min, i);
343
+ y_min = Math.min(y_min, j);
344
+ x_max = Math.max(x_max, i);
345
+ y_max = Math.max(y_max, j);
346
+ }
347
+ }
348
+ }
349
+
350
+ image = await image.crop([x_min, y_min, x_max, y_max]);
351
+ return image;
352
+ }
353
+
354
+ /**
355
+ * Pad the image by a certain amount.
356
+ * @param {Float32Array} pixelData The pixel data to pad.
357
+ * @param {number[]} imgDims The dimensions of the image (height, width, channels).
358
+ * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.
359
+ * @param {Object} options The options for padding.
360
+ * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
361
+ * @param {boolean} [options.center=false] Whether to center the image.
362
+ * @param {number} [options.constant_values=0] The constant value to use for padding.
363
+ * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
364
+ */
365
+ pad_image(pixelData, imgDims, padSize, {
366
+ mode = 'constant',
367
+ center = false,
368
+ constant_values = 0,
369
+ } = {}) {
370
+ const [imageHeight, imageWidth, imageChannels] = imgDims;
371
+
372
+ let paddedImageWidth, paddedImageHeight;
373
+ if (typeof padSize === 'number') {
374
+ paddedImageWidth = padSize;
375
+ paddedImageHeight = padSize;
376
+ } else {
377
+ paddedImageWidth = padSize.width;
378
+ paddedImageHeight = padSize.height;
379
+ }
380
+
381
+ // Only add padding if there is a difference in size
382
+ if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {
383
+ const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);
384
+ if (Array.isArray(constant_values)) {
385
+ // Fill with constant values, cycling through the array
386
+ for (let i = 0; i < paddedPixelData.length; ++i) {
387
+ paddedPixelData[i] = constant_values[i % imageChannels];
388
+ }
389
+ } else if (constant_values !== 0) {
390
+ paddedPixelData.fill(constant_values);
391
+ }
392
+
393
+ const [left, top] = center
394
+ ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]
395
+ : [0, 0];
396
+
397
+ // Copy the original image into the padded image
398
+ for (let i = 0; i < imageHeight; ++i) {
399
+ const a = (i + top) * paddedImageWidth;
400
+ const b = i * imageWidth;
401
+ for (let j = 0; j < imageWidth; ++j) {
402
+ const c = (a + j + left) * imageChannels;
403
+ const d = (b + j) * imageChannels;
404
+ for (let k = 0; k < imageChannels; ++k) {
405
+ paddedPixelData[c + k] = pixelData[d + k];
406
+ }
407
+ }
408
+ }
409
+
410
+ if (mode === 'symmetric') {
411
+ if (center) {
412
+ throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');
413
+ // TODO: Implement this
414
+ }
415
+ const h1 = imageHeight - 1;
416
+ const w1 = imageWidth - 1;
417
+ for (let i = 0; i < paddedImageHeight; ++i) {
418
+ const a = i * paddedImageWidth;
419
+ const b = calculateReflectOffset(i, h1) * imageWidth;
420
+
421
+ for (let j = 0; j < paddedImageWidth; ++j) {
422
+ if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image
423
+ const c = (a + j) * imageChannels;
424
+ const d = (b + calculateReflectOffset(j, w1)) * imageChannels;
425
+
426
+ // Copy channel-wise
427
+ for (let k = 0; k < imageChannels; ++k) {
428
+ paddedPixelData[c + k] = pixelData[d + k];
429
+ }
430
+ }
431
+ }
432
+ }
433
+
434
+
435
+ // Update pixel data and image dimensions
436
+ pixelData = paddedPixelData;
437
+ imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]
438
+ }
439
+ return [pixelData, imgDims];
440
+ }
441
+
442
+ /**
443
+ * Rescale the image' pixel values by `this.rescale_factor`.
444
+ * @param {Float32Array} pixelData The pixel data to rescale.
445
+ * @returns {void}
446
+ */
447
+ rescale(pixelData) {
448
+ for (let i = 0; i < pixelData.length; ++i) {
449
+ pixelData[i] = this.rescale_factor * pixelData[i];
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Find the target (width, height) dimension of the output image after
455
+ * resizing given the input image and the desired size.
456
+ * @param {RawImage} image The image to resize.
457
+ * @param {any} size The size to use for resizing the image.
458
+ * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
459
+ */
460
+ get_resize_output_image_size(image, size) {
461
+ // `size` comes in many forms, so we need to handle them all here:
462
+ // 1. `size` is an integer, in which case we resize the image to be a square
463
+
464
+ const [srcWidth, srcHeight] = image.size;
465
+
466
+ let shortest_edge;
467
+ let longest_edge;
468
+
469
+ if (this.do_thumbnail) {
470
+ // NOTE: custom logic for `Donut` models
471
+ const { height, width } = size;
472
+ shortest_edge = Math.min(height, width)
473
+ }
474
+ // Support both formats for backwards compatibility
475
+ else if (Number.isInteger(size)) {
476
+ shortest_edge = size;
477
+ longest_edge = this.config.max_size ?? shortest_edge;
478
+
479
+ } else if (size !== undefined) {
480
+ // Extract known properties from `size`
481
+ shortest_edge = size.shortest_edge;
482
+ longest_edge = size.longest_edge;
483
+ }
484
+
485
+ // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`
486
+ // while keeping the largest dimension <= `longest_edge`
487
+ if (shortest_edge !== undefined || longest_edge !== undefined) {
488
+ // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/
489
+ // Try resize so that shortest edge is `shortest_edge` (target)
490
+ const shortResizeFactor = shortest_edge === undefined
491
+ ? 1 // If `shortest_edge` is not set, don't upscale
492
+ : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);
493
+
494
+ const newWidth = srcWidth * shortResizeFactor;
495
+ const newHeight = srcHeight * shortResizeFactor;
496
+
497
+ // The new width and height might be greater than `longest_edge`, so
498
+ // we downscale again to ensure the largest dimension is `longest_edge`
499
+ const longResizeFactor = longest_edge === undefined
500
+ ? 1 // If `longest_edge` is not set, don't downscale
501
+ : Math.min(longest_edge / newWidth, longest_edge / newHeight);
502
+
503
+ // To avoid certain floating point precision issues, we round to 2 decimal places
504
+ let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));
505
+ let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));
506
+
507
+ if (this.size_divisibility !== undefined) {
508
+ [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility)
509
+ }
510
+ return [finalWidth, finalHeight];
511
+
512
+ } else if (size !== undefined && size.width !== undefined && size.height !== undefined) {
513
+ // If `width` and `height` are set, resize to those dimensions
514
+
515
+ let newWidth = size.width;
516
+ let newHeight = size.height;
517
+
518
+ // Custom for DPT models
519
+ if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {
520
+
521
+ // determine new height and width
522
+ let scale_height = newHeight / srcHeight;
523
+ let scale_width = newWidth / srcWidth;
524
+
525
+ // scale as little as possible
526
+ if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {
527
+ // fit width
528
+ scale_height = scale_width;
529
+ } else {
530
+ // fit height
531
+ scale_width = scale_height;
532
+ }
533
+
534
+ newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);
535
+ newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);
536
+ }
537
+
538
+ return [newWidth, newHeight];
539
+
540
+ } else if (this.size_divisibility !== undefined) {
541
+ return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);
542
+ } else {
543
+ throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`);
544
+ }
545
+ }
546
+
547
+ /**
548
+ * Resizes the image.
549
+ * @param {RawImage} image The image to resize.
550
+ * @returns {Promise<RawImage>} The resized image.
551
+ */
552
+ async resize(image) {
553
+ const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);
554
+ return await image.resize(newWidth, newHeight, {
555
+ resample: this.resample,
556
+ });
557
+ }
558
+
559
+ /**
560
+ * @typedef {object} PreprocessedImage
561
+ * @property {HeightWidth} original_size The original size of the image.
562
+ * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
563
+ * @property {Tensor} pixel_values The pixel values of the preprocessed image.
564
+ */
565
+
566
+ /**
567
+ * Preprocesses the given image.
568
+ *
569
+ * @param {RawImage} image The image to preprocess.
570
+ * @param {Object} overrides The overrides for the preprocessing options.
571
+ * @returns {Promise<PreprocessedImage>} The preprocessed image.
572
+ */
573
+ async preprocess(image, {
574
+ do_normalize = null,
575
+ do_pad = null,
576
+ do_convert_rgb = null,
577
+ do_convert_grayscale = null,
578
+ do_flip_channel_order = null,
579
+ } = {}) {
580
+ if (this.do_crop_margin) {
581
+ // NOTE: Specific to nougat processors. This is done before resizing,
582
+ // and can be interpreted as a pre-preprocessing step.
583
+ image = await this.crop_margin(image);
584
+ }
585
+
586
+ const [srcWidth, srcHeight] = image.size; // original image size
587
+
588
+ // Convert image to RGB if specified in config.
589
+ if (do_convert_rgb ?? this.do_convert_rgb) {
590
+ image = image.rgb();
591
+ } else if (do_convert_grayscale) {
592
+ image = image.grayscale();
593
+ }
594
+
595
+ // TODO:
596
+ // For efficiency reasons, it might be best to merge the resize and center crop operations into one.
597
+
598
+ // Resize all images
599
+ if (this.do_resize) {
600
+ image = await this.resize(image);
601
+ }
602
+
603
+ // Resize the image using thumbnail method.
604
+ if (this.do_thumbnail) {
605
+ image = await this.thumbnail(image, this.size, this.resample);
606
+ }
607
+
608
+ if (this.do_center_crop) {
609
+
610
+ let crop_width;
611
+ let crop_height;
612
+ if (Number.isInteger(this.crop_size)) {
613
+ crop_width = this.crop_size;
614
+ crop_height = this.crop_size;
615
+ } else {
616
+ crop_width = this.crop_size.width;
617
+ crop_height = this.crop_size.height;
618
+ }
619
+
620
+ image = await image.center_crop(crop_width, crop_height);
621
+ }
622
+
623
+ /** @type {HeightWidth} */
624
+ const reshaped_input_size = [image.height, image.width];
625
+
626
+ // NOTE: All pixel-level manipulation (i.e., modifying `pixelData`)
627
+ // occurs with data in the hwc format (height, width, channels),
628
+ // to emulate the behavior of the original Python code (w/ numpy).
629
+ let pixelData = Float32Array.from(image.data);
630
+ let imgDims = [image.height, image.width, image.channels];
631
+
632
+ if (this.do_rescale) {
633
+ this.rescale(pixelData);
634
+ }
635
+
636
+ if (do_normalize ?? this.do_normalize) {
637
+ let image_mean = this.image_mean;
638
+ if (!Array.isArray(this.image_mean)) {
639
+ image_mean = new Array(image.channels).fill(image_mean);
640
+ }
641
+
642
+ let image_std = this.image_std;
643
+ if (!Array.isArray(this.image_std)) {
644
+ image_std = new Array(image.channels).fill(image_mean);
645
+ }
646
+
647
+ if (image_mean.length !== image.channels || image_std.length !== image.channels) {
648
+ throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);
649
+ }
650
+
651
+ for (let i = 0; i < pixelData.length; i += image.channels) {
652
+ for (let j = 0; j < image.channels; ++j) {
653
+ pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];
654
+ }
655
+ }
656
+ }
657
+
658
+ // do padding after rescaling/normalizing
659
+ if (do_pad ?? this.do_pad) {
660
+ if (this.pad_size) {
661
+ const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);
662
+ [pixelData, imgDims] = padded; // Update pixel data and image dimensions
663
+ } else if (this.size_divisibility) {
664
+ const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);
665
+ [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });
666
+ }
667
+ }
668
+
669
+ if (do_flip_channel_order ?? this.do_flip_channel_order) {
670
+ if (imgDims[2] !== 3) {
671
+ throw new Error('Flipping channel order is only supported for RGB images.');
672
+ }
673
+ // Convert RGB to BGR
674
+ for (let i = 0; i < pixelData.length; i += 3) {
675
+ const temp = pixelData[i];
676
+ pixelData[i] = pixelData[i + 2];
677
+ pixelData[i + 2] = temp;
678
+ }
679
+ }
680
+
681
+ const pixel_values = new Tensor('float32', pixelData, imgDims)
682
+ .permute(2, 0, 1); // convert to channel dimension format (hwc -> chw)
683
+
684
+ return {
685
+ original_size: [srcHeight, srcWidth],
686
+ reshaped_input_size: reshaped_input_size,
687
+ pixel_values: pixel_values,
688
+ }
689
+ }
690
+
691
+ /**
692
+ * Calls the feature extraction process on an array of images,
693
+ * preprocesses each image, and concatenates the resulting
694
+ * features into a single Tensor.
695
+ * @param {RawImage[]} images The image(s) to extract features from.
696
+ * @param {...any} args Additional arguments.
697
+ * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
698
+ */
699
+ async _call(images, ...args) {
700
+ if (!Array.isArray(images)) {
701
+ images = [images];
702
+ }
703
+ /** @type {PreprocessedImage[]} */
704
+ const imageData = await Promise.all(images.map(x => this.preprocess(x)));
705
+
706
+ // Stack pixel values
707
+ const pixel_values = stack(imageData.map(x => x.pixel_values), 0);
708
+
709
+ return {
710
+ pixel_values: pixel_values,
711
+
712
+ // Original sizes of images
713
+ original_sizes: imageData.map(x => x.original_size),
714
+
715
+ // Reshaped sizes of images, before padding or cropping
716
+ reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),
717
+ }
718
+ }
719
+
720
+ }
721
+
722
+ export class SegformerFeatureExtractor extends ImageFeatureExtractor {
723
+
724
+ /**
725
+ * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps.
726
+ * @param {*} outputs Raw outputs of the model.
727
+ * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size
728
+ * (height, width) of each prediction. If unset, predictions will not be resized.
729
+ * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.
730
+ */
731
+ post_process_semantic_segmentation(outputs, target_sizes = null) {
732
+
733
+ const logits = outputs.logits;
734
+ const batch_size = logits.dims[0];
735
+
736
+ if (target_sizes !== null && target_sizes.length !== batch_size) {
737
+ throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
738
+ }
739
+
740
+ const toReturn = [];
741
+ for (let i = 0; i < batch_size; ++i) {
742
+ const target_size = target_sizes !== null ? target_sizes[i] : null;
743
+
744
+ let data = logits[i];
745
+
746
+ // 1. If target_size is not null, we need to resize the masks to the target size
747
+ if (target_size !== null) {
748
+ // resize the masks to the target size
749
+ data = interpolate(data, target_size, 'bilinear', false);
750
+ }
751
+ const [height, width] = target_size ?? data.dims.slice(-2);
752
+
753
+ const segmentation = new Tensor(
754
+ 'int32',
755
+ new Int32Array(height * width),
756
+ [height, width]
757
+ );
758
+
759
+ // Buffer to store current largest value
760
+ const buffer = data[0].data;
761
+ for (let j = 1; j < data.dims[0]; ++j) {
762
+ const row = data[j].data;
763
+ for (let k = 0; k < row.length; ++k) {
764
+ if (row[k] > buffer[k]) {
765
+ buffer[k] = row[k];
766
+ segmentation.data[k] = j;
767
+ }
768
+ }
769
+ }
770
+
771
+ // Store which objects have labels
772
+ // This is much more efficient that creating a set of the final values
773
+ const hasLabel = new Array(data.dims[0]);
774
+ const out = segmentation.data;
775
+ for (let j = 0; j < out.length; ++j) {
776
+ const index = out[j];
777
+ hasLabel[index] = index;
778
+ }
779
+ /** @type {number[]} The unique list of labels that were detected */
780
+ const labels = hasLabel.filter(x => x !== undefined);
781
+
782
+ toReturn.push({ segmentation, labels });
783
+ }
784
+ return toReturn;
785
+ }
786
+ }
787
+ export class DPTFeatureExtractor extends ImageFeatureExtractor { }
788
+ export class DPTImageProcessor extends DPTFeatureExtractor { } // NOTE: extends DPTFeatureExtractor
789
+ export class BitImageProcessor extends ImageFeatureExtractor { }
790
+ export class GLPNFeatureExtractor extends ImageFeatureExtractor { }
791
+ export class CLIPFeatureExtractor extends ImageFeatureExtractor { }
792
+ export class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { }
793
+ export class SiglipImageProcessor extends ImageFeatureExtractor { }
794
+ export class ConvNextFeatureExtractor extends ImageFeatureExtractor {
795
+ constructor(config) {
796
+ super(config);
797
+
798
+ /**
799
+ * Percentage of the image to crop. Only has an effect if this.size < 384.
800
+ */
801
+ this.crop_pct = this.config.crop_pct ?? (224 / 256);
802
+ }
803
+
804
+ async resize(image) {
805
+ const shortest_edge = this.size?.shortest_edge;
806
+ if (shortest_edge === undefined) {
807
+ throw new Error(`Size dictionary must contain 'shortest_edge' key.`);
808
+ }
809
+
810
+ if (shortest_edge < 384) {
811
+ // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
812
+ const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);
813
+
814
+ const [newWidth, newHeight] = this.get_resize_output_image_size(image, {
815
+ shortest_edge: resize_shortest_edge,
816
+ });
817
+
818
+ image = await image.resize(newWidth, newHeight, {
819
+ resample: this.resample,
820
+ });
821
+
822
+ // then crop to (shortest_edge, shortest_edge)
823
+ image = await image.center_crop(shortest_edge, shortest_edge);
824
+ } else {
825
+ // warping (no cropping) when evaluated at 384 or larger
826
+ image = await image.resize(shortest_edge, shortest_edge, {
827
+ resample: this.resample,
828
+ });
829
+ }
830
+
831
+ return image;
832
+ }
833
+ }
834
+ export class ConvNextImageProcessor extends ConvNextFeatureExtractor { } // NOTE extends ConvNextFeatureExtractor
835
+ export class ViTFeatureExtractor extends ImageFeatureExtractor { }
836
+ export class ViTImageProcessor extends ImageFeatureExtractor { }
837
+
838
+ export class EfficientNetImageProcessor extends ImageFeatureExtractor {
839
+ constructor(config) {
840
+ super(config);
841
+ this.include_top = this.config.include_top ?? true;
842
+ if (this.include_top) {
843
+ this.image_std = this.image_std.map(x => x * x);
844
+ }
845
+ }
846
+ }
847
+
848
+
849
+ export class MobileViTFeatureExtractor extends ImageFeatureExtractor { }
850
+ export class MobileViTImageProcessor extends MobileViTFeatureExtractor { } // NOTE extends MobileViTFeatureExtractor
851
+ export class OwlViTFeatureExtractor extends ImageFeatureExtractor {
852
+ /** @type {post_process_object_detection} */
853
+ post_process_object_detection(...args) {
854
+ return post_process_object_detection(...args);
855
+ }
856
+ }
857
+ export class Owlv2ImageProcessor extends OwlViTFeatureExtractor { } // NOTE extends OwlViTFeatureExtractor
858
+
859
+ export class DeiTFeatureExtractor extends ImageFeatureExtractor { }
860
+ export class BeitFeatureExtractor extends ImageFeatureExtractor { }
861
+ export class DonutFeatureExtractor extends ImageFeatureExtractor {
862
+ pad_image(pixelData, imgDims, padSize, options = {}) {
863
+ const [imageHeight, imageWidth, imageChannels] = imgDims;
864
+
865
+ let image_mean = this.image_mean;
866
+ if (!Array.isArray(this.image_mean)) {
867
+ image_mean = new Array(imageChannels).fill(image_mean);
868
+ }
869
+
870
+ let image_std = this.image_std;
871
+ if (!Array.isArray(image_std)) {
872
+ image_std = new Array(imageChannels).fill(image_mean);
873
+ }
874
+
875
+ const constant_values = image_mean.map((x, i) => - x / image_std[i]);
876
+
877
+ return super.pad_image(pixelData, imgDims, padSize, {
878
+ center: true,
879
+
880
+ // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.
881
+ // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451
882
+ constant_values: constant_values,
883
+ ...options,
884
+ });
885
+ }
886
+ }
887
+ export class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor
888
+
889
+ /**
890
+ * @typedef {object} DetrFeatureExtractorResultProps
891
+ * @property {Tensor} pixel_mask
892
+ * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult
893
+ */
894
+
895
+ /**
896
+ * Detr Feature Extractor.
897
+ *
898
+ * @extends ImageFeatureExtractor
899
+ */
900
+ export class DetrFeatureExtractor extends ImageFeatureExtractor {
901
+ /**
902
+ * Calls the feature extraction process on an array of images, preprocesses
903
+ * each image, and concatenates the resulting features into a single Tensor.
904
+ * @param {RawImage[]} images The image(s) to extract features from.
905
+ * @returns {Promise<DetrFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
906
+ */
907
+ async _call(images) {
908
+ const result = await super._call(images);
909
+
910
+ // TODO support differently-sized images, for now assume all images are the same size.
911
+ // TODO support different mask sizes (not just 64x64)
912
+ // Currently, just fill pixel mask with 1s
913
+ const maskSize = [result.pixel_values.dims[0], 64, 64];
914
+ const pixel_mask = new Tensor(
915
+ 'int64',
916
+ new BigInt64Array(maskSize.reduce((a, b) => a * b)).fill(1n),
917
+ maskSize
918
+ );
919
+
920
+ return { ...result, pixel_mask };
921
+ }
922
+
923
+ /**
924
+ * Post-processes the outputs of the model (for object detection).
925
+ * @param {Object} outputs The outputs of the model that must be post-processed
926
+ * @param {Tensor} outputs.logits The logits
927
+ * @param {Tensor} outputs.pred_boxes The predicted boxes.
928
+ * @return {Object[]} An array of objects containing the post-processed outputs.
929
+ */
930
+
931
+ /** @type {post_process_object_detection} */
932
+ post_process_object_detection(...args) {
933
+ return post_process_object_detection(...args);
934
+ }
935
+
936
+ /**
937
+ * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.
938
+ * @param {Tensor} class_logits The class logits.
939
+ * @param {Tensor} mask_logits The mask logits.
940
+ * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.
941
+ * @param {number} num_labels The number of labels.
942
+ * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.
943
+ */
944
+ remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {
945
+
946
+ let mask_probs_item = [];
947
+ let pred_scores_item = [];
948
+ let pred_labels_item = [];
949
+
950
+ for (let j = 0; j < class_logits.dims[0]; ++j) {
951
+ let cls = class_logits[j];
952
+ let mask = mask_logits[j];
953
+
954
+ let pred_label = max(cls.data)[1];
955
+ if (pred_label === num_labels) {
956
+ // Is the background, so we ignore it
957
+ continue;
958
+ }
959
+
960
+ let scores = softmax(cls.data);
961
+ let pred_score = scores[pred_label];
962
+ if (pred_score > object_mask_threshold) {
963
+ mask_probs_item.push(mask);
964
+ pred_scores_item.push(pred_score);
965
+ pred_labels_item.push(pred_label);
966
+ }
967
+ }
968
+
969
+ return [mask_probs_item, pred_scores_item, pred_labels_item];
970
+
971
+ }
972
+
973
+ /**
974
+ * Checks whether the segment is valid or not.
975
+ * @param {Int32Array} mask_labels Labels for each pixel in the mask.
976
+ * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.
977
+ * @param {number} k The class id of the segment.
978
+ * @param {number} mask_threshold The mask threshold.
979
+ * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
980
+ * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.
981
+ */
982
+ check_segment_validity(
983
+ mask_labels,
984
+ mask_probs,
985
+ k,
986
+ mask_threshold = 0.5,
987
+ overlap_mask_area_threshold = 0.8
988
+ ) {
989
+ // mask_k is a 1D array of indices, indicating where the mask is equal to k
990
+ let mask_k = [];
991
+ let mask_k_area = 0;
992
+ let original_area = 0;
993
+
994
+ // Compute the area of all the stuff in query k
995
+ for (let i = 0; i < mask_labels.length; ++i) {
996
+ if (mask_labels[i] === k) {
997
+ mask_k.push(i);
998
+ ++mask_k_area;
999
+ }
1000
+
1001
+ if (mask_probs[k].data[i] >= mask_threshold) {
1002
+ ++original_area;
1003
+ }
1004
+ }
1005
+ let mask_exists = mask_k_area > 0 && original_area > 0;
1006
+
1007
+ // Eliminate disconnected tiny segments
1008
+ if (mask_exists) {
1009
+ // Perform additional check
1010
+ let area_ratio = mask_k_area / original_area;
1011
+ mask_exists = area_ratio > overlap_mask_area_threshold;
1012
+ }
1013
+
1014
+ return [mask_exists, mask_k]
1015
+ }
1016
+
1017
+ /**
1018
+ * Computes the segments.
1019
+ * @param {Tensor[]} mask_probs The mask probabilities.
1020
+ * @param {number[]} pred_scores The predicted scores.
1021
+ * @param {number[]} pred_labels The predicted labels.
1022
+ * @param {number} mask_threshold The mask threshold.
1023
+ * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
1024
+ * @param {Set<number>} label_ids_to_fuse The label ids to fuse.
1025
+ * @param {number[]} target_size The target size of the image.
1026
+ * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.
1027
+ */
1028
+ compute_segments(
1029
+ mask_probs,
1030
+ pred_scores,
1031
+ pred_labels,
1032
+ mask_threshold,
1033
+ overlap_mask_area_threshold,
1034
+ label_ids_to_fuse = null,
1035
+ target_size = null,
1036
+ ) {
1037
+ let [height, width] = target_size ?? mask_probs[0].dims;
1038
+
1039
+ let segmentation = new Tensor(
1040
+ 'int32',
1041
+ new Int32Array(height * width),
1042
+ [height, width]
1043
+ );
1044
+ let segments = [];
1045
+
1046
+ // 1. If target_size is not null, we need to resize the masks to the target size
1047
+ if (target_size !== null) {
1048
+ // resize the masks to the target size
1049
+ for (let i = 0; i < mask_probs.length; ++i) {
1050
+ mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false);
1051
+ }
1052
+ }
1053
+
1054
+ // 2. Weigh each mask by its prediction score
1055
+ // NOTE: `mask_probs` is updated in-place
1056
+ //
1057
+ // Temporary storage for the best label/scores for each pixel ([height, width]):
1058
+ let mask_labels = new Int32Array(mask_probs[0].data.length);
1059
+ let bestScores = new Float32Array(mask_probs[0].data.length);
1060
+
1061
+ for (let i = 0; i < mask_probs.length; ++i) {
1062
+ let score = pred_scores[i];
1063
+
1064
+ for (let j = 0; j < mask_probs[i].data.length; ++j) {
1065
+ mask_probs[i].data[j] *= score
1066
+ if (mask_probs[i].data[j] > bestScores[j]) {
1067
+ mask_labels[j] = i;
1068
+ bestScores[j] = mask_probs[i].data[j];
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ let current_segment_id = 0;
1074
+
1075
+ // let stuff_memory_list = {}
1076
+ for (let k = 0; k < pred_labels.length; ++k) {
1077
+ let pred_class = pred_labels[k];
1078
+
1079
+ // TODO add `should_fuse`
1080
+ // let should_fuse = pred_class in label_ids_to_fuse
1081
+
1082
+ // Check if mask exists and large enough to be a segment
1083
+ let [mask_exists, mask_k] = this.check_segment_validity(
1084
+ mask_labels,
1085
+ mask_probs,
1086
+ k,
1087
+ mask_threshold,
1088
+ overlap_mask_area_threshold
1089
+ )
1090
+
1091
+ if (!mask_exists) {
1092
+ // Nothing to see here
1093
+ continue;
1094
+ }
1095
+
1096
+ // TODO
1097
+ // if (pred_class in stuff_memory_list) {
1098
+ // current_segment_id = stuff_memory_list[pred_class]
1099
+ // } else {
1100
+ // current_segment_id += 1;
1101
+ // }
1102
+ ++current_segment_id;
1103
+
1104
+
1105
+ // Add current object segment to final segmentation map
1106
+ for (let index of mask_k) {
1107
+ segmentation.data[index] = current_segment_id;
1108
+ }
1109
+
1110
+ segments.push({
1111
+ id: current_segment_id,
1112
+ label_id: pred_class,
1113
+ // was_fused: should_fuse, TODO
1114
+ score: pred_scores[k],
1115
+ })
1116
+
1117
+ // TODO
1118
+ // if(should_fuse){
1119
+ // stuff_memory_list[pred_class] = current_segment_id
1120
+ // }
1121
+ }
1122
+
1123
+ return [segmentation, segments];
1124
+ }
1125
+
1126
+ /**
1127
+ * Post-process the model output to generate the final panoptic segmentation.
1128
+ * @param {*} outputs The model output to post process
1129
+ * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
1130
+ * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
1131
+ * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
1132
+ * @param {Set<number>} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.
1133
+ * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to.
1134
+ * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
1135
+ */
1136
+ post_process_panoptic_segmentation(
1137
+ outputs,
1138
+ threshold = 0.5,
1139
+ mask_threshold = 0.5,
1140
+ overlap_mask_area_threshold = 0.8,
1141
+ label_ids_to_fuse = null,
1142
+ target_sizes = null,
1143
+ ) {
1144
+ if (label_ids_to_fuse === null) {
1145
+ console.warn("`label_ids_to_fuse` unset. No instance will be fused.")
1146
+ label_ids_to_fuse = new Set();
1147
+ }
1148
+
1149
+ const class_queries_logits = outputs.logits; // [batch_size, num_queries, num_classes+1]
1150
+ const masks_queries_logits = outputs.pred_masks; // [batch_size, num_queries, height, width]
1151
+
1152
+ const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width]
1153
+
1154
+ let [batch_size, num_queries, num_labels] = class_queries_logits.dims;
1155
+ num_labels -= 1; // Remove last class (background)
1156
+
1157
+ if (target_sizes !== null && target_sizes.length !== batch_size) {
1158
+ throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
1159
+ }
1160
+
1161
+ let toReturn = [];
1162
+ for (let i = 0; i < batch_size; ++i) {
1163
+ let target_size = target_sizes !== null ? target_sizes[i] : null;
1164
+
1165
+ let class_logits = class_queries_logits[i];
1166
+ let mask_logits = mask_probs[i];
1167
+
1168
+ let [mask_probs_item, pred_scores_item, pred_labels_item] = this.remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);
1169
+
1170
+ if (pred_labels_item.length === 0) {
1171
+ // No mask found
1172
+ let [height, width] = target_size ?? mask_logits.dims.slice(-2);
1173
+
1174
+ let segmentation = new Tensor(
1175
+ 'int32',
1176
+ new Int32Array(height * width).fill(-1),
1177
+ [height, width]
1178
+ )
1179
+ toReturn.push({
1180
+ segmentation: segmentation,
1181
+ segments_info: []
1182
+ });
1183
+ continue;
1184
+ }
1185
+
1186
+
1187
+ // Get segmentation map and segment information of batch item
1188
+ let [segmentation, segments] = this.compute_segments(
1189
+ mask_probs_item,
1190
+ pred_scores_item,
1191
+ pred_labels_item,
1192
+ mask_threshold,
1193
+ overlap_mask_area_threshold,
1194
+ label_ids_to_fuse,
1195
+ target_size,
1196
+ )
1197
+
1198
+ toReturn.push({
1199
+ segmentation: segmentation,
1200
+ segments_info: segments
1201
+ })
1202
+ }
1203
+
1204
+ return toReturn;
1205
+ }
1206
+
1207
+ post_process_instance_segmentation() {
1208
+ // TODO
1209
+ throw Error("Not implemented yet");
1210
+ }
1211
+ }
1212
+
1213
+ export class YolosFeatureExtractor extends ImageFeatureExtractor {
1214
+ /** @type {post_process_object_detection} */
1215
+ post_process_object_detection(...args) {
1216
+ return post_process_object_detection(...args);
1217
+ }
1218
+ }
1219
+
1220
+ /**
1221
+ * @typedef {object} SamImageProcessorResult
1222
+ * @property {Tensor} pixel_values
1223
+ * @property {HeightWidth[]} original_sizes
1224
+ * @property {HeightWidth[]} reshaped_input_sizes
1225
+ * @property {Tensor} [input_points]
1226
+ * @property {Tensor} [input_labels]
1227
+ */
1228
+
1229
+ export class SamImageProcessor extends ImageFeatureExtractor {
1230
+
1231
+ /**
1232
+ *
1233
+ * @param {any} input_points
1234
+ * @param {HeightWidth[]} original_sizes
1235
+ * @param {HeightWidth[]} reshaped_input_sizes
1236
+ * @returns {Tensor}
1237
+ */
1238
+ reshape_input_points(input_points, original_sizes, reshaped_input_sizes) {
1239
+
1240
+ // Make deep copy to avoid altering user's input
1241
+ input_points = structuredClone(input_points);
1242
+ let shape = calculateDimensions(input_points);
1243
+
1244
+ // TODO: add support for 2D input_points
1245
+ if (shape.length === 3) {
1246
+ // Correct user's input
1247
+ shape = [1, ...shape];
1248
+ input_points = [input_points];
1249
+ } else if (shape.length !== 4) {
1250
+ throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.")
1251
+ }
1252
+
1253
+ // Reshape input points
1254
+ for (let i = 0; i < input_points.length; ++i) { // batch_size
1255
+ let originalImageSize = original_sizes[i];
1256
+ let reshapedImageSize = reshaped_input_sizes[i];
1257
+
1258
+ let resizeFactors = [
1259
+ reshapedImageSize[0] / originalImageSize[0],
1260
+ reshapedImageSize[1] / originalImageSize[1]
1261
+ ]
1262
+
1263
+ for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size
1264
+ for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image
1265
+ for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2
1266
+ input_points[i][j][k][w] *= resizeFactors[w];
1267
+ }
1268
+ }
1269
+ }
1270
+ }
1271
+
1272
+ return new Tensor(
1273
+ 'float32',
1274
+ Float32Array.from(input_points.flat(Infinity)),
1275
+ shape
1276
+ )
1277
+
1278
+ }
1279
+
1280
+ /**
1281
+ *
1282
+ * @param {any} input_labels
1283
+ * @param {Tensor} input_points
1284
+ * @returns {Tensor}
1285
+ */
1286
+ add_input_labels(input_labels, input_points) {
1287
+ let shape = calculateDimensions(input_labels);
1288
+ if (shape.length === 2) {
1289
+ // Correct user's input
1290
+ shape = [1, ...shape];
1291
+ input_labels = [input_labels];
1292
+ } else if (shape.length !== 3) {
1293
+ throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.")
1294
+ }
1295
+
1296
+ if (shape.some((x, i) => x !== input_points.dims[i])) {
1297
+ throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`)
1298
+ }
1299
+ return new Tensor(
1300
+ 'int64',
1301
+ input_labels.flat(Infinity).map(BigInt),
1302
+ shape,
1303
+ )
1304
+ }
1305
+ /**
1306
+ * @param {any[]} images The URL(s) of the image(s) to extract features from.
1307
+ * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user.
1308
+ * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.
1309
+ * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.
1310
+ * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.
1311
+ * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.
1312
+ * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.
1313
+ * @returns {Promise<SamImageProcessorResult>}
1314
+ */
1315
+ async _call(images, input_points = null, input_labels = null) {
1316
+ // TODO allow user to use preprocessed images
1317
+ /** @type {SamImageProcessorResult} */
1318
+ const processed = await super._call(images);
1319
+
1320
+ if (input_points) {
1321
+ processed.input_points = this.reshape_input_points(
1322
+ input_points, processed.original_sizes, processed.reshaped_input_sizes
1323
+ );
1324
+ }
1325
+
1326
+ if (input_labels) {
1327
+ if (!processed.input_points) {
1328
+ throw Error("`input_points` must be provided if `input_labels` are provided.")
1329
+ }
1330
+ processed.input_labels = this.add_input_labels(input_labels, processed.input_points);
1331
+ }
1332
+
1333
+ return processed;
1334
+ }
1335
+
1336
+ /**
1337
+ * Remove padding and upscale masks to the original image size.
1338
+ * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
1339
+ * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.
1340
+ * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
1341
+ * @param {Object} options Optional parameters for post-processing.
1342
+ * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.
1343
+ * @param {boolean} [options.binarize] Whether to binarize the masks.
1344
+ * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.
1345
+ * @param {number} [options.pad_size.height] The height the images were padded to.
1346
+ * @param {number} [options.pad_size.width] The width the images were padded to.
1347
+ * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.
1348
+ */
1349
+ post_process_masks(masks, original_sizes, reshaped_input_sizes, {
1350
+ mask_threshold = 0.0,
1351
+ binarize = true,
1352
+ pad_size = null,
1353
+ } = {}) {
1354
+ // masks: [1, 1, 3, 256, 256]
1355
+
1356
+ const output_masks = [];
1357
+
1358
+ pad_size = pad_size ?? this.pad_size;
1359
+
1360
+ const target_image_size = [pad_size.height, pad_size.width];
1361
+
1362
+ for (let i = 0; i < original_sizes.length; ++i) {
1363
+ const original_size = original_sizes[i];
1364
+ const reshaped_input_size = reshaped_input_sizes[i];
1365
+
1366
+ const mask = masks[i]; // [b, c, h, w]
1367
+
1368
+ // TODO: improve
1369
+ const interpolated_masks = [];
1370
+ for (let j = 0; j < mask.dims[0]; ++j) {
1371
+ const m = mask[j]; // 3d tensor
1372
+
1373
+ // Upscale mask to padded size
1374
+ let interpolated_mask = interpolate(m, target_image_size, 'bilinear', false);
1375
+
1376
+ // Crop mask
1377
+ interpolated_mask = interpolated_mask.slice(null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);
1378
+
1379
+ // Downscale mask
1380
+ interpolated_mask = interpolate(interpolated_mask, original_size, 'bilinear', false);
1381
+
1382
+ if (binarize) {
1383
+ const binarizedMaskData = new Uint8Array(interpolated_mask.data.length);
1384
+ for (let i = 0; i < interpolated_mask.data.length; ++i) {
1385
+ if (interpolated_mask.data[i] > mask_threshold) {
1386
+ binarizedMaskData[i] = 1;
1387
+ }
1388
+ }
1389
+ interpolated_mask = new Tensor(
1390
+ 'bool',
1391
+ binarizedMaskData,
1392
+ interpolated_mask.dims
1393
+ )
1394
+ }
1395
+
1396
+ interpolated_masks.push(interpolated_mask);
1397
+ }
1398
+
1399
+ output_masks.push(stack(interpolated_masks));
1400
+ }
1401
+
1402
+ return output_masks;
1403
+ }
1404
+ }
1405
+
1406
+ export class Swin2SRImageProcessor extends ImageFeatureExtractor {
1407
+ pad_image(pixelData, imgDims, padSize, options = {}) {
1408
+ // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.
1409
+ // In other words, the image is padded so that its width and height are multiples of `padSize`.
1410
+ const [imageHeight, imageWidth, imageChannels] = imgDims;
1411
+
1412
+ return super.pad_image(pixelData, imgDims, {
1413
+ // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already
1414
+ // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).
1415
+ // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.
1416
+ width: imageWidth + (padSize - imageWidth % padSize) % padSize,
1417
+ height: imageHeight + (padSize - imageHeight % padSize) % padSize,
1418
+ }, {
1419
+ mode: 'symmetric',
1420
+ center: false,
1421
+ constant_values: -1,
1422
+ ...options,
1423
+ })
1424
+ }
1425
+ }
1426
+
1427
+ export class VitMatteImageProcessor extends ImageFeatureExtractor {
1428
+ /**
1429
+ * Calls the feature extraction process on an array of images, preprocesses
1430
+ * each image, and concatenates the resulting features into a single Tensor.
1431
+ * @param {RawImage[]} images The image(s) to extract features from.
1432
+ * @param {RawImage[]} trimaps The trimaps(s) to extract features from.
1433
+ * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
1434
+ */
1435
+ async _call(images, trimaps) {
1436
+ if (!Array.isArray(images)) {
1437
+ images = [images];
1438
+ }
1439
+ if (!Array.isArray(trimaps)) {
1440
+ trimaps = [trimaps];
1441
+ }
1442
+
1443
+ const imageData = await Promise.all(images.map(x => this.preprocess(x)));
1444
+ const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, {
1445
+ do_normalize: false,
1446
+ do_convert_rgb: false,
1447
+ do_convert_grayscale: true,
1448
+ })));
1449
+
1450
+
1451
+ // Stack pixel values
1452
+ const pixel_values = stack(imageData.map(
1453
+ // Concatenate images and trimaps
1454
+ (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0)
1455
+ ), 0);
1456
+
1457
+ return {
1458
+ pixel_values: pixel_values,
1459
+
1460
+ // Original sizes of images
1461
+ original_sizes: imageData.map(x => x.original_size),
1462
+
1463
+ // Reshaped sizes of images, before padding or cropping
1464
+ reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),
1465
+ }
1466
+ }
1467
+ }
1468
+
1469
+ export class WhisperFeatureExtractor extends FeatureExtractor {
1470
+
1471
+ constructor(config) {
1472
+ super(config);
1473
+
1474
+ // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.
1475
+ this.config.mel_filters ??= mel_filter_bank(
1476
+ Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins
1477
+ this.config.feature_size, // num_mel_filters
1478
+ 0.0, // min_frequency
1479
+ 8000.0, // max_frequency
1480
+ this.config.sampling_rate, // sampling_rate
1481
+ "slaney", // norm
1482
+ "slaney", // mel_scale
1483
+ );
1484
+
1485
+ this.window = window_function(this.config.n_fft, 'hann');
1486
+ }
1487
+
1488
+ /**
1489
+ * Computes the log-Mel spectrogram of the provided audio waveform.
1490
+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1491
+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1492
+ */
1493
+ _extract_fbank_features(waveform) {
1494
+ const { data, dims } = spectrogram(
1495
+ waveform,
1496
+ this.window, // window
1497
+ this.config.n_fft, // frame_length
1498
+ this.config.hop_length, // hop_length
1499
+ {
1500
+ power: 2.0,
1501
+ mel_filters: this.config.mel_filters,
1502
+ log_mel: 'log10',
1503
+
1504
+ // Custom
1505
+ max_num_frames: this.config.nb_max_frames, // 3000
1506
+ }
1507
+ )
1508
+
1509
+ const maxValue = max(data)[0];
1510
+
1511
+ for (let i = 0; i < data.length; ++i) {
1512
+ data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;
1513
+ }
1514
+
1515
+ return { data, dims };
1516
+ }
1517
+
1518
+ /**
1519
+ * Asynchronously extracts features from a given audio using the provided configuration.
1520
+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1521
+ * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1522
+ */
1523
+ async _call(audio) {
1524
+ validate_audio_inputs(audio, 'WhisperFeatureExtractor');
1525
+
1526
+ let waveform;
1527
+ if (audio.length > this.config.n_samples) {
1528
+ console.warn(
1529
+ "Attempting to extract features for audio longer than 30 seconds. " +
1530
+ "If using a pipeline to extract transcript from a long audio clip, " +
1531
+ "remember to specify `chunk_length_s` and/or `stride_length_s`."
1532
+ );
1533
+ waveform = audio.slice(0, this.config.n_samples);
1534
+ } else {
1535
+ // pad with zeros
1536
+ waveform = new Float32Array(this.config.n_samples);
1537
+ waveform.set(audio);
1538
+ }
1539
+
1540
+ const { data, dims } = this._extract_fbank_features(waveform);
1541
+
1542
+ return {
1543
+ input_features: new Tensor('float32',
1544
+ data,
1545
+ [1, ...dims]
1546
+ )
1547
+ };
1548
+ }
1549
+ }
1550
+
1551
+ export class Wav2Vec2FeatureExtractor extends FeatureExtractor {
1552
+
1553
+ /**
1554
+ * @param {Float32Array} input_values
1555
+ * @returns {Float32Array}
1556
+ */
1557
+ _zero_mean_unit_var_norm(input_values) {
1558
+ // TODO support batch?
1559
+ const sum = input_values.reduce((a, b) => a + b, 0);
1560
+ const mean = sum / input_values.length;
1561
+ const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length;
1562
+ return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7));
1563
+ }
1564
+
1565
+ /**
1566
+ * Asynchronously extracts features from a given audio using the provided configuration.
1567
+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1568
+ * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.
1569
+ */
1570
+ async _call(audio) {
1571
+ validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor');
1572
+
1573
+ if (audio instanceof Float64Array) {
1574
+ audio = new Float32Array(audio);
1575
+ }
1576
+
1577
+ let input_values = audio;
1578
+
1579
+ // zero-mean and unit-variance normalization
1580
+ if (this.config.do_normalize) {
1581
+ input_values = this._zero_mean_unit_var_norm(input_values);
1582
+ }
1583
+
1584
+ // TODO: allow user to pass in attention mask
1585
+ const shape = [1, input_values.length];
1586
+ return {
1587
+ input_values: new Tensor('float32', input_values, shape),
1588
+ attention_mask: new Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape)
1589
+ };
1590
+ }
1591
+ }
1592
+
1593
+ export class SeamlessM4TFeatureExtractor extends FeatureExtractor {
1594
+
1595
+ constructor(config) {
1596
+ super(config);
1597
+
1598
+ const sampling_rate = this.config.sampling_rate;
1599
+ const mel_filters = mel_filter_bank(
1600
+ 256, // num_frequency_bins
1601
+ this.config.num_mel_bins, // num_mel_filters
1602
+ 20, // min_frequency
1603
+ Math.floor(sampling_rate / 2), // max_frequency
1604
+ sampling_rate, // sampling_rate
1605
+ null, // norm
1606
+ "kaldi", // mel_scale
1607
+ true, // triangularize_in_mel_space
1608
+ );
1609
+
1610
+ // Do padding:
1611
+ for (let i = 0; i < mel_filters.length; ++i) {
1612
+ mel_filters[i].push(0);
1613
+ }
1614
+ this.mel_filters = mel_filters;
1615
+
1616
+ this.window = window_function(400, 'povey', {
1617
+ periodic: false,
1618
+ })
1619
+ }
1620
+
1621
+ /**
1622
+ * Computes the log-Mel spectrogram of the provided audio waveform.
1623
+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1624
+ * @param {number} max_length The maximum number of frames to return.
1625
+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1626
+ */
1627
+ _extract_fbank_features(waveform, max_length) {
1628
+ // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
1629
+
1630
+ // Kaldi compliance: 16-bit signed integers
1631
+ // 32768 == 2 ** 15
1632
+ waveform = waveform.map((/** @type {number} */ x) => x * 32768)
1633
+
1634
+ return spectrogram(
1635
+ waveform,
1636
+ this.window, // window
1637
+ 400, // frame_length
1638
+ 160, // hop_length
1639
+ {
1640
+ fft_length: 512,
1641
+ power: 2.0,
1642
+ center: false,
1643
+ preemphasis: 0.97,
1644
+ mel_filters: this.mel_filters,
1645
+ log_mel: 'log',
1646
+ mel_floor: 1.192092955078125e-07,
1647
+ remove_dc_offset: true,
1648
+
1649
+ // Custom
1650
+ max_num_frames: max_length,
1651
+ transpose: true,
1652
+ }
1653
+ )
1654
+ }
1655
+
1656
+ /**
1657
+ * Asynchronously extracts features from a given audio using the provided configuration.
1658
+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1659
+ * @param {Object} options Optional parameters for feature extraction.
1660
+ * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`.
1661
+ * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of.
1662
+ * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel.
1663
+ * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask.
1664
+ * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors.
1665
+ */
1666
+ async _call(audio, {
1667
+ padding = true,
1668
+ pad_to_multiple_of = 2,
1669
+ do_normalize_per_mel_bins = true,
1670
+ return_attention_mask = true,
1671
+ } = {}) {
1672
+ validate_audio_inputs(audio, 'SeamlessM4TFeatureExtractor');
1673
+
1674
+ let features = this._extract_fbank_features(audio, this.config.max_length);
1675
+
1676
+ if (do_normalize_per_mel_bins) {
1677
+ const [num_features, feature_size] = features.dims;
1678
+ for (let i = 0; i < feature_size; ++i) {
1679
+ let sum = 0;
1680
+ for (let j = 0; j < num_features; ++j) {
1681
+ sum += features.data[j * feature_size + i];
1682
+ }
1683
+
1684
+ const mean = sum / num_features;
1685
+
1686
+ let variance = 0;
1687
+ for (let j = 0; j < num_features; ++j) {
1688
+ variance += (features.data[j * feature_size + i] - mean) ** 2;
1689
+ }
1690
+ variance /= num_features - 1; // NOTE: We use ddof=1
1691
+
1692
+ const std = Math.sqrt(variance + 1e-7);
1693
+ for (let j = 0; j < num_features; ++j) {
1694
+ const index = j * feature_size + i;
1695
+ features.data[index] = (features.data[index] - mean) / std;
1696
+ }
1697
+ }
1698
+ }
1699
+
1700
+ let padded_attention_mask;
1701
+ if (padding) {
1702
+ const [num_frames, num_channels] = features.dims;
1703
+
1704
+ const pad_size = num_frames % pad_to_multiple_of;
1705
+ if (pad_size > 0) {
1706
+ const padded_data = new Float32Array(num_channels * (num_frames + pad_size));
1707
+ padded_data.set(features.data)
1708
+ padded_data.fill(this.config.padding_value, features.data.length)
1709
+
1710
+ const numPaddedFrames = num_frames + pad_size;
1711
+ features = {
1712
+ data: padded_data,
1713
+ dims: [numPaddedFrames, num_channels],
1714
+ }
1715
+
1716
+ if (return_attention_mask) {
1717
+ padded_attention_mask = new Tensor(
1718
+ 'int64',
1719
+ new BigInt64Array(numPaddedFrames),
1720
+ [1, numPaddedFrames],
1721
+ )
1722
+ padded_attention_mask.data.fill(1n, 0, num_frames);
1723
+ }
1724
+ }
1725
+ }
1726
+
1727
+ const [num_frames, num_channels] = features.dims;
1728
+
1729
+ const stride = this.config.stride;
1730
+ const remainder = num_frames % stride;
1731
+ if (remainder !== 0) {
1732
+ throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`)
1733
+ }
1734
+
1735
+ const input_features = new Tensor('float32',
1736
+ features.data,
1737
+ features.dims,
1738
+ ).view(
1739
+ 1,
1740
+ Math.floor(num_frames / stride),
1741
+ num_channels * stride,
1742
+ );
1743
+
1744
+ const result = { input_features }
1745
+
1746
+ if (return_attention_mask) {
1747
+ const reshapedNumFrames = input_features.dims[1];
1748
+
1749
+ const attention_mask = new Tensor(
1750
+ 'int64',
1751
+ new BigInt64Array(reshapedNumFrames),
1752
+ [1, reshapedNumFrames],
1753
+ );
1754
+ if (padded_attention_mask) {
1755
+ for (let i = 1, j = 0; i < num_frames; i += stride, ++j) {
1756
+ attention_mask.data[j] = padded_attention_mask.data[i];
1757
+ }
1758
+ } else {
1759
+ attention_mask.data.fill(1n);
1760
+ }
1761
+
1762
+ result.attention_mask = attention_mask;
1763
+ }
1764
+
1765
+ return result;
1766
+ }
1767
+ }
1768
+
1769
+ export class ASTFeatureExtractor extends FeatureExtractor {
1770
+
1771
+
1772
+ constructor(config) {
1773
+ super(config);
1774
+
1775
+ const sampling_rate = this.config.sampling_rate;
1776
+ const mel_filters = mel_filter_bank(
1777
+ 256, // num_frequency_bins
1778
+ this.config.num_mel_bins, // num_mel_filters
1779
+ 20, // min_frequency
1780
+ Math.floor(sampling_rate / 2), // max_frequency
1781
+ sampling_rate, // sampling_rate
1782
+ null, // norm
1783
+ "kaldi", // mel_scale
1784
+ true, // triangularize_in_mel_space
1785
+ );
1786
+
1787
+ // Do padding:
1788
+ for (let i = 0; i < mel_filters.length; ++i) {
1789
+ mel_filters[i].push(0);
1790
+ }
1791
+ this.mel_filters = mel_filters;
1792
+
1793
+ this.window = window_function(400, 'hann', {
1794
+ periodic: false,
1795
+ })
1796
+
1797
+ this.mean = this.config.mean;
1798
+ this.std = this.config.std;
1799
+ }
1800
+
1801
+ /**
1802
+ * Computes the log-Mel spectrogram of the provided audio waveform.
1803
+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1804
+ * @param {number} max_length The maximum number of frames to return.
1805
+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1806
+ */
1807
+ _extract_fbank_features(waveform, max_length) {
1808
+ // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
1809
+ return spectrogram(
1810
+ waveform,
1811
+ this.window, // window
1812
+ 400, // frame_length
1813
+ 160, // hop_length
1814
+ {
1815
+ fft_length: 512,
1816
+ power: 2.0,
1817
+ center: false,
1818
+ preemphasis: 0.97,
1819
+ mel_filters: this.mel_filters,
1820
+ log_mel: 'log',
1821
+ mel_floor: 1.192092955078125e-07,
1822
+ remove_dc_offset: true,
1823
+
1824
+ // Custom
1825
+ max_num_frames: max_length,
1826
+ transpose: true,
1827
+ }
1828
+ )
1829
+ }
1830
+
1831
+
1832
+ /**
1833
+ * Asynchronously extracts features from a given audio using the provided configuration.
1834
+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1835
+ * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1836
+ */
1837
+ async _call(audio) {
1838
+ validate_audio_inputs(audio, 'ASTFeatureExtractor');
1839
+
1840
+ const features = this._extract_fbank_features(audio, this.config.max_length);
1841
+ if (this.config.do_normalize) {
1842
+ // Normalize the input audio spectrogram to have mean=0, std=0.5
1843
+ const denom = this.std * 2;
1844
+ for (let i = 0; i < features.data.length; ++i) {
1845
+ features.data[i] = (features.data[i] - this.mean) / denom;
1846
+ }
1847
+ }
1848
+
1849
+ return {
1850
+ input_values: new Tensor('float32',
1851
+ features.data,
1852
+ [1, ...features.dims]
1853
+ )
1854
+ };
1855
+ }
1856
+ }
1857
+
1858
+ export class ClapFeatureExtractor extends FeatureExtractor {
1859
+
1860
+ constructor(config) {
1861
+ super(config);
1862
+
1863
+ this.mel_filters = mel_filter_bank(
1864
+ this.config.nb_frequency_bins, // num_frequency_bins
1865
+ this.config.feature_size, // num_mel_filters
1866
+ this.config.frequency_min, // min_frequency
1867
+ this.config.frequency_max, // max_frequency
1868
+ this.config.sampling_rate, // sampling_rate
1869
+ null, // norm
1870
+ "htk", // mel_scale
1871
+ );
1872
+
1873
+ this.mel_filters_slaney = mel_filter_bank(
1874
+ this.config.nb_frequency_bins, // num_frequency_bins
1875
+ this.config.feature_size, // num_mel_filters
1876
+ this.config.frequency_min, // min_frequency
1877
+ this.config.frequency_max, // max_frequency
1878
+ this.config.sampling_rate, // sampling_rate
1879
+ "slaney", // norm
1880
+ "slaney", // mel_scale
1881
+ );
1882
+
1883
+ this.window = window_function(this.config.fft_window_size, 'hann')
1884
+
1885
+ }
1886
+
1887
+
1888
+ /**
1889
+ * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
1890
+ *
1891
+ * Four different path are possible:
1892
+ * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
1893
+ * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
1894
+ * are then stacked together. They will later be used for `feature_fusion`.
1895
+ * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
1896
+ * padded based on `padding`.
1897
+ * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
1898
+ * based on `padding`, and is repeated `4` times.
1899
+ * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
1900
+ * spectrogram will be computed on a random crop of the waveform.
1901
+ *
1902
+ * @param {Float32Array|Float64Array} waveform The input waveform.
1903
+ * @param {number} max_length The maximum length of the waveform.
1904
+ * @param {string} truncation The truncation strategy to use.
1905
+ * @param {string} padding The padding strategy to use.
1906
+ * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.
1907
+ */
1908
+ _get_input_mel(waveform, max_length, truncation, padding) {
1909
+
1910
+ /** @type {{ data: Float32Array; dims: number[]}} */
1911
+ let input_mel;
1912
+ let longer = false;
1913
+ const diff = waveform.length - max_length;
1914
+ if (diff > 0) {
1915
+ if (truncation === 'rand_trunc') {
1916
+ longer = true;
1917
+ const idx = Math.floor(Math.random() * (diff + 1));
1918
+ waveform = waveform.subarray(idx, idx + max_length);
1919
+
1920
+ input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);
1921
+ input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
1922
+ } else {
1923
+ // TODO implement fusion strategy
1924
+ throw new Error(`Truncation strategy "${truncation}" not implemented`)
1925
+ }
1926
+ } else {
1927
+ if (diff < 0) {
1928
+ let padded = new Float64Array(max_length); // already padded with zeros
1929
+ padded.set(waveform);
1930
+
1931
+ if (padding === 'repeat') {
1932
+ for (let i = waveform.length; i < max_length; i += waveform.length) {
1933
+ padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i);
1934
+ }
1935
+ } else if (padding === 'repeatpad') {
1936
+ for (let i = waveform.length; i < -diff; i += waveform.length) {
1937
+ padded.set(waveform, i);
1938
+ }
1939
+ }
1940
+ waveform = padded;
1941
+ }
1942
+
1943
+ if (truncation === 'fusion') {
1944
+ throw new Error(`Truncation strategy "${truncation}" not implemented`)
1945
+ }
1946
+
1947
+ input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);
1948
+ input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
1949
+ }
1950
+
1951
+ return {
1952
+ ...input_mel,
1953
+ longer,
1954
+ }
1955
+ }
1956
+
1957
+ /**
1958
+ * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.
1959
+ * In CLAP, two different filter banks are used depending on the truncation pattern:
1960
+ * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
1961
+ * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
1962
+ * is set to `"fusion"`.
1963
+ * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
1964
+ * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
1965
+ * implementation when the truncation mode is not `"fusion"`.
1966
+ *
1967
+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1968
+ * @param {number[][]} mel_filters The mel filters to use.
1969
+ * @param {number} [max_length=null] The maximum number of frames to return.
1970
+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1971
+ */
1972
+ _extract_fbank_features(waveform, mel_filters, max_length = null) {
1973
+ // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
1974
+ return spectrogram(
1975
+ waveform,
1976
+ this.window, // window
1977
+ this.config.fft_window_size, // frame_length
1978
+ this.config.hop_length, // hop_length
1979
+ {
1980
+ power: 2.0,
1981
+ mel_filters,
1982
+ log_mel: 'dB',
1983
+
1984
+ // Custom
1985
+ max_num_frames: max_length,
1986
+ do_pad: false,
1987
+ transpose: true,
1988
+ }
1989
+ )
1990
+ }
1991
+
1992
+
1993
+ /**
1994
+ * Asynchronously extracts features from a given audio using the provided configuration.
1995
+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1996
+ * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1997
+ */
1998
+ async _call(audio, {
1999
+ max_length = null,
2000
+ } = {}) {
2001
+ validate_audio_inputs(audio, 'ClapFeatureExtractor');
2002
+
2003
+ // convert to mel spectrogram, truncate and pad if needed.
2004
+ const padded_inputs = this._get_input_mel(
2005
+ audio,
2006
+ max_length ?? this.config.nb_max_samples,
2007
+ this.config.truncation,
2008
+ this.config.padding,
2009
+ );
2010
+
2011
+
2012
+ return {
2013
+ input_features: new Tensor('float32',
2014
+ padded_inputs.data,
2015
+ [1, ...padded_inputs.dims]
2016
+ )
2017
+ };
2018
+ }
2019
+ }
2020
+
2021
+
2022
+
2023
+ export class SpeechT5FeatureExtractor extends FeatureExtractor { }
2024
+
2025
+ /**
2026
+ * Represents a Processor that extracts features from an input.
2027
+ * @extends Callable
2028
+ */
2029
+ export class Processor extends Callable {
2030
+ /**
2031
+ * Creates a new Processor with the given feature extractor.
2032
+ * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.
2033
+ */
2034
+ constructor(feature_extractor) {
2035
+ super();
2036
+ this.feature_extractor = feature_extractor;
2037
+ // TODO use tokenizer here?
2038
+ }
2039
+
2040
+ /**
2041
+ * Calls the feature_extractor function with the given input.
2042
+ * @param {any} input The input to extract features from.
2043
+ * @param {...any} args Additional arguments.
2044
+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
2045
+ */
2046
+ async _call(input, ...args) {
2047
+ return await this.feature_extractor(input, ...args);
2048
+ }
2049
+ }
2050
+
2051
+ export class SamProcessor extends Processor {
2052
+ /**
2053
+ * @borrows SamImageProcessor#_call as _call
2054
+ */
2055
+ async _call(...args) {
2056
+ return await this.feature_extractor(...args);
2057
+ }
2058
+
2059
+ /**
2060
+ * @borrows SamImageProcessor#post_process_masks as post_process_masks
2061
+ */
2062
+ post_process_masks(...args) {
2063
+ // @ts-ignore
2064
+ return this.feature_extractor.post_process_masks(...args);
2065
+ }
2066
+ /**
2067
+ * @borrows SamImageProcessor#reshape_input_points as reshape_input_points
2068
+ */
2069
+ reshape_input_points(...args) {
2070
+ // @ts-ignore
2071
+ return this.feature_extractor.reshape_input_points(...args);
2072
+ }
2073
+ }
2074
+
2075
+ /**
2076
+ * Represents a WhisperProcessor that extracts features from an audio input.
2077
+ * @extends Processor
2078
+ */
2079
+ export class WhisperProcessor extends Processor {
2080
+ /**
2081
+ * Calls the feature_extractor function with the given audio input.
2082
+ * @param {any} audio The audio input to extract features from.
2083
+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
2084
+ */
2085
+ async _call(audio) {
2086
+ return await this.feature_extractor(audio)
2087
+ }
2088
+ }
2089
+
2090
+
2091
+ export class Wav2Vec2ProcessorWithLM extends Processor {
2092
+ /**
2093
+ * Calls the feature_extractor function with the given audio input.
2094
+ * @param {any} audio The audio input to extract features from.
2095
+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
2096
+ */
2097
+ async _call(audio) {
2098
+ return await this.feature_extractor(audio)
2099
+ }
2100
+ }
2101
+
2102
+ export class SpeechT5Processor extends Processor {
2103
+ /**
2104
+ * Calls the feature_extractor function with the given input.
2105
+ * @param {any} input The input to extract features from.
2106
+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
2107
+ */
2108
+ async _call(input) {
2109
+ return await this.feature_extractor(input)
2110
+ }
2111
+ }
2112
+
2113
+ export class OwlViTProcessor extends Processor { }
2114
+
2115
+
2116
+ //////////////////////////////////////////////////
2117
+ /**
2118
+ * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.
2119
+ * The chosen processor class is determined by the type specified in the processor config.
2120
+ *
2121
+ * **Example:** Load a processor using `from_pretrained`.
2122
+ * ```javascript
2123
+ * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');
2124
+ * ```
2125
+ *
2126
+ * **Example:** Run an image through a processor.
2127
+ * ```javascript
2128
+ * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');
2129
+ * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
2130
+ * let image_inputs = await processor(image);
2131
+ * // {
2132
+ * // "pixel_values": {
2133
+ * // "dims": [ 1, 3, 224, 224 ],
2134
+ * // "type": "float32",
2135
+ * // "data": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ],
2136
+ * // "size": 150528
2137
+ * // },
2138
+ * // "original_sizes": [
2139
+ * // [ 533, 800 ]
2140
+ * // ],
2141
+ * // "reshaped_input_sizes": [
2142
+ * // [ 224, 224 ]
2143
+ * // ]
2144
+ * // }
2145
+ * ```
2146
+ */
2147
+ export class AutoProcessor {
2148
+ static FEATURE_EXTRACTOR_CLASS_MAPPING = {
2149
+ ImageFeatureExtractor,
2150
+ WhisperFeatureExtractor,
2151
+ ViTFeatureExtractor,
2152
+ MobileViTFeatureExtractor,
2153
+ MobileViTImageProcessor,
2154
+ OwlViTFeatureExtractor,
2155
+ Owlv2ImageProcessor,
2156
+ CLIPFeatureExtractor,
2157
+ ChineseCLIPFeatureExtractor,
2158
+ SiglipImageProcessor,
2159
+ ConvNextFeatureExtractor,
2160
+ ConvNextImageProcessor,
2161
+ SegformerFeatureExtractor,
2162
+ BitImageProcessor,
2163
+ DPTImageProcessor,
2164
+ DPTFeatureExtractor,
2165
+ GLPNFeatureExtractor,
2166
+ BeitFeatureExtractor,
2167
+ DeiTFeatureExtractor,
2168
+ DetrFeatureExtractor,
2169
+ YolosFeatureExtractor,
2170
+ DonutFeatureExtractor,
2171
+ NougatImageProcessor,
2172
+ EfficientNetImageProcessor,
2173
+
2174
+ ViTImageProcessor,
2175
+ VitMatteImageProcessor,
2176
+ SamImageProcessor,
2177
+ Swin2SRImageProcessor,
2178
+ Wav2Vec2FeatureExtractor,
2179
+ SeamlessM4TFeatureExtractor,
2180
+ SpeechT5FeatureExtractor,
2181
+ ASTFeatureExtractor,
2182
+ ClapFeatureExtractor,
2183
+ }
2184
+
2185
+ static PROCESSOR_CLASS_MAPPING = {
2186
+ WhisperProcessor,
2187
+ Wav2Vec2ProcessorWithLM,
2188
+ SamProcessor,
2189
+ SpeechT5Processor,
2190
+ OwlViTProcessor,
2191
+ }
2192
+
2193
+ /**
2194
+ * Instantiate one of the processor classes of the library from a pretrained model.
2195
+ *
2196
+ * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object
2197
+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
2198
+ *
2199
+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
2200
+ * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
2201
+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
2202
+ * user or organization name, like `dbmdz/bert-base-german-cased`.
2203
+ * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
2204
+ * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
2205
+ *
2206
+ * @returns {Promise<Processor>} A new instance of the Processor class.
2207
+ */
2208
+ static async from_pretrained(pretrained_model_name_or_path, {
2209
+ progress_callback = null,
2210
+ config = null,
2211
+ cache_dir = null,
2212
+ local_files_only = false,
2213
+ revision = 'main',
2214
+ } = {}) {
2215
+
2216
+ let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, 'preprocessor_config.json', true, {
2217
+ progress_callback,
2218
+ config,
2219
+ cache_dir,
2220
+ local_files_only,
2221
+ revision,
2222
+ })
2223
+
2224
+ // Determine feature extractor class
2225
+ // TODO: Ensure backwards compatibility with old configs
2226
+ let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type;
2227
+ let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];
2228
+
2229
+ if (!feature_extractor_class) {
2230
+ if (preprocessorConfig.size !== undefined) {
2231
+ // Assume ImageFeatureExtractor
2232
+ console.warn(`Feature extractor type "${key}" not found, assuming ImageFeatureExtractor due to size parameter in config.`);
2233
+ feature_extractor_class = ImageFeatureExtractor;
2234
+ } else {
2235
+ throw new Error(`Unknown Feature Extractor type: ${key}`);
2236
+ }
2237
+ }
2238
+
2239
+ // If no associated processor class, use default
2240
+ let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;
2241
+
2242
+ // Instantiate processor and feature extractor
2243
+ let feature_extractor = new feature_extractor_class(preprocessorConfig);
2244
+ return new processor_class(feature_extractor);
2245
+ }
2246
+ }
2247
+ //////////////////////////////////////////////////
2248
+