@huggingface/transformers 3.0.1 → 3.1.0

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