spec-cat 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/_nuxt/{Bqlz6CoK.js → BE_75kPa.js} +1 -1
  3. package/.output/public/_nuxt/{B2wdmh_w.js → BJ7m4fRW.js} +53 -53
  4. package/.output/public/_nuxt/{KNuzSjk0.js → CCNYUZ9m.js} +1 -1
  5. package/.output/public/_nuxt/{BvosqTnx.js → DGtcdWVl.js} +1 -1
  6. package/.output/public/_nuxt/DxEx-kFx.js +1 -0
  7. package/.output/public/_nuxt/{BwcbSlWF.js → DyMq_cQC.js} +2 -2
  8. package/.output/public/_nuxt/{COTT6rNZ.js → _cj5lOdZ.js} +1 -1
  9. package/.output/public/_nuxt/builds/latest.json +1 -1
  10. package/.output/public/_nuxt/builds/meta/3a0aacc1-0bd1-4d15-8b8a-3cee48cbfc69.json +1 -0
  11. package/.output/public/_nuxt/{BUOk7wkI.js → gDut6QrP.js} +1 -1
  12. package/.output/public/_nuxt/{C5wk2twv.js → nJpWpjzg.js} +1 -1
  13. package/.output/public/_nuxt/{DBab5Zcv.js → waQ9fPC1.js} +1 -1
  14. package/.output/server/chunks/_/codexProvider.mjs +64 -18
  15. package/.output/server/chunks/_/codexProvider.mjs.map +1 -1
  16. package/.output/server/chunks/build/client.precomputed.mjs +1 -1
  17. package/.output/server/chunks/build/client.precomputed.mjs.map +1 -1
  18. package/.output/server/chunks/nitro/nitro.mjs +702 -703
  19. package/.output/server/chunks/routes/_ws.mjs +37 -7
  20. package/.output/server/chunks/routes/_ws.mjs.map +1 -1
  21. package/.output/server/node_modules/@huggingface/jinja/dist/index.js +1572 -0
  22. package/.output/server/node_modules/@huggingface/jinja/package.json +55 -0
  23. package/.output/server/node_modules/@xenova/transformers/package.json +84 -0
  24. package/.output/server/node_modules/@xenova/transformers/src/backends/onnx.js +50 -0
  25. package/.output/server/node_modules/@xenova/transformers/src/configs.js +107 -0
  26. package/.output/server/node_modules/@xenova/transformers/src/env.js +128 -0
  27. package/.output/server/node_modules/@xenova/transformers/src/models.js +6267 -0
  28. package/.output/server/node_modules/@xenova/transformers/src/pipelines.js +3287 -0
  29. package/.output/server/node_modules/@xenova/transformers/src/processors.js +2248 -0
  30. package/.output/server/node_modules/@xenova/transformers/src/tokenizers.js +4479 -0
  31. package/.output/server/node_modules/@xenova/transformers/src/transformers.js +24 -0
  32. package/.output/server/node_modules/@xenova/transformers/src/utils/audio.js +672 -0
  33. package/.output/server/node_modules/@xenova/transformers/src/utils/core.js +175 -0
  34. package/.output/server/node_modules/@xenova/transformers/src/utils/data-structures.js +415 -0
  35. package/.output/server/node_modules/@xenova/transformers/src/utils/generation.js +873 -0
  36. package/.output/server/node_modules/@xenova/transformers/src/utils/hub.js +658 -0
  37. package/.output/server/node_modules/@xenova/transformers/src/utils/image.js +731 -0
  38. package/.output/server/node_modules/@xenova/transformers/src/utils/maths.js +985 -0
  39. package/.output/server/node_modules/@xenova/transformers/src/utils/tensor.js +1239 -0
  40. package/.output/server/node_modules/color/index.js +496 -0
  41. package/.output/server/node_modules/color/package.json +47 -0
  42. package/.output/server/node_modules/color-convert/conversions.js +839 -0
  43. package/.output/server/node_modules/color-convert/index.js +81 -0
  44. package/.output/server/node_modules/color-convert/package.json +48 -0
  45. package/.output/server/node_modules/color-convert/route.js +97 -0
  46. package/.output/server/node_modules/color-name/index.js +152 -0
  47. package/.output/server/node_modules/color-name/package.json +28 -0
  48. package/.output/server/node_modules/color-string/index.js +242 -0
  49. package/.output/server/node_modules/color-string/package.json +39 -0
  50. package/.output/server/node_modules/detect-libc/lib/detect-libc.js +313 -0
  51. package/.output/server/node_modules/detect-libc/lib/elf.js +39 -0
  52. package/.output/server/node_modules/detect-libc/lib/filesystem.js +51 -0
  53. package/.output/server/node_modules/detect-libc/lib/process.js +24 -0
  54. package/.output/server/node_modules/detect-libc/package.json +44 -0
  55. package/.output/server/node_modules/is-arrayish/index.js +9 -0
  56. package/.output/server/node_modules/is-arrayish/package.json +45 -0
  57. package/.output/server/node_modules/onnxruntime-common/dist/ort-common.node.js +7 -0
  58. package/.output/server/node_modules/onnxruntime-common/package.json +31 -0
  59. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/darwin/arm64/onnxruntime_binding.node +0 -0
  60. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/darwin/x64/onnxruntime_binding.node +0 -0
  61. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/arm64/libonnxruntime.so.1.14.0 +0 -0
  62. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/arm64/onnxruntime_binding.node +0 -0
  63. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/libonnxruntime.so.1.14.0 +0 -0
  64. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/onnxruntime_binding.node +0 -0
  65. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/win32/arm64/onnxruntime_binding.node +0 -0
  66. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/win32/x64/onnxruntime_binding.node +0 -0
  67. package/.output/server/node_modules/onnxruntime-node/dist/backend.js +75 -0
  68. package/.output/server/node_modules/onnxruntime-node/dist/binding.js +10 -0
  69. package/.output/server/node_modules/onnxruntime-node/dist/index.js +23 -0
  70. package/.output/server/node_modules/onnxruntime-node/package.json +58 -0
  71. package/.output/server/node_modules/onnxruntime-web/dist/ort-web.node.js +7 -0
  72. package/.output/server/node_modules/onnxruntime-web/package.json +84 -0
  73. package/.output/server/node_modules/semver/classes/semver.js +333 -0
  74. package/.output/server/node_modules/semver/functions/coerce.js +62 -0
  75. package/.output/server/node_modules/semver/functions/compare.js +7 -0
  76. package/.output/server/node_modules/semver/functions/gte.js +5 -0
  77. package/.output/server/node_modules/semver/functions/parse.js +18 -0
  78. package/.output/server/node_modules/semver/internal/constants.js +37 -0
  79. package/.output/server/node_modules/semver/internal/debug.js +11 -0
  80. package/.output/server/node_modules/semver/internal/identifiers.js +29 -0
  81. package/.output/server/node_modules/semver/internal/parse-options.js +17 -0
  82. package/.output/server/node_modules/semver/internal/re.js +223 -0
  83. package/.output/server/node_modules/semver/package.json +78 -0
  84. package/.output/server/node_modules/sharp/build/Release/sharp-linux-x64.node +0 -0
  85. package/.output/server/node_modules/sharp/lib/channel.js +174 -0
  86. package/.output/server/node_modules/sharp/lib/colour.js +184 -0
  87. package/.output/server/node_modules/sharp/lib/composite.js +210 -0
  88. package/.output/server/node_modules/sharp/lib/constructor.js +439 -0
  89. package/.output/server/node_modules/sharp/lib/index.js +16 -0
  90. package/.output/server/node_modules/sharp/lib/input.js +631 -0
  91. package/.output/server/node_modules/sharp/lib/is.js +155 -0
  92. package/.output/server/node_modules/sharp/lib/libvips.js +140 -0
  93. package/.output/server/node_modules/sharp/lib/operation.js +919 -0
  94. package/.output/server/node_modules/sharp/lib/output.js +1413 -0
  95. package/.output/server/node_modules/sharp/lib/platform.js +30 -0
  96. package/.output/server/node_modules/sharp/lib/resize.js +582 -0
  97. package/.output/server/node_modules/sharp/lib/sharp.js +38 -0
  98. package/.output/server/node_modules/sharp/lib/utility.js +287 -0
  99. package/.output/server/node_modules/sharp/package.json +204 -0
  100. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/THIRD-PARTY-NOTICES.md +43 -0
  101. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/lib/libvips-cpp.so.42 +0 -0
  102. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/platform.json +1 -0
  103. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/versions.json +31 -0
  104. package/.output/server/node_modules/simple-swizzle/index.js +29 -0
  105. package/.output/server/node_modules/simple-swizzle/package.json +36 -0
  106. package/.output/server/package.json +15 -1
  107. package/README.md +2 -0
  108. package/package.json +12 -19
  109. package/.output/public/_nuxt/5FxpIoe_.js +0 -1
  110. package/.output/public/_nuxt/builds/meta/21578a05-1b7e-4847-a8ff-7480800ea4a6.json +0 -1
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @file Entry point for the Transformers.js library. Only the exports from this file
3
+ * are available to the end user, and are grouped as follows:
4
+ *
5
+ * 1. [Pipelines](./pipelines)
6
+ * 2. [Environment variables](./env)
7
+ * 3. [Models](./models)
8
+ * 4. [Tokenizers](./tokenizers)
9
+ * 5. [Processors](./processors)
10
+ *
11
+ * @module transformers
12
+ */
13
+
14
+ export * from './pipelines.js';
15
+ export * from './env.js';
16
+ export * from './models.js';
17
+ export * from './tokenizers.js';
18
+ export * from './processors.js';
19
+ export * from './configs.js';
20
+
21
+ export * from './utils/audio.js';
22
+ export * from './utils/image.js';
23
+ export * from './utils/tensor.js';
24
+ export * from './utils/maths.js';
@@ -0,0 +1,672 @@
1
+ /**
2
+ * @file Helper module for audio processing.
3
+ *
4
+ * These functions and classes are only used internally,
5
+ * meaning an end-user shouldn't need to access anything here.
6
+ *
7
+ * @module utils/audio
8
+ */
9
+
10
+ import {
11
+ getFile,
12
+ } from './hub.js';
13
+ import { FFT, max } from './maths.js';
14
+ import {
15
+ calculateReflectOffset,
16
+ } from './core.js';
17
+
18
+
19
+ /**
20
+ * Helper function to read audio from a path/URL.
21
+ * @param {string|URL} url The path/URL to load the audio from.
22
+ * @param {number} sampling_rate The sampling rate to use when decoding the audio.
23
+ * @returns {Promise<Float32Array>} The decoded audio as a `Float32Array`.
24
+ */
25
+ export async function read_audio(url, sampling_rate) {
26
+ if (typeof AudioContext === 'undefined') {
27
+ // Running in node or an environment without AudioContext
28
+ throw Error(
29
+ "Unable to load audio from path/URL since `AudioContext` is not available in your environment. " +
30
+ "Instead, audio data should be passed directly to the pipeline/processor. " +
31
+ "For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing."
32
+ )
33
+ }
34
+
35
+ const response = await (await getFile(url)).arrayBuffer();
36
+ const audioCTX = new AudioContext({ sampleRate: sampling_rate });
37
+ if (typeof sampling_rate === 'undefined') {
38
+ console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`)
39
+ }
40
+ const decoded = await audioCTX.decodeAudioData(response);
41
+
42
+ /** @type {Float32Array} */
43
+ let audio;
44
+
45
+ // We now replicate HuggingFace's `ffmpeg_read` method:
46
+ if (decoded.numberOfChannels === 2) {
47
+ // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,
48
+ // the audio signal is summed across both channels to create a single mono channel.
49
+ // However, if the audio is at full scale (i.e. the highest possible volume level),
50
+ // the summing of the two channels can cause the audio signal to clip or distort.
51
+
52
+ // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)
53
+ // to the audio signal before summing the two channels. This scaling factor ensures
54
+ // that the combined audio signal will not exceed the maximum possible level, even
55
+ // if both channels are at full scale.
56
+
57
+ // After applying this scaling factor, the audio signal from both channels is summed
58
+ // to create a single mono channel. It's worth noting that this scaling factor is
59
+ // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.
60
+ // If you're using a different downmixing method, or if you're not downmixing the
61
+ // audio at all, this scaling factor may not be needed.
62
+ const SCALING_FACTOR = Math.sqrt(2);
63
+
64
+ const left = decoded.getChannelData(0);
65
+ const right = decoded.getChannelData(1);
66
+
67
+ audio = new Float32Array(left.length);
68
+ for (let i = 0; i < decoded.length; ++i) {
69
+ audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2;
70
+ }
71
+
72
+ } else {
73
+ // If the audio is not stereo, we can just use the first channel:
74
+ audio = decoded.getChannelData(0);
75
+ }
76
+
77
+ return audio;
78
+ }
79
+
80
+ /**
81
+ * Generates a Hanning window of length M.
82
+ *
83
+ * @param {number} M The length of the Hanning window to generate.
84
+ * @returns {Float64Array} The generated Hanning window.
85
+ */
86
+ export function hanning(M) {
87
+ if (M < 1) {
88
+ return new Float64Array();
89
+ }
90
+ if (M === 1) {
91
+ return new Float64Array([1]);
92
+ }
93
+ const denom = M - 1;
94
+ const factor = Math.PI / denom;
95
+ const cos_vals = new Float64Array(M);
96
+ for (let i = 0; i < M; ++i) {
97
+ const n = 2 * i - denom;
98
+ cos_vals[i] = 0.5 + 0.5 * Math.cos(factor * n);
99
+ }
100
+ return cos_vals;
101
+ }
102
+
103
+ const HERTZ_TO_MEL_MAPPING = {
104
+ "htk": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)),
105
+ "kaldi": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)),
106
+ "slaney": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) =>
107
+ freq >= min_log_hertz
108
+ ? min_log_mel + Math.log(freq / min_log_hertz) * logstep
109
+ : 3.0 * freq / 200.0,
110
+ }
111
+
112
+ /**
113
+ * @template {Float32Array|Float64Array|number} T
114
+ * @param {T} freq
115
+ * @param {string} [mel_scale]
116
+ * @returns {T}
117
+ */
118
+ function hertz_to_mel(freq, mel_scale = "htk") {
119
+ const fn = HERTZ_TO_MEL_MAPPING[mel_scale];
120
+ if (!fn) {
121
+ throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
122
+ }
123
+
124
+ return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x));
125
+ }
126
+
127
+ const MEL_TO_HERTZ_MAPPING = {
128
+ "htk": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),
129
+ "kaldi": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0),
130
+ "slaney": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel
131
+ ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))
132
+ : 200.0 * mels / 3.0,
133
+ }
134
+
135
+ /**
136
+ * @template {Float32Array|Float64Array|number} T
137
+ * @param {T} mels
138
+ * @param {string} [mel_scale]
139
+ * @returns {T}
140
+ */
141
+ function mel_to_hertz(mels, mel_scale = "htk") {
142
+ const fn = MEL_TO_HERTZ_MAPPING[mel_scale];
143
+ if (!fn) {
144
+ throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
145
+ }
146
+
147
+ return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x));
148
+ }
149
+
150
+ /**
151
+ * Creates a triangular filter bank.
152
+ *
153
+ * Adapted from torchaudio and librosa.
154
+ *
155
+ * @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.
156
+ * @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.
157
+ * @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.
158
+ */
159
+ function _create_triangular_filter_bank(fft_freqs, filter_freqs) {
160
+ const filter_diff = Float64Array.from(
161
+ { length: filter_freqs.length - 1 },
162
+ (_, i) => filter_freqs[i + 1] - filter_freqs[i]
163
+ );
164
+
165
+ const slopes = Array.from({
166
+ length: fft_freqs.length
167
+ }, () => new Array(filter_freqs.length));
168
+
169
+ for (let j = 0; j < fft_freqs.length; ++j) {
170
+ const slope = slopes[j];
171
+ for (let i = 0; i < filter_freqs.length; ++i) {
172
+ slope[i] = filter_freqs[i] - fft_freqs[j];
173
+ }
174
+ }
175
+
176
+ const numFreqs = filter_freqs.length - 2;
177
+ const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length));
178
+
179
+ for (let j = 0; j < fft_freqs.length; ++j) { // 201
180
+ const slope = slopes[j];
181
+ for (let i = 0; i < numFreqs; ++i) { // 80
182
+ const down = -slope[i] / filter_diff[i];
183
+ const up = slope[i + 2] / filter_diff[i + 1];
184
+ ret[i][j] = Math.max(0, Math.min(down, up));
185
+ }
186
+ }
187
+ return ret;
188
+ }
189
+
190
+ /**
191
+ * Return evenly spaced numbers over a specified interval.
192
+ * @param {number} start The starting value of the sequence.
193
+ * @param {number} end The end value of the sequence.
194
+ * @param {number} num Number of samples to generate.
195
+ * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`.
196
+ */
197
+ function linspace(start, end, num) {
198
+ const step = (end - start) / (num - 1);
199
+ return Float64Array.from({ length: num }, (_, i) => start + step * i);
200
+ }
201
+
202
+ /**
203
+ * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and
204
+ * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters
205
+ * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these
206
+ * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.
207
+ * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`).
208
+ * @param {number} num_mel_filters Number of mel filters to generate.
209
+ * @param {number} min_frequency Lowest frequency of interest in Hz.
210
+ * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.
211
+ * @param {number} sampling_rate Sample rate of the audio waveform.
212
+ * @param {string} [norm] If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization).
213
+ * @param {string} [mel_scale] The mel frequency scale to use, `"htk"` or `"slaney"`.
214
+ * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space.
215
+ * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.
216
+ * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).
217
+ * This is a projection matrix to go from a spectrogram to a mel spectrogram.
218
+ */
219
+ export function mel_filter_bank(
220
+ num_frequency_bins,
221
+ num_mel_filters,
222
+ min_frequency,
223
+ max_frequency,
224
+ sampling_rate,
225
+ norm = null,
226
+ mel_scale = "htk",
227
+ triangularize_in_mel_space = false,
228
+ ) {
229
+ if (norm !== null && norm !== "slaney") {
230
+ throw new Error('norm must be one of null or "slaney"');
231
+ }
232
+
233
+ const mel_min = hertz_to_mel(min_frequency, mel_scale);
234
+ const mel_max = hertz_to_mel(max_frequency, mel_scale);
235
+ const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);
236
+
237
+ let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);
238
+ let fft_freqs; // frequencies of FFT bins in Hz
239
+
240
+ if (triangularize_in_mel_space) {
241
+ const fft_bin_width = sampling_rate / (num_frequency_bins * 2);
242
+ fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale);
243
+ filter_freqs = mel_freqs;
244
+ } else {
245
+ fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);
246
+ }
247
+
248
+ const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);
249
+
250
+ if (norm !== null && norm === "slaney") {
251
+ // Slaney-style mel is scaled to be approx constant energy per channel
252
+ for (let i = 0; i < num_mel_filters; ++i) {
253
+ const filter = mel_filters[i];
254
+ const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);
255
+ for (let j = 0; j < num_frequency_bins; ++j) {
256
+ // Apply this enorm to all frequency bins
257
+ filter[j] *= enorm;
258
+ }
259
+ }
260
+ }
261
+
262
+ // TODO warn if there is a zero row
263
+
264
+ return mel_filters;
265
+
266
+ }
267
+
268
+ /**
269
+ * @template {Float32Array|Float64Array} T
270
+ * Pads an array with a reflected version of itself on both ends.
271
+ * @param {T} array The array to pad.
272
+ * @param {number} left The amount of padding to add to the left.
273
+ * @param {number} right The amount of padding to add to the right.
274
+ * @returns {T} The padded array.
275
+ */
276
+ function padReflect(array, left, right) {
277
+ // @ts-ignore
278
+ const padded = new array.constructor(array.length + left + right);
279
+ const w = array.length - 1;
280
+
281
+ for (let i = 0; i < array.length; ++i) {
282
+ padded[left + i] = array[i];
283
+ }
284
+
285
+ for (let i = 1; i <= left; ++i) {
286
+ padded[left - i] = array[calculateReflectOffset(i, w)];
287
+ }
288
+
289
+ for (let i = 1; i <= right; ++i) {
290
+ padded[w + left + i] = array[calculateReflectOffset(w - i, w)];
291
+ }
292
+
293
+ return padded;
294
+ }
295
+
296
+ /**
297
+ * Helper function to compute `amplitude_to_db` and `power_to_db`.
298
+ * @template {Float32Array|Float64Array} T
299
+ * @param {T} spectrogram
300
+ * @param {number} factor
301
+ * @param {number} reference
302
+ * @param {number} min_value
303
+ * @param {number} db_range
304
+ * @returns {T}
305
+ */
306
+ function _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) {
307
+ if (reference <= 0) {
308
+ throw new Error('reference must be greater than zero');
309
+ }
310
+
311
+ if (min_value <= 0) {
312
+ throw new Error('min_value must be greater than zero');
313
+ }
314
+
315
+ reference = Math.max(min_value, reference);
316
+
317
+ const logReference = Math.log10(reference);
318
+ for (let i = 0; i < spectrogram.length; ++i) {
319
+ spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference)
320
+ }
321
+
322
+ if (db_range !== null) {
323
+ if (db_range <= 0) {
324
+ throw new Error('db_range must be greater than zero');
325
+ }
326
+ const maxValue = max(spectrogram)[0] - db_range;
327
+ for (let i = 0; i < spectrogram.length; ++i) {
328
+ spectrogram[i] = Math.max(spectrogram[i], maxValue);
329
+ }
330
+ }
331
+
332
+ return spectrogram;
333
+ }
334
+
335
+ /**
336
+ * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`,
337
+ * using basic logarithm properties for numerical stability. NOTE: Operates in-place.
338
+ *
339
+ * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
340
+ * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
341
+ * This means that large variations in energy may not sound all that different if the sound is loud to begin with.
342
+ * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
343
+ *
344
+ * @template {Float32Array|Float64Array} T
345
+ * @param {T} spectrogram The input amplitude (mel) spectrogram.
346
+ * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.
347
+ * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.
348
+ * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels,
349
+ * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.
350
+ * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the
351
+ * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
352
+ * @returns {T} The modified spectrogram in decibels.
353
+ */
354
+ function amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) {
355
+ return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range);
356
+ }
357
+
358
+ /**
359
+ * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`,
360
+ * using basic logarithm properties for numerical stability. NOTE: Operates in-place.
361
+ *
362
+ * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
363
+ * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
364
+ * This means that large variations in energy may not sound all that different if the sound is loud to begin with.
365
+ * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
366
+ *
367
+ * Based on the implementation of `librosa.power_to_db`.
368
+ *
369
+ * @template {Float32Array|Float64Array} T
370
+ * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!
371
+ * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.
372
+ * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.
373
+ * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels,
374
+ * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.
375
+ * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the
376
+ * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
377
+ * @returns {T} The modified spectrogram in decibels.
378
+ */
379
+ function power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) {
380
+ return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range);
381
+ }
382
+
383
+ /**
384
+ * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
385
+ *
386
+ * This function can create the following kinds of spectrograms:
387
+ * - amplitude spectrogram (`power = 1.0`)
388
+ * - power spectrogram (`power = 2.0`)
389
+ * - complex-valued spectrogram (`power = None`)
390
+ * - log spectrogram (use `log_mel` argument)
391
+ * - mel spectrogram (provide `mel_filters`)
392
+ * - log-mel spectrogram (provide `mel_filters` and `log_mel`)
393
+ *
394
+ * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame.
395
+ * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
396
+ * typically the next power of two.
397
+ *
398
+ * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform.
399
+ * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be
400
+ * shorter than `frame_length`, but we're assuming the array has already been zero-padded.
401
+ * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`).
402
+ * @param {number} hop_length The stride between successive analysis frames in samples.
403
+ * @param {Object} options
404
+ * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.
405
+ * For optimal speed, this should be a power of two. If `null`, uses `frame_length`.
406
+ * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers.
407
+ * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame
408
+ * `t` will start at time `t * hop_length`.
409
+ * @param {string} [options.pad_mode="reflect"] Padding mode used when `center` is `true`. Possible values are: `"constant"` (pad with zeros),
410
+ * `"edge"` (pad with edge values), `"reflect"` (pads with mirrored values).
411
+ * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`
412
+ * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins.
413
+ * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT.
414
+ * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`.
415
+ * If supplied, applies this filter bank to create a mel spectrogram.
416
+ * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks.
417
+ * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are:
418
+ * `null` (don't convert), `"log"` (take the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels).
419
+ * Can only be used when `power` is not `null`.
420
+ * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set
421
+ * the loudest part to 0 dB. Must be greater than zero.
422
+ * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`.
423
+ * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB.
424
+ * Must be greater than zero.
425
+ * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
426
+ * peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
427
+ * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in
428
+ * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.
429
+ * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value.
430
+ * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames.
431
+ * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.
432
+ * @returns {{data: Float32Array, dims: number[]}} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).
433
+ */
434
+ export function spectrogram(
435
+ waveform,
436
+ window,
437
+ frame_length,
438
+ hop_length,
439
+ {
440
+ fft_length = null,
441
+ power = 1.0,
442
+ center = true,
443
+ pad_mode = "reflect",
444
+ onesided = true,
445
+ preemphasis = null,
446
+ mel_filters = null,
447
+ mel_floor = 1e-10,
448
+ log_mel = null,
449
+ reference = 1.0,
450
+ min_value = 1e-10,
451
+ db_range = null,
452
+ remove_dc_offset = null,
453
+
454
+ // Custom parameters for efficiency reasons
455
+ max_num_frames = null,
456
+ do_pad = true,
457
+ transpose = false,
458
+ } = {}
459
+ ) {
460
+ const window_length = window.length;
461
+ if (fft_length === null) {
462
+ fft_length = frame_length;
463
+ }
464
+ if (frame_length > fft_length) {
465
+ throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`)
466
+ }
467
+
468
+ if (window_length !== frame_length) {
469
+ throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`);
470
+ }
471
+
472
+ if (hop_length <= 0) {
473
+ throw new Error("hop_length must be greater than zero");
474
+ }
475
+
476
+ if (power === null && mel_filters !== null) {
477
+ throw new Error(
478
+ "You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. " +
479
+ "Specify `power` to fix this issue."
480
+ );
481
+ }
482
+
483
+ if (center) {
484
+ if (pad_mode !== 'reflect') {
485
+ throw new Error(`pad_mode="${pad_mode}" not implemented yet.`)
486
+ }
487
+ const half_window = Math.floor((fft_length - 1) / 2) + 1;
488
+ waveform = padReflect(waveform, half_window, half_window);
489
+ }
490
+
491
+ // split waveform into frames of frame_length size
492
+ const num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length))
493
+
494
+ const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length
495
+
496
+ let d1 = num_frames;
497
+ let d1Max = num_frames;
498
+
499
+ // If maximum number of frames is provided, we must either pad or truncate
500
+ if (max_num_frames !== null) {
501
+ if (max_num_frames > num_frames) { // input is too short, so we pad
502
+ if (do_pad) {
503
+ d1Max = max_num_frames;
504
+ }
505
+ } else { // input is too long, so we truncate
506
+ d1Max = d1 = max_num_frames;
507
+ }
508
+ }
509
+
510
+ // Preallocate arrays to store output.
511
+ const fft = new FFT(fft_length);
512
+ const inputBuffer = new Float64Array(fft_length);
513
+ const outputBuffer = new Float64Array(fft.outputBufferSize);
514
+ const magnitudes = new Array(d1);
515
+
516
+ for (let i = 0; i < d1; ++i) {
517
+ // Populate buffer with waveform data
518
+ const offset = i * hop_length;
519
+ for (let j = 0; j < frame_length; ++j) {
520
+ inputBuffer[j] = waveform[offset + j];
521
+ }
522
+
523
+ if (remove_dc_offset) {
524
+ let sum = 0;
525
+ for (let j = 0; j < frame_length; ++j) {
526
+ sum += inputBuffer[j];
527
+ }
528
+ const mean = sum / frame_length;
529
+ for (let j = 0; j < frame_length; ++j) {
530
+ inputBuffer[j] -= mean;
531
+ }
532
+ }
533
+
534
+ if (preemphasis !== null) {
535
+ // Done in reverse to avoid copies and distructive modification
536
+ for (let j = frame_length - 1; j >= 1; --j) {
537
+ inputBuffer[j] -= preemphasis * inputBuffer[j - 1];
538
+ }
539
+ inputBuffer[0] *= 1 - preemphasis;
540
+ }
541
+
542
+ for (let j = 0; j < window.length; ++j) {
543
+ inputBuffer[j] *= window[j];
544
+ }
545
+
546
+ fft.realTransform(outputBuffer, inputBuffer);
547
+
548
+ // compute magnitudes
549
+ const row = new Array(num_frequency_bins);
550
+ for (let j = 0; j < row.length; ++j) {
551
+ const j2 = j << 1;
552
+ row[j] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;
553
+ }
554
+ magnitudes[i] = row;
555
+ }
556
+
557
+ if (power !== null && power !== 2) {
558
+ // slight optimization to not sqrt
559
+ const pow = 2 / power; // we use 2 since we already squared
560
+ for (let i = 0; i < magnitudes.length; ++i) {
561
+ const magnitude = magnitudes[i];
562
+ for (let j = 0; j < magnitude.length; ++j) {
563
+ magnitude[j] **= pow;
564
+ }
565
+ }
566
+ }
567
+
568
+ // TODO: What if `mel_filters` is null?
569
+ const num_mel_filters = mel_filters.length;
570
+
571
+ // Only here do we create Float32Array
572
+ const mel_spec = new Float32Array(num_mel_filters * d1Max);
573
+
574
+ // Perform matrix muliplication:
575
+ // mel_spec = mel_filters @ magnitudes.T
576
+ // - mel_filters.shape=(80, 201)
577
+ // - magnitudes.shape=(3000, 201) => - magnitudes.T.shape=(201, 3000)
578
+ // - mel_spec.shape=(80, 3000)
579
+ const dims = transpose ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max];
580
+ for (let i = 0; i < num_mel_filters; ++i) { // num melfilters (e.g., 80)
581
+ const filter = mel_filters[i];
582
+ for (let j = 0; j < d1; ++j) { // num frames (e.g., 3000)
583
+ const magnitude = magnitudes[j];
584
+
585
+ let sum = 0;
586
+ for (let k = 0; k < num_frequency_bins; ++k) { // num frequency bins (e.g., 201)
587
+ sum += filter[k] * magnitude[k];
588
+ }
589
+
590
+ mel_spec[
591
+ transpose
592
+ ? j * num_mel_filters + i
593
+ : i * d1 + j
594
+ ] = Math.max(mel_floor, sum);
595
+ }
596
+ }
597
+
598
+ if (power !== null && log_mel !== null) {
599
+ const o = Math.min(mel_spec.length, d1 * num_mel_filters);
600
+ switch (log_mel) {
601
+ case 'log':
602
+ for (let i = 0; i < o; ++i) {
603
+ mel_spec[i] = Math.log(mel_spec[i]);
604
+ }
605
+ break;
606
+ case 'log10':
607
+ for (let i = 0; i < o; ++i) {
608
+ mel_spec[i] = Math.log10(mel_spec[i]);
609
+ }
610
+ break;
611
+ case 'dB':
612
+ if (power === 1.0) {
613
+ // NOTE: operates in-place
614
+ amplitude_to_db(mel_spec, reference, min_value, db_range);
615
+ } else if (power === 2.0) {
616
+ power_to_db(mel_spec, reference, min_value, db_range);
617
+ } else {
618
+ throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`)
619
+ }
620
+ break;
621
+ default:
622
+ throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`);
623
+ }
624
+ }
625
+
626
+ return { data: mel_spec, dims };
627
+ }
628
+
629
+ /**
630
+ * Returns an array containing the specified window.
631
+ * @param {number} window_length The length of the window in samples.
632
+ * @param {string} name The name of the window function.
633
+ * @param {Object} options Additional options.
634
+ * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric.
635
+ * @param {number} [options.frame_length=null] The length of the analysis frames in samples.
636
+ * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded.
637
+ * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
638
+ * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.
639
+ */
640
+ export function window_function(window_length, name, {
641
+ periodic = true,
642
+ frame_length = null,
643
+ center = true,
644
+ } = {}) {
645
+ const length = periodic ? window_length + 1 : window_length;
646
+ let window;
647
+ switch (name) {
648
+ case 'boxcar':
649
+ window = new Float64Array(length).fill(1.0);
650
+ break;
651
+ case 'hann':
652
+ case 'hann_window':
653
+ window = hanning(length);
654
+ break;
655
+ case 'povey':
656
+ window = hanning(length).map(x => Math.pow(x, 0.85));
657
+ break;
658
+ default:
659
+ throw new Error(`Unknown window type ${name}.`);
660
+ }
661
+ if (periodic) {
662
+ window = window.subarray(0, window_length);
663
+ }
664
+ if (frame_length === null) {
665
+ return window;
666
+ }
667
+ if (window_length > frame_length) {
668
+ throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);
669
+ }
670
+
671
+ return window;
672
+ }