@huggingface/transformers 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +376 -0
  3. package/dist/ort-wasm-simd-threaded.jsep.wasm +0 -0
  4. package/dist/transformers.cjs +30741 -0
  5. package/dist/transformers.cjs.map +1 -0
  6. package/dist/transformers.js +33858 -0
  7. package/dist/transformers.js.map +1 -0
  8. package/dist/transformers.min.cjs +173 -0
  9. package/dist/transformers.min.cjs.map +1 -0
  10. package/dist/transformers.min.js +231 -0
  11. package/dist/transformers.min.js.map +1 -0
  12. package/package.json +92 -0
  13. package/src/backends/onnx.js +151 -0
  14. package/src/configs.js +360 -0
  15. package/src/env.js +152 -0
  16. package/src/generation/configuration_utils.js +381 -0
  17. package/src/generation/logits_process.js +716 -0
  18. package/src/generation/logits_sampler.js +204 -0
  19. package/src/generation/parameters.js +35 -0
  20. package/src/generation/stopping_criteria.js +156 -0
  21. package/src/generation/streamers.js +212 -0
  22. package/src/models/whisper/common_whisper.js +151 -0
  23. package/src/models/whisper/generation_whisper.js +89 -0
  24. package/src/models.js +7028 -0
  25. package/src/ops/registry.js +92 -0
  26. package/src/pipelines.js +3341 -0
  27. package/src/processors.js +2614 -0
  28. package/src/tokenizers.js +4395 -0
  29. package/src/transformers.js +28 -0
  30. package/src/utils/audio.js +704 -0
  31. package/src/utils/constants.js +2 -0
  32. package/src/utils/core.js +149 -0
  33. package/src/utils/data-structures.js +445 -0
  34. package/src/utils/devices.js +11 -0
  35. package/src/utils/dtypes.js +62 -0
  36. package/src/utils/generic.js +35 -0
  37. package/src/utils/hub.js +671 -0
  38. package/src/utils/image.js +745 -0
  39. package/src/utils/maths.js +1050 -0
  40. package/src/utils/tensor.js +1378 -0
  41. package/types/backends/onnx.d.ts +26 -0
  42. package/types/backends/onnx.d.ts.map +1 -0
  43. package/types/configs.d.ts +59 -0
  44. package/types/configs.d.ts.map +1 -0
  45. package/types/env.d.ts +106 -0
  46. package/types/env.d.ts.map +1 -0
  47. package/types/generation/configuration_utils.d.ts +320 -0
  48. package/types/generation/configuration_utils.d.ts.map +1 -0
  49. package/types/generation/logits_process.d.ts +354 -0
  50. package/types/generation/logits_process.d.ts.map +1 -0
  51. package/types/generation/logits_sampler.d.ts +51 -0
  52. package/types/generation/logits_sampler.d.ts.map +1 -0
  53. package/types/generation/parameters.d.ts +47 -0
  54. package/types/generation/parameters.d.ts.map +1 -0
  55. package/types/generation/stopping_criteria.d.ts +81 -0
  56. package/types/generation/stopping_criteria.d.ts.map +1 -0
  57. package/types/generation/streamers.d.ts +81 -0
  58. package/types/generation/streamers.d.ts.map +1 -0
  59. package/types/models/whisper/common_whisper.d.ts +8 -0
  60. package/types/models/whisper/common_whisper.d.ts.map +1 -0
  61. package/types/models/whisper/generation_whisper.d.ts +76 -0
  62. package/types/models/whisper/generation_whisper.d.ts.map +1 -0
  63. package/types/models.d.ts +3845 -0
  64. package/types/models.d.ts.map +1 -0
  65. package/types/ops/registry.d.ts +11 -0
  66. package/types/ops/registry.d.ts.map +1 -0
  67. package/types/pipelines.d.ts +2403 -0
  68. package/types/pipelines.d.ts.map +1 -0
  69. package/types/processors.d.ts +917 -0
  70. package/types/processors.d.ts.map +1 -0
  71. package/types/tokenizers.d.ts +999 -0
  72. package/types/tokenizers.d.ts.map +1 -0
  73. package/types/transformers.d.ts +13 -0
  74. package/types/transformers.d.ts.map +1 -0
  75. package/types/utils/audio.d.ts +130 -0
  76. package/types/utils/audio.d.ts.map +1 -0
  77. package/types/utils/constants.d.ts +2 -0
  78. package/types/utils/constants.d.ts.map +1 -0
  79. package/types/utils/core.d.ts +91 -0
  80. package/types/utils/core.d.ts.map +1 -0
  81. package/types/utils/data-structures.d.ts +236 -0
  82. package/types/utils/data-structures.d.ts.map +1 -0
  83. package/types/utils/devices.d.ts +8 -0
  84. package/types/utils/devices.d.ts.map +1 -0
  85. package/types/utils/dtypes.d.ts +22 -0
  86. package/types/utils/dtypes.d.ts.map +1 -0
  87. package/types/utils/generic.d.ts +11 -0
  88. package/types/utils/generic.d.ts.map +1 -0
  89. package/types/utils/hub.d.ts +191 -0
  90. package/types/utils/hub.d.ts.map +1 -0
  91. package/types/utils/image.d.ts +119 -0
  92. package/types/utils/image.d.ts.map +1 -0
  93. package/types/utils/maths.d.ts +280 -0
  94. package/types/utils/maths.d.ts.map +1 -0
  95. package/types/utils/tensor.d.ts +392 -0
  96. package/types/utils/tensor.d.ts.map +1 -0
@@ -0,0 +1,4395 @@
1
+
2
+ /**
3
+ * @file Tokenizers are used to prepare textual inputs for a model.
4
+ *
5
+ * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.
6
+ * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.
7
+ * ```javascript
8
+ * import { AutoTokenizer } from '@huggingface/transformers';
9
+ *
10
+ * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
11
+ * const { input_ids } = await tokenizer('I love transformers!');
12
+ * // Tensor {
13
+ * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],
14
+ * // dims: [1, 6],
15
+ * // type: 'int64',
16
+ * // size: 6,
17
+ * // }
18
+ * ```
19
+ *
20
+ * @module tokenizers
21
+ */
22
+ import {
23
+ Callable,
24
+ } from './utils/generic.js';
25
+
26
+ import {
27
+ reverseDictionary,
28
+ escapeRegExp,
29
+ isIntegralNumber,
30
+ mergeArrays,
31
+ } from './utils/core.js';
32
+
33
+ import {
34
+ getModelJSON,
35
+ } from './utils/hub.js';
36
+
37
+ import { max, min, round } from './utils/maths.js';
38
+ import { Tensor } from './utils/tensor.js';
39
+
40
+ import {
41
+ PriorityQueue,
42
+ TokenLattice,
43
+ CharTrie,
44
+ } from './utils/data-structures.js';
45
+
46
+ import { Template } from '@huggingface/jinja';
47
+
48
+ import {
49
+ WHISPER_LANGUAGE_MAPPING,
50
+ whisper_language_to_code,
51
+ } from './models/whisper/common_whisper.js';
52
+ import { GITHUB_ISSUE_URL } from './utils/constants.js';
53
+
54
+ /**
55
+ * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.
56
+ * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.
57
+ * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions
58
+ */
59
+
60
+ /**
61
+ * Loads a tokenizer from the specified path.
62
+ * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.
63
+ * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
64
+ * @returns {Promise<any[]>} A promise that resolves with information about the loaded tokenizer.
65
+ */
66
+ async function loadTokenizer(pretrained_model_name_or_path, options) {
67
+
68
+ const info = await Promise.all([
69
+ getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),
70
+ getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),
71
+ ])
72
+
73
+ // Override legacy option if `options.legacy` is not null
74
+ if (options.legacy !== null) {
75
+ info[1].legacy = options.legacy;
76
+ }
77
+ return info;
78
+ }
79
+
80
+
81
+ /**
82
+ * Helper function to split a string on a regex, but keep the delimiters.
83
+ * This is required, because the JavaScript `.split()` method does not keep the delimiters,
84
+ * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).
85
+ * @param {string} text The text to split.
86
+ * @param {RegExp} regex The regex to split on.
87
+ * @returns {string[]} The split string.
88
+ */
89
+ function regexSplit(text, regex) {
90
+ const result = [];
91
+ let prev = 0;
92
+ for (const match of text.matchAll(regex)) {
93
+ const fullMatch = match[0];
94
+ if (prev < match.index) {
95
+ result.push(text.slice(prev, match.index));
96
+ }
97
+ if (fullMatch.length > 0) {
98
+ result.push(fullMatch);
99
+ }
100
+ prev = match.index + fullMatch.length;
101
+ }
102
+ if (prev < text.length) {
103
+ result.push(text.slice(prev));
104
+ }
105
+ return result;
106
+ }
107
+
108
+
109
+ /**
110
+ * Helper method to construct a pattern from a config object.
111
+ * @param {Object} pattern The pattern object.
112
+ * @param {boolean} invert Whether to invert the pattern.
113
+ * @returns {RegExp|null} The compiled pattern.
114
+ */
115
+ function createPattern(pattern, invert = true) {
116
+
117
+ if (pattern.Regex !== undefined) {
118
+ // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \# or \& or \~).
119
+ // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).
120
+ // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.
121
+ // For this reason, it is necessary to remove these backslashes before creating the regex.
122
+ // See https://stackoverflow.com/a/63007777/13989043 for more information
123
+ let regex = pattern.Regex.replace(/\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary
124
+
125
+ // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.
126
+ for (const [key, value] of PROBLEMATIC_REGEX_MAP) {
127
+ regex = regex.replaceAll(key, value);
128
+ }
129
+
130
+ return new RegExp(regex, 'gu');
131
+
132
+ } else if (pattern.String !== undefined) {
133
+ const escaped = escapeRegExp(pattern.String);
134
+ // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()
135
+ return new RegExp(invert ? escaped : `(${escaped})`, 'gu');
136
+
137
+ } else {
138
+ console.warn('Unknown pattern type:', pattern)
139
+ return null;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Helper function to convert an Object to a Map
145
+ * @param {Object} obj The object to convert.
146
+ * @returns {Map<string, any>} The map.
147
+ */
148
+ function objectToMap(obj) {
149
+ return new Map(Object.entries(obj));
150
+ }
151
+
152
+ /**
153
+ * Helper function to convert a tensor to a list before decoding.
154
+ * @param {Tensor} tensor The tensor to convert.
155
+ * @returns {number[]} The tensor as a list.
156
+ */
157
+ function prepareTensorForDecode(tensor) {
158
+ const dims = tensor.dims;
159
+ switch (dims.length) {
160
+ case 1:
161
+ return tensor.tolist();
162
+ case 2:
163
+ if (dims[0] !== 1) {
164
+ throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');
165
+ }
166
+ return tensor.tolist()[0];
167
+ default:
168
+ throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms
174
+ * @param {string} text The text to clean up.
175
+ * @returns {string} The cleaned up text.
176
+ */
177
+ function clean_up_tokenization(text) {
178
+ // Clean up a list of simple English tokenization artifacts
179
+ // like spaces before punctuations and abbreviated forms
180
+ return text.replace(/ \./g, '.')
181
+ .replace(/ \?/g, '?')
182
+ .replace(/ \!/g, '!')
183
+ .replace(/ ,/g, ',')
184
+ .replace(/ \' /g, "'")
185
+ .replace(/ n\'t/g, "n't")
186
+ .replace(/ \'m/g, "'m")
187
+ .replace(/ \'s/g, "'s")
188
+ .replace(/ \'ve/g, "'ve")
189
+ .replace(/ \'re/g, "'re");
190
+ }
191
+
192
+ /**
193
+ * Helper function to remove accents from a string.
194
+ * @param {string} text The text to remove accents from.
195
+ * @returns {string} The text with accents removed.
196
+ */
197
+ function remove_accents(text) {
198
+ return text.replace(/[\u0300-\u036f]/g, '');
199
+ }
200
+
201
+ /**
202
+ * Helper function to lowercase a string and remove accents.
203
+ * @param {string} text The text to lowercase and remove accents from.
204
+ * @returns {string} The lowercased text with accents removed.
205
+ */
206
+ function lowercase_and_remove_accent(text) {
207
+ return remove_accents(text.toLowerCase());
208
+ }
209
+
210
+
211
+ /**
212
+ * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.
213
+ *
214
+ * A "chinese character" is defined as anything in the CJK Unicode block:
215
+ * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
216
+ *
217
+ * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.
218
+ * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.
219
+ * Those alphabets are used to write space-separated words, so they are not treated specially
220
+ * and are handled like all other languages.
221
+ *
222
+ * @param {number|bigint} cp The Unicode codepoint to check.
223
+ * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.
224
+ */
225
+ export function is_chinese_char(cp) {
226
+ return (
227
+ (cp >= 0x4E00 && cp <= 0x9FFF)
228
+ || (cp >= 0x3400 && cp <= 0x4DBF)
229
+ || (cp >= 0x20000 && cp <= 0x2A6DF)
230
+ || (cp >= 0x2A700 && cp <= 0x2B73F)
231
+ || (cp >= 0x2B740 && cp <= 0x2B81F)
232
+ || (cp >= 0x2B820 && cp <= 0x2CEAF)
233
+ || (cp >= 0xF900 && cp <= 0xFAFF)
234
+ || (cp >= 0x2F800 && cp <= 0x2FA1F)
235
+ )
236
+ }
237
+
238
+ /**
239
+ * Helper function to fuse consecutive values in an array equal to the specified value.
240
+ * @param {string[]} arr The input array
241
+ * @param {any} value The value to fuse on.
242
+ * @param {Map<string, any>} mapping The mapping from input domain to value.
243
+ */
244
+ function fuse(arr, value, mapping) {
245
+ const fused = [];
246
+ let i = 0;
247
+ while (i < arr.length) {
248
+ fused.push(arr[i])
249
+ if ((mapping.get(arr[i]) ?? value) !== value) {
250
+ ++i;
251
+ continue;
252
+ }
253
+
254
+ while (i < arr.length && (mapping.get(arr[i]) ?? value) === value) {
255
+ ++i;
256
+ }
257
+ }
258
+
259
+ return fused;
260
+ }
261
+
262
+ /**
263
+ * Split a string on whitespace.
264
+ * @param {string} text The text to split.
265
+ * @returns {string[]} The split string.
266
+ */
267
+ function whitespace_split(text) {
268
+ return text.match(/\S+/g) || [];
269
+ }
270
+
271
+ const PUNCTUATION_REGEX = '\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E';
272
+ const PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu');
273
+
274
+ // A mapping of regex patterns to their equivalent (but longer) JS-compatible versions.
275
+ const PROBLEMATIC_REGEX_MAP = new Map([
276
+ // This uses the case insensitive group modifier, which is not supported in JavaScript.
277
+ // When parsing the regex, an "Invalid group" error is thrown.
278
+ ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],
279
+ ])
280
+
281
+
282
+ /**
283
+ * Represent a token added by the user on top of the existing Model vocabulary.
284
+ * AddedToken can be configured to specify the behavior they should have in various situations like:
285
+ * - Whether they should only match single words
286
+ * - Whether to include any whitespace on its left or right
287
+ */
288
+ class AddedToken {
289
+ /**
290
+ * Creates a new instance of AddedToken.
291
+ * @param {Object} config Added token configuration object.
292
+ * @param {string} config.content The content of the added token.
293
+ * @param {number} config.id The id of the added token.
294
+ * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
295
+ * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
296
+ * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
297
+ * @param {boolean} [config.normalized=false] Whether this token should be normalized.
298
+ * @param {boolean} [config.special=false] Whether this token is special.
299
+ */
300
+ constructor(config) {
301
+ this.content = config.content;
302
+ this.id = config.id;
303
+ this.single_word = config.single_word ?? false;
304
+ this.lstrip = config.lstrip ?? false;
305
+ this.rstrip = config.rstrip ?? false;
306
+ this.special = config.special ?? false;
307
+ this.normalized = config.normalized ?? null;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Abstract base class for tokenizer models.
313
+ *
314
+ * @extends Callable
315
+ */
316
+ export class TokenizerModel extends Callable {
317
+ /**
318
+ * Creates a new instance of TokenizerModel.
319
+ * @param {Object} config The configuration object for the TokenizerModel.
320
+ */
321
+ constructor(config) {
322
+ super();
323
+ this.config = config;
324
+
325
+ /** @type {string[]} */
326
+ this.vocab = [];
327
+
328
+ /**
329
+ * A mapping of tokens to ids.
330
+ * @type {Map<string, number>}
331
+ */
332
+ this.tokens_to_ids = new Map();
333
+
334
+ this.unk_token_id = undefined;
335
+ this.unk_token = undefined;
336
+ this.end_of_word_suffix = undefined;
337
+
338
+ /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */
339
+ this.fuse_unk = this.config.fuse_unk ?? false;
340
+ }
341
+
342
+ /**
343
+ * Instantiates a new TokenizerModel instance based on the configuration object provided.
344
+ * @param {Object} config The configuration object for the TokenizerModel.
345
+ * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
346
+ * @returns {TokenizerModel} A new instance of a TokenizerModel.
347
+ * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
348
+ */
349
+ static fromConfig(config, ...args) {
350
+ switch (config.type) {
351
+ case 'WordPiece':
352
+ return new WordPieceTokenizer(config);
353
+ case 'Unigram':
354
+ // @ts-ignore
355
+ return new Unigram(config, ...args);
356
+
357
+ case 'BPE':
358
+ return new BPE(config);
359
+
360
+ default:
361
+ if (config.vocab) {
362
+ // @ts-ignore
363
+ return new LegacyTokenizerModel(config, ...args);
364
+ }
365
+ throw new Error(`Unknown TokenizerModel type: ${config.type}`);
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Internal function to call the TokenizerModel instance.
371
+ * @param {string[]} tokens The tokens to encode.
372
+ * @returns {string[]} The encoded token IDs.
373
+ */
374
+ _call(tokens) {
375
+ let ids = this.encode(tokens);
376
+ if (this.fuse_unk) {
377
+ // Fuse unknown tokens
378
+ ids = fuse(ids, this.unk_token_id, this.tokens_to_ids);
379
+ }
380
+ return ids;
381
+ }
382
+
383
+ /**
384
+ * Encodes a list of tokens into a list of token IDs.
385
+ * @param {string[]} tokens The tokens to encode.
386
+ * @returns {string[]} The encoded tokens.
387
+ * @throws Will throw an error if not implemented in a subclass.
388
+ */
389
+ encode(tokens) {
390
+ throw Error("encode should be implemented in subclass.")
391
+ }
392
+
393
+ /**
394
+ * Converts a list of tokens into a list of token IDs.
395
+ * @param {string[]} tokens The tokens to convert.
396
+ * @returns {number[]} The converted token IDs.
397
+ */
398
+ convert_tokens_to_ids(tokens) {
399
+ return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);
400
+ }
401
+
402
+ /**
403
+ * Converts a list of token IDs into a list of tokens.
404
+ * @param {number[]|bigint[]} ids The token IDs to convert.
405
+ * @returns {string[]} The converted tokens.
406
+ */
407
+ convert_ids_to_tokens(ids) {
408
+ return ids.map(i => this.vocab[i] ?? this.unk_token);
409
+ }
410
+ }
411
+
412
+ /**
413
+ * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.
414
+ * @extends TokenizerModel
415
+ */
416
+ class WordPieceTokenizer extends TokenizerModel {
417
+ /**
418
+ * @param {Object} config The configuration object.
419
+ * @param {Object} config.vocab A mapping of tokens to ids.
420
+ * @param {string} config.unk_token The unknown token string.
421
+ * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.
422
+ * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.
423
+ */
424
+ constructor(config) {
425
+ super(config);
426
+ /**
427
+ * A mapping of tokens to ids.
428
+ * @type {Map<string, number>}
429
+ */
430
+ this.tokens_to_ids = objectToMap(config.vocab);
431
+
432
+ /**
433
+ * The id of the unknown token.
434
+ * @type {number}
435
+ */
436
+ this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
437
+
438
+ /**
439
+ * The unknown token string.
440
+ * @type {string}
441
+ */
442
+ this.unk_token = config.unk_token;
443
+
444
+ /**
445
+ * The maximum number of characters allowed per word.
446
+ * @type {number}
447
+ */
448
+ this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;
449
+
450
+ /**
451
+ * An array of tokens.
452
+ * @type {string[]}
453
+ */
454
+ this.vocab = new Array(this.tokens_to_ids.size);
455
+ for (const [key, value] of this.tokens_to_ids) {
456
+ this.vocab[value] = key;
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Encodes an array of tokens using WordPiece encoding.
462
+ * @param {string[]} tokens The tokens to encode.
463
+ * @returns {string[]} An array of encoded tokens.
464
+ */
465
+ encode(tokens) {
466
+ const outputTokens = [];
467
+ for (const token of tokens) {
468
+ const chars = [...token];
469
+ if (chars.length > this.max_input_chars_per_word) {
470
+ outputTokens.push(this.unk_token);
471
+ continue;
472
+ }
473
+
474
+ let isUnknown = false;
475
+ let start = 0;
476
+ const subTokens = [];
477
+
478
+ while (start < chars.length) {
479
+ let end = chars.length;
480
+ let currentSubstring = null;
481
+ while (start < end) {
482
+ let substr = chars.slice(start, end).join('');
483
+
484
+ if (start > 0) {
485
+ substr = this.config.continuing_subword_prefix + substr;
486
+ }
487
+ if (this.tokens_to_ids.has(substr)) {
488
+ currentSubstring = substr;
489
+ break;
490
+ }
491
+
492
+ --end;
493
+ }
494
+ if (currentSubstring === null) {
495
+ isUnknown = true;
496
+ break;
497
+ }
498
+ subTokens.push(currentSubstring);
499
+ start = end;
500
+ }
501
+ if (isUnknown) {
502
+ outputTokens.push(this.unk_token);
503
+ } else {
504
+ outputTokens.push(...subTokens);
505
+ }
506
+ }
507
+
508
+ return outputTokens;
509
+ }
510
+
511
+ }
512
+
513
+ /**
514
+ * Class representing a Unigram tokenizer model.
515
+ * @extends TokenizerModel
516
+ */
517
+ class Unigram extends TokenizerModel {
518
+ /**
519
+ * Create a new Unigram tokenizer model.
520
+ * @param {Object} config The configuration object for the Unigram model.
521
+ * @param {number} config.unk_id The ID of the unknown token
522
+ * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.
523
+ * @param {Object} moreConfig Additional configuration object for the Unigram model.
524
+ */
525
+ constructor(config, moreConfig) {
526
+ super(config);
527
+
528
+ const vocabSize = config.vocab.length;
529
+ this.vocab = new Array(vocabSize);
530
+ this.scores = new Array(vocabSize);
531
+ for (let i = 0; i < vocabSize; ++i) {
532
+ const piece = config.vocab[i];
533
+ this.vocab[i] = piece[0];
534
+ this.scores[i] = piece[1];
535
+ }
536
+
537
+ this.unk_token_id = config.unk_id;
538
+ this.unk_token = this.vocab[config.unk_id];
539
+
540
+ this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));
541
+ this.bosToken = ' '; // beginning of a sentence token
542
+
543
+ this.bosTokenId = this.tokens_to_ids.get(this.bosToken); // NOTE: may be undefined
544
+ this.eosToken = moreConfig.eos_token;
545
+
546
+ this.eosTokenId = this.tokens_to_ids.get(this.eosToken);
547
+ this.unkToken = this.vocab[this.unk_token_id];
548
+
549
+ this.minScore = min(this.scores)[0];
550
+
551
+ this.unkScore = this.minScore - 10.0;
552
+ this.scores[this.unk_token_id] = this.unkScore;
553
+
554
+ this.trie = new CharTrie();
555
+ this.trie.extend(this.vocab);
556
+
557
+ // NOTE: `fuse_unk` is hardcoded to true for Unigram models
558
+ // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119
559
+ this.fuse_unk = true;
560
+ }
561
+
562
+ /**
563
+ * Populates lattice nodes.
564
+ * @param {TokenLattice} lattice The token lattice to populate with nodes.
565
+ */
566
+ populateNodes(lattice) {
567
+ const sentence = lattice.sentence;
568
+ const len = sentence.length;
569
+ let beginPos = 0;
570
+ while (beginPos < len) {
571
+ const mblen = 1;
572
+ let hasSingleNode = false;
573
+ const tokens = [];
574
+
575
+ for (let token of this.trie.commonPrefixSearch(sentence.slice(beginPos))) {
576
+ tokens.push(token);
577
+ const tokenId = this.tokens_to_ids.get(token);
578
+ const tokenScore = this.scores[tokenId];
579
+ const n = token.length;
580
+ lattice.insert(beginPos, n, tokenScore, tokenId);
581
+ if (!hasSingleNode && n === mblen) {
582
+ hasSingleNode = true;
583
+ }
584
+ }
585
+ if (!hasSingleNode) {
586
+ lattice.insert(beginPos, mblen, this.unkScore, this.unk_token_id);
587
+ }
588
+ beginPos += mblen;
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Encodes an array of tokens into an array of subtokens using the unigram model.
594
+ *
595
+ * @param {string} normalized The normalized string.
596
+ * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.
597
+ */
598
+ tokenize(normalized) {
599
+ const lattice = new TokenLattice(normalized, this.bosTokenId, this.eosTokenId);
600
+ this.populateNodes(lattice);
601
+ return lattice.tokens();
602
+ }
603
+
604
+ /**
605
+ * Encodes an array of tokens using Unigram encoding.
606
+ * @param {string[]} tokens The tokens to encode.
607
+ * @returns {string[]} An array of encoded tokens.
608
+ */
609
+ encode(tokens) {
610
+ const toReturn = [];
611
+ for (const token of tokens) {
612
+ const tokenized = this.tokenize(token);
613
+ toReturn.push(...tokenized);
614
+ }
615
+ return toReturn;
616
+ }
617
+
618
+ }
619
+
620
+ /**
621
+ * Returns list of utf-8 byte and a mapping to unicode strings.
622
+ * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.
623
+ * @returns {Object} Object with utf-8 byte keys and unicode string values.
624
+ */
625
+ const BYTES_TO_UNICODE = (() => {
626
+ // Returns list of utf-8 byte and a mapping to unicode strings.
627
+ // We specifically avoids mapping to whitespace/control characters
628
+ // the bpe code barfs on.
629
+
630
+ const bs = [
631
+ ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
632
+ ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)),
633
+ ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0)),
634
+ ];
635
+ const cs = bs.slice();
636
+ let n = 0;
637
+ for (let b = 0; b < 256; ++b) {
638
+ if (!bs.includes(b)) {
639
+ bs.push(b);
640
+ cs.push(256 + n);
641
+ n += 1;
642
+ }
643
+ }
644
+ const ccs = cs.map(n => String.fromCharCode(n));
645
+ return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
646
+ })();
647
+
648
+ const UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);
649
+
650
+
651
+ /**
652
+ * @typedef {Object} BPENode
653
+ * @property {string} token The token associated with the node
654
+ * @property {number} bias A positional bias for the node.
655
+ * @property {number} [score] The score of the node.
656
+ * @property {BPENode} [prev] The previous node in the linked list.
657
+ * @property {BPENode} [next] The next node in the linked list.
658
+ */
659
+
660
+ /**
661
+ * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.
662
+ * @extends TokenizerModel
663
+ */
664
+ class BPE extends TokenizerModel {
665
+ /**
666
+ * Create a BPE instance.
667
+ * @param {Object} config The configuration object for BPE.
668
+ * @param {Object} config.vocab A mapping of tokens to ids.
669
+ * @param {string[]} config.merges An array of BPE merges as strings.
670
+ * @param {string} config.unk_token The unknown token used for out of vocabulary words.
671
+ * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.
672
+ * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.
673
+ * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)
674
+ * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.
675
+ */
676
+ constructor(config) {
677
+ super(config);
678
+
679
+ this.BPE_SPLIT_TOKEN = ' ';
680
+
681
+ /** @type {Map<string, number>} */
682
+ this.tokens_to_ids = objectToMap(config.vocab);
683
+
684
+ this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
685
+ this.unk_token = config.unk_token;
686
+
687
+ this.vocab = new Array(this.tokens_to_ids.size);
688
+ for (const [key, value] of this.tokens_to_ids) {
689
+ this.vocab[value] = key;
690
+ }
691
+
692
+ this.bpe_ranks = new Map(config.merges.map((x, i) => [x, i]));
693
+ this.merges = config.merges.map(x => x.split(this.BPE_SPLIT_TOKEN));
694
+
695
+ this.end_of_word_suffix = config.end_of_word_suffix;
696
+
697
+ // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)
698
+ this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;
699
+
700
+ this.byte_fallback = this.config.byte_fallback ?? false;
701
+
702
+ if (this.byte_fallback) {
703
+ this.text_encoder = new TextEncoder();
704
+ }
705
+
706
+ this.ignore_merges = this.config.ignore_merges ?? false;
707
+
708
+ /** @type {Map<string, string[]>} */
709
+ this.cache = new Map();
710
+ }
711
+
712
+ /**
713
+ * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority
714
+ * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.
715
+ * @param {string} token The token to encode.
716
+ * @returns {string[]} The BPE encoded tokens.
717
+ */
718
+ bpe(token) {
719
+ if (token.length === 0) {
720
+ return [];
721
+ }
722
+
723
+ const cached = this.cache.get(token);
724
+ if (cached !== undefined) {
725
+ return cached;
726
+ }
727
+
728
+ const word = Array.from(token);
729
+ if (this.end_of_word_suffix) {
730
+ word[word.length - 1] += this.end_of_word_suffix;
731
+ }
732
+
733
+ let result = [];
734
+ if (word.length > 1) {
735
+ // Create a priority queue to store the nodes that will be merged.
736
+ // The comparator function compares the scores of the nodes.
737
+ const queue = new PriorityQueue((a, b) => a.score < b.score);
738
+
739
+ // Construct a doubly-linked list of nodes that will be inserted into the priority queue,
740
+ // starting with the individual characters. We also populate each node with a positional
741
+ // bias to break ties in the priority queue.
742
+ let startingNode = {
743
+ token: word[0],
744
+ bias: 0,
745
+ prev: null,
746
+ next: null,
747
+ }
748
+
749
+ let previousNode = startingNode
750
+ for (let i = 1; i < word.length; ++i) {
751
+ const currentNode = {
752
+ bias: i / word.length, // Add fractional component to break ties
753
+ token: word[i],
754
+ prev: previousNode,
755
+ next: null,
756
+ }
757
+ previousNode.next = currentNode
758
+ this._add_node(queue, previousNode)
759
+ previousNode = currentNode
760
+ }
761
+
762
+ while (!queue.isEmpty()) {
763
+ // Get the next node with the highest priority
764
+ const node = queue.pop();
765
+
766
+ // Check that this merge is still possible
767
+ if (node.deleted || !node.next || node.next.deleted) continue;
768
+
769
+ // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.
770
+ // This is because they will both be replaced by a new node representing the merge result.
771
+ node.deleted = true;
772
+ node.next.deleted = true;
773
+
774
+ // Next, we fix the node that comes before the current node (i.e., left side of the merge).
775
+ if (node.prev) {
776
+
777
+ // Make a shallow copy of the previous node
778
+ const newPreviousNode = { ...node.prev };
779
+
780
+ // Mark the old previous node as deleted. This avoids erroneous merges later,
781
+ // because there may still be references to this node in the priority queue.
782
+ node.prev.deleted = true;
783
+ node.prev = newPreviousNode;
784
+
785
+ // Update the reference of the previous node, by pointing its previous node to this new previous node.
786
+ if (newPreviousNode.prev) {
787
+ newPreviousNode.prev.next = newPreviousNode;
788
+ } else {
789
+ // If the previous of the previous node does not exist, it means that
790
+ // `newPreviousNode` must be the new `startingNode`.
791
+ startingNode = newPreviousNode;
792
+ }
793
+ }
794
+
795
+ // Create a new node which represents the result of the merge.
796
+ const merged = {
797
+ token: node.token + node.next.token,
798
+ bias: node.bias,
799
+ prev: node.prev,
800
+ next: node.next.next,
801
+ }
802
+
803
+ // We now consider where we can add the new merged node to the priority queue:
804
+ // 1. prev <-> merged
805
+ if (merged.prev) {
806
+ merged.prev.next = merged;
807
+ this._add_node(queue, merged.prev);
808
+ } else {
809
+ // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.
810
+ startingNode = merged;
811
+ }
812
+
813
+ // 2. merged <-> next
814
+ if (merged.next) {
815
+ merged.next.prev = merged;
816
+ this._add_node(queue, merged);
817
+ }
818
+ }
819
+
820
+ // Traverse the linked list, starting from the `startingNode`, and collect the tokens.
821
+ for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {
822
+ result.push(currentNode.token);
823
+ }
824
+ } else {
825
+ result = word;
826
+ }
827
+
828
+ // Possibly append suffix
829
+ if (this.continuing_subword_suffix) {
830
+ // Do not append suffix to the last token
831
+ for (let i = 0; i < result.length - 1; ++i) {
832
+ result[i] += this.continuing_subword_suffix;
833
+ }
834
+ }
835
+
836
+ // Save the result to the cache
837
+ this.cache.set(token, result);
838
+
839
+ return result;
840
+ }
841
+
842
+
843
+ /**
844
+ * Helper function to add a node to the priority queue.
845
+ * @param {PriorityQueue} queue
846
+ * @param {BPENode} node
847
+ * @private
848
+ */
849
+ _add_node(queue, node) {
850
+ // `score` is a measure of the merge priority: lower means higher priority
851
+ // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)
852
+ // We also add a fractional component to the score to break ties (with the earlier character having higher priority)
853
+ const rank = this.bpe_ranks.get(node.token + this.BPE_SPLIT_TOKEN + node.next.token);
854
+ if (rank !== undefined) {
855
+ node.score = rank + node.bias;
856
+ queue.push(node);
857
+ }
858
+ }
859
+
860
+ /**
861
+ * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.
862
+ * @param {string[]} tokens The input sequence of tokens to encode.
863
+ * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.
864
+ */
865
+ encode(tokens) {
866
+ const outputTokens = [];
867
+
868
+ for (const token of tokens) {
869
+ if (this.ignore_merges && this.tokens_to_ids.has(token)) {
870
+ outputTokens.push(token);
871
+ continue;
872
+ }
873
+ const bpe_token_list = this.bpe(token);
874
+
875
+ for (const t of bpe_token_list) {
876
+ if (this.tokens_to_ids.has(t)) {
877
+ outputTokens.push(t);
878
+ } else {
879
+ if (this.byte_fallback) {
880
+ outputTokens.push(
881
+ ...Array.from(this.text_encoder.encode(t))
882
+ .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`)
883
+ );
884
+ } else {
885
+ outputTokens.push(this.unk_token);
886
+ }
887
+ }
888
+ }
889
+ }
890
+
891
+ return outputTokens;
892
+ }
893
+
894
+ }
895
+
896
+ /**
897
+ * Legacy tokenizer class for tokenizers with only a vocabulary.
898
+ */
899
+ class LegacyTokenizerModel extends TokenizerModel {
900
+ /**
901
+ * Create a LegacyTokenizerModel instance.
902
+ * @param {Object} config The configuration object for LegacyTokenizerModel.
903
+ * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.
904
+ * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.
905
+ */
906
+ constructor(config, moreConfig) {
907
+ super(config);
908
+
909
+ /**@type {Map<string, number>} */
910
+ this.tokens_to_ids = objectToMap(
911
+ moreConfig.target_lang
912
+ ? config.vocab[moreConfig.target_lang]
913
+ : config.vocab
914
+ );
915
+
916
+ this.bos_token = moreConfig.bos_token;
917
+ this.bos_token_id = this.tokens_to_ids.get(this.bos_token);
918
+
919
+ this.eos_token = moreConfig.eos_token;
920
+ this.eos_token_id = this.tokens_to_ids.get(this.eos_token);
921
+
922
+ this.pad_token = moreConfig.pad_token;
923
+ this.pad_token_id = this.tokens_to_ids.get(this.pad_token);
924
+
925
+ this.unk_token = moreConfig.unk_token;
926
+ this.unk_token_id = this.tokens_to_ids.get(this.unk_token);
927
+
928
+ this.vocab = new Array(this.tokens_to_ids.size);
929
+ for (const [key, value] of this.tokens_to_ids) {
930
+ this.vocab[value] = key;
931
+ }
932
+ }
933
+
934
+ encode(tokens) {
935
+ return tokens;
936
+ }
937
+ }
938
+
939
+
940
+ /**
941
+ * A base class for text normalization.
942
+ * @abstract
943
+ */
944
+ class Normalizer extends Callable {
945
+ /**
946
+ * @param {Object} config The configuration object for the normalizer.
947
+ */
948
+ constructor(config) {
949
+ super();
950
+ this.config = config;
951
+ }
952
+
953
+ /**
954
+ * Factory method for creating normalizers from config objects.
955
+ * @static
956
+ * @param {Object} config The configuration object for the normalizer.
957
+ * @returns {Normalizer} A Normalizer object.
958
+ * @throws {Error} If an unknown Normalizer type is specified in the config.
959
+ */
960
+ static fromConfig(config) {
961
+ if (config === null) return null;
962
+ switch (config.type) {
963
+ case 'BertNormalizer':
964
+ return new BertNormalizer(config);
965
+ case 'Precompiled':
966
+ return new Precompiled(config);
967
+ case 'Sequence':
968
+ return new NormalizerSequence(config);
969
+ case 'Replace':
970
+ return new Replace(config);
971
+ case 'NFC':
972
+ return new NFC(config);
973
+ case 'NFKC':
974
+ return new NFKC(config);
975
+ case 'NFKD':
976
+ return new NFKD(config);
977
+ case 'Strip':
978
+ return new StripNormalizer(config);
979
+ case 'StripAccents':
980
+ return new StripAccents(config);
981
+ case 'Lowercase':
982
+ return new Lowercase(config);
983
+ case 'Prepend':
984
+ return new Prepend(config);
985
+ default:
986
+ throw new Error(`Unknown Normalizer type: ${config.type}`);
987
+ }
988
+ }
989
+
990
+ /**
991
+ * Normalize the input text.
992
+ * @abstract
993
+ * @param {string} text The text to normalize.
994
+ * @returns {string} The normalized text.
995
+ * @throws {Error} If this method is not implemented in a subclass.
996
+ */
997
+ normalize(text) {
998
+ throw Error("normalize should be implemented in subclass.")
999
+ }
1000
+
1001
+ /**
1002
+ * Alias for {@link Normalizer#normalize}.
1003
+ * @param {string} text The text to normalize.
1004
+ * @returns {string} The normalized text.
1005
+ */
1006
+ _call(text) {
1007
+ return this.normalize(text);
1008
+ }
1009
+
1010
+ }
1011
+
1012
+ /**
1013
+ * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.
1014
+ * @extends Normalizer
1015
+ */
1016
+ class Replace extends Normalizer {
1017
+ /**
1018
+ * Normalize the input text by replacing the pattern with the content.
1019
+ * @param {string} text The input text to be normalized.
1020
+ * @returns {string} The normalized text after replacing the pattern with the content.
1021
+ */
1022
+ normalize(text) {
1023
+ const pattern = createPattern(this.config.pattern);
1024
+ return pattern === null
1025
+ ? text
1026
+ : text.replaceAll(pattern, this.config.content);
1027
+ }
1028
+ }
1029
+
1030
+ /**
1031
+ * A normalizer that applies Unicode normalization form C (NFC) to the input text.
1032
+ * @extends Normalizer
1033
+ */
1034
+ class NFC extends Normalizer {
1035
+ /**
1036
+ * Normalize the input text by applying Unicode normalization form C (NFC).
1037
+ * @param {string} text The input text to be normalized.
1038
+ * @returns {string} The normalized text.
1039
+ */
1040
+ normalize(text) {
1041
+ text = text.normalize('NFC')
1042
+ return text;
1043
+ }
1044
+ }
1045
+
1046
+ /**
1047
+ * NFKC Normalizer.
1048
+ * @extends Normalizer
1049
+ */
1050
+ class NFKC extends Normalizer {
1051
+ /**
1052
+ * Normalize text using NFKC normalization.
1053
+ * @param {string} text The text to be normalized.
1054
+ * @returns {string} The normalized text.
1055
+ */
1056
+ normalize(text) {
1057
+ text = text.normalize('NFKC')
1058
+ return text;
1059
+ }
1060
+ }
1061
+ /**
1062
+ * NFKD Normalizer.
1063
+ * @extends Normalizer
1064
+ */
1065
+ class NFKD extends Normalizer {
1066
+ /**
1067
+ * Normalize text using NFKD normalization.
1068
+ * @param {string} text The text to be normalized.
1069
+ * @returns {string} The normalized text.
1070
+ */
1071
+ normalize(text) {
1072
+ text = text.normalize('NFKD')
1073
+ return text;
1074
+ }
1075
+ }
1076
+
1077
+ /**
1078
+ * A normalizer that strips leading and/or trailing whitespace from the input text.
1079
+ */
1080
+ class StripNormalizer extends Normalizer {
1081
+ /**
1082
+ * Strip leading and/or trailing whitespace from the input text.
1083
+ * @param {string} text The input text.
1084
+ * @returns {string} The normalized text.
1085
+ */
1086
+ normalize(text) {
1087
+ if (this.config.strip_left && this.config.strip_right) {
1088
+ // Fast path to avoid an extra trim call
1089
+ text = text.trim();
1090
+ } else {
1091
+ if (this.config.strip_left) {
1092
+ text = text.trimStart();
1093
+ }
1094
+ if (this.config.strip_right) {
1095
+ text = text.trimEnd();
1096
+ }
1097
+ }
1098
+ return text;
1099
+ }
1100
+ }
1101
+
1102
+ /**
1103
+ * StripAccents normalizer removes all accents from the text.
1104
+ * @extends Normalizer
1105
+ */
1106
+ class StripAccents extends Normalizer {
1107
+ /**
1108
+ * Remove all accents from the text.
1109
+ * @param {string} text The input text.
1110
+ * @returns {string} The normalized text without accents.
1111
+ */
1112
+ normalize(text) {
1113
+ text = remove_accents(text);
1114
+ return text;
1115
+ }
1116
+ }
1117
+
1118
+ /**
1119
+ * A Normalizer that lowercases the input string.
1120
+ * @extends Normalizer
1121
+ */
1122
+ class Lowercase extends Normalizer {
1123
+ /**
1124
+ * Lowercases the input string.
1125
+ * @param {string} text The text to normalize.
1126
+ * @returns {string} The normalized text.
1127
+ */
1128
+ normalize(text) {
1129
+ text = text.toLowerCase();
1130
+ return text;
1131
+ }
1132
+ }
1133
+
1134
+ /**
1135
+ * A Normalizer that prepends a string to the input string.
1136
+ * @extends Normalizer
1137
+ */
1138
+ class Prepend extends Normalizer {
1139
+ /**
1140
+ * Prepends the input string.
1141
+ * @param {string} text The text to normalize.
1142
+ * @returns {string} The normalized text.
1143
+ */
1144
+ normalize(text) {
1145
+ text = this.config.prepend + text;
1146
+ return text;
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * A Normalizer that applies a sequence of Normalizers.
1152
+ * @extends Normalizer
1153
+ */
1154
+ class NormalizerSequence extends Normalizer {
1155
+ /**
1156
+ * Create a new instance of NormalizerSequence.
1157
+ * @param {Object} config The configuration object.
1158
+ * @param {Object[]} config.normalizers An array of Normalizer configuration objects.
1159
+ */
1160
+ constructor(config) {
1161
+ super(config);
1162
+ this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));
1163
+ }
1164
+ /**
1165
+ * Apply a sequence of Normalizers to the input text.
1166
+ * @param {string} text The text to normalize.
1167
+ * @returns {string} The normalized text.
1168
+ */
1169
+ normalize(text) {
1170
+ return this.normalizers.reduce((t, normalizer) => {
1171
+ return normalizer.normalize(t);
1172
+ }, text);
1173
+ }
1174
+ }
1175
+
1176
+ /**
1177
+ * A class representing a normalizer used in BERT tokenization.
1178
+ * @extends Normalizer
1179
+ */
1180
+ class BertNormalizer extends Normalizer {
1181
+ /**
1182
+ * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.
1183
+ *
1184
+ * @param {string} text The input text to tokenize.
1185
+ * @returns {string} The tokenized text with whitespace added around CJK characters.
1186
+ */
1187
+ _tokenize_chinese_chars(text) {
1188
+ /* Adds whitespace around any CJK character. */
1189
+ const output = [];
1190
+ for (let i = 0; i < text.length; ++i) {
1191
+ const char = text[i];
1192
+ const cp = char.charCodeAt(0);
1193
+ if (is_chinese_char(cp)) {
1194
+ output.push(" ");
1195
+ output.push(char);
1196
+ output.push(" ");
1197
+ } else {
1198
+ output.push(char);
1199
+ }
1200
+ }
1201
+ return output.join("");
1202
+ }
1203
+
1204
+ /**
1205
+ * Strips accents from the given text.
1206
+ * @param {string} text The text to strip accents from.
1207
+ * @returns {string} The text with accents removed.
1208
+ */
1209
+ stripAccents(text) {
1210
+ return text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
1211
+ }
1212
+
1213
+
1214
+ /**
1215
+ * Checks whether `char` is a control character.
1216
+ * @param {string} char The character to check.
1217
+ * @returns {boolean} Whether `char` is a control character.
1218
+ * @private
1219
+ */
1220
+ _is_control(char) {
1221
+ switch (char) {
1222
+ case '\t':
1223
+ case '\n':
1224
+ case '\r':
1225
+ // These are technically control characters but we count them as whitespace characters.
1226
+ return false;
1227
+
1228
+ default:
1229
+ // Check if unicode category starts with C:
1230
+ // Cc - Control
1231
+ // Cf - Format
1232
+ // Co - Private Use
1233
+ // Cs - Surrogate
1234
+ return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char);
1235
+ }
1236
+ }
1237
+
1238
+ /**
1239
+ * Performs invalid character removal and whitespace cleanup on text.
1240
+ * @param {string} text The text to clean.
1241
+ * @returns {string} The cleaned text.
1242
+ * @private
1243
+ */
1244
+ _clean_text(text) {
1245
+ const output = [];
1246
+ for (const char of text) {
1247
+ const cp = char.charCodeAt(0);
1248
+ if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {
1249
+ continue;
1250
+ }
1251
+ if (/^\s$/.test(char)) { // is whitespace
1252
+ output.push(" ");
1253
+ } else {
1254
+ output.push(char);
1255
+ }
1256
+ }
1257
+ return output.join("");
1258
+ }
1259
+ /**
1260
+ * Normalizes the given text based on the configuration.
1261
+ * @param {string} text The text to normalize.
1262
+ * @returns {string} The normalized text.
1263
+ */
1264
+ normalize(text) {
1265
+ if (this.config.clean_text) {
1266
+ text = this._clean_text(text);
1267
+ }
1268
+
1269
+ if (this.config.handle_chinese_chars) {
1270
+ text = this._tokenize_chinese_chars(text);
1271
+ }
1272
+
1273
+ if (this.config.lowercase) {
1274
+ text = text.toLowerCase();
1275
+
1276
+ if (this.config.strip_accents !== false) {
1277
+ text = this.stripAccents(text);
1278
+ }
1279
+ } else if (this.config.strip_accents) {
1280
+ text = this.stripAccents(text);
1281
+ }
1282
+
1283
+ return text;
1284
+ }
1285
+ }
1286
+
1287
+ /**
1288
+ * A callable class representing a pre-tokenizer used in tokenization. Subclasses
1289
+ * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.
1290
+ * @extends Callable
1291
+ */
1292
+ class PreTokenizer extends Callable {
1293
+ /**
1294
+ * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.
1295
+ *
1296
+ * @static
1297
+ * @param {Object} config A configuration object for the pre-tokenizer.
1298
+ * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.
1299
+ * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.
1300
+ */
1301
+ static fromConfig(config) {
1302
+ if (config === null) return null;
1303
+
1304
+ switch (config.type) {
1305
+ case 'BertPreTokenizer':
1306
+ return new BertPreTokenizer(config);
1307
+ case 'Sequence':
1308
+ return new PreTokenizerSequence(config);
1309
+ case 'Whitespace':
1310
+ return new WhitespacePreTokenizer(config);
1311
+ case 'WhitespaceSplit':
1312
+ return new WhitespaceSplit(config);
1313
+ case 'Metaspace':
1314
+ return new MetaspacePreTokenizer(config);
1315
+
1316
+ case 'ByteLevel':
1317
+ return new ByteLevelPreTokenizer(config);
1318
+ case 'Split':
1319
+ return new SplitPreTokenizer(config);
1320
+ case 'Punctuation':
1321
+ return new PunctuationPreTokenizer(config);
1322
+ case 'Digits':
1323
+ return new DigitsPreTokenizer(config);
1324
+ case 'Replace':
1325
+ return new ReplacePreTokenizer(config);
1326
+ default:
1327
+ throw new Error(`Unknown PreTokenizer type: ${config.type}`);
1328
+ }
1329
+ }
1330
+
1331
+ /**
1332
+ * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
1333
+ *
1334
+ * @abstract
1335
+ * @param {string} text The text to pre-tokenize.
1336
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1337
+ * @returns {string[]} The pre-tokenized text.
1338
+ * @throws {Error} If the method is not implemented in the subclass.
1339
+ */
1340
+ pre_tokenize_text(text, options) {
1341
+ throw Error("pre_tokenize_text should be implemented in subclass.")
1342
+ }
1343
+
1344
+ /**
1345
+ * Tokenizes the given text into pre-tokens.
1346
+ * @param {string|string[]} text The text or array of texts to pre-tokenize.
1347
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1348
+ * @returns {string[]} An array of pre-tokens.
1349
+ */
1350
+ pre_tokenize(text, options) {
1351
+ return (Array.isArray(text)
1352
+ ? text.map(x => this.pre_tokenize_text(x, options))
1353
+ : this.pre_tokenize_text(text, options)
1354
+ ).flat();
1355
+ }
1356
+
1357
+ /**
1358
+ * Alias for {@link PreTokenizer#pre_tokenize}.
1359
+ * @param {string|string[]} text The text or array of texts to pre-tokenize.
1360
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1361
+ * @returns {string[]} An array of pre-tokens.
1362
+ */
1363
+ _call(text, options) {
1364
+ return this.pre_tokenize(text, options);
1365
+ }
1366
+ }
1367
+
1368
+ /**
1369
+ * @extends PreTokenizer
1370
+ */
1371
+ class BertPreTokenizer extends PreTokenizer {
1372
+ /**
1373
+ * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme
1374
+ * similar to that used in the original implementation of BERT.
1375
+ *
1376
+ * @param {Object} config The configuration object.
1377
+ */
1378
+ constructor(config) {
1379
+ super();
1380
+ // Construct a pattern which matches the rust implementation:
1381
+ // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11
1382
+ // Equivalent to removing whitespace and splitting on punctuation (both \p{P} and other ascii characters)
1383
+ this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');
1384
+ }
1385
+ /**
1386
+ * Tokenizes a single text using the BERT pre-tokenization scheme.
1387
+ *
1388
+ * @param {string} text The text to tokenize.
1389
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1390
+ * @returns {string[]} An array of tokens.
1391
+ */
1392
+ pre_tokenize_text(text, options) {
1393
+ return text.trim().match(this.pattern) || [];
1394
+ }
1395
+ }
1396
+
1397
+ /**
1398
+ * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.
1399
+ * @extends PreTokenizer
1400
+ */
1401
+ class ByteLevelPreTokenizer extends PreTokenizer {
1402
+ /**
1403
+ * Creates a new instance of the `ByteLevelPreTokenizer` class.
1404
+ * @param {Object} config The configuration object.
1405
+ */
1406
+ constructor(config) {
1407
+ super();
1408
+ this.config = config;
1409
+
1410
+ /**
1411
+ * @type {boolean} Whether to add a leading space to the first word.
1412
+ * This allows to treat the leading word just as any other word.
1413
+ */
1414
+ this.add_prefix_space = this.config.add_prefix_space;
1415
+
1416
+ /**
1417
+ * @type {boolean} Whether the post processing step should trim offsets
1418
+ * to avoid including whitespaces.
1419
+ * @todo Use this in the pretokenization step.
1420
+ */
1421
+ this.trim_offsets = this.config.trim_offsets;
1422
+
1423
+ /**
1424
+ * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.
1425
+ * Set it to False if you want to use your own splitting. Defaults to true.
1426
+ */
1427
+ this.use_regex = this.config.use_regex ?? true;
1428
+ this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
1429
+
1430
+ this.byte_encoder = BYTES_TO_UNICODE;
1431
+ this.text_encoder = new TextEncoder();
1432
+ }
1433
+
1434
+ /**
1435
+ * Tokenizes a single piece of text using byte-level tokenization.
1436
+ * @param {string} text The text to tokenize.
1437
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1438
+ * @returns {string[]} An array of tokens.
1439
+ */
1440
+ pre_tokenize_text(text, options) {
1441
+ // Add a leading space if the option is enabled
1442
+ if (this.add_prefix_space && !text.startsWith(' ')) {
1443
+ text = ' ' + text;
1444
+ }
1445
+
1446
+ // Split on whitespace and punctuation
1447
+ const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];
1448
+
1449
+ // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
1450
+ return tokens.map(
1451
+ token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')
1452
+ );
1453
+ }
1454
+ }
1455
+
1456
+ /**
1457
+ * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior
1458
+ */
1459
+
1460
+ /**
1461
+ * Splits text using a given pattern.
1462
+ * @extends PreTokenizer
1463
+ */
1464
+ class SplitPreTokenizer extends PreTokenizer {
1465
+ /**
1466
+ * @param {Object} config The configuration options for the pre-tokenizer.
1467
+ * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
1468
+ * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.
1469
+ * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.
1470
+ * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1471
+ * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.
1472
+ */
1473
+ constructor(config) {
1474
+ super();
1475
+ this.config = config;
1476
+ // TODO support all behaviours (config.behavior)
1477
+
1478
+ this.pattern = createPattern(this.config.pattern, this.config.invert);
1479
+ }
1480
+
1481
+ /**
1482
+ * Tokenizes text by splitting it using the given pattern.
1483
+ * @param {string} text The text to tokenize.
1484
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1485
+ * @returns {string[]} An array of tokens.
1486
+ */
1487
+ pre_tokenize_text(text, options) {
1488
+ if (this.pattern === null) {
1489
+ return [];
1490
+ }
1491
+
1492
+ if (this.config.invert) {
1493
+ return text.match(this.pattern) || [];
1494
+ } else {
1495
+ return regexSplit(text, this.pattern);
1496
+ }
1497
+ }
1498
+ }
1499
+
1500
+ /**
1501
+ * Splits text based on punctuation.
1502
+ * @extends PreTokenizer
1503
+ */
1504
+ class PunctuationPreTokenizer extends PreTokenizer {
1505
+ /**
1506
+ * @param {Object} config The configuration options for the pre-tokenizer.
1507
+ * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1508
+ */
1509
+ constructor(config) {
1510
+ super();
1511
+ this.config = config;
1512
+ this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');
1513
+ }
1514
+
1515
+ /**
1516
+ * Tokenizes text by splitting it using the given pattern.
1517
+ * @param {string} text The text to tokenize.
1518
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1519
+ * @returns {string[]} An array of tokens.
1520
+ */
1521
+ pre_tokenize_text(text, options) {
1522
+ return text.match(this.pattern) || [];
1523
+ }
1524
+ }
1525
+
1526
+
1527
+ /**
1528
+ * Splits text based on digits.
1529
+ * @extends PreTokenizer
1530
+ */
1531
+ class DigitsPreTokenizer extends PreTokenizer {
1532
+ /**
1533
+ * @param {Object} config The configuration options for the pre-tokenizer.
1534
+ * @param {boolean} config.individual_digits Whether to split on individual digits.
1535
+ */
1536
+ constructor(config) {
1537
+ super();
1538
+ this.config = config;
1539
+
1540
+ // Construct a pattern which matches the rust implementation:
1541
+ const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? '' : '+'}`;
1542
+ this.pattern = new RegExp(digit_pattern, 'gu');
1543
+ }
1544
+
1545
+ /**
1546
+ * Tokenizes text by splitting it using the given pattern.
1547
+ * @param {string} text The text to tokenize.
1548
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1549
+ * @returns {string[]} An array of tokens.
1550
+ */
1551
+ pre_tokenize_text(text, options) {
1552
+ return text.match(this.pattern) || [];
1553
+ }
1554
+ }
1555
+
1556
+ /**
1557
+ * @typedef {Object} PostProcessedOutput
1558
+ * @property {string[]} tokens List of token produced by the post-processor.
1559
+ * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.
1560
+ */
1561
+
1562
+
1563
+ /**
1564
+ * @typedef {Object} EncodingSingle
1565
+ * @property {number[]} input_ids List of token ids to be fed to a model.
1566
+ * @property {number[]} attention_mask List of token type ids to be fed to a model
1567
+ * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model
1568
+ */
1569
+
1570
+
1571
+ /**
1572
+ * @extends Callable
1573
+ */
1574
+ class PostProcessor extends Callable {
1575
+
1576
+ /**
1577
+ * @param {Object} config The configuration for the post-processor.
1578
+ */
1579
+ constructor(config) {
1580
+ super();
1581
+ this.config = config;
1582
+ }
1583
+
1584
+ /**
1585
+ * Factory method to create a PostProcessor object from a configuration object.
1586
+ *
1587
+ * @param {Object} config Configuration object representing a PostProcessor.
1588
+ * @returns {PostProcessor} A PostProcessor object created from the given configuration.
1589
+ * @throws {Error} If an unknown PostProcessor type is encountered.
1590
+ */
1591
+ static fromConfig(config) {
1592
+ if (config === null) return null;
1593
+ switch (config.type) {
1594
+ case 'TemplateProcessing':
1595
+ return new TemplateProcessing(config);
1596
+
1597
+ case 'ByteLevel':
1598
+ return new ByteLevelPostProcessor(config);
1599
+
1600
+ case 'RobertaProcessing':
1601
+ return new RobertaProcessing(config);
1602
+ case 'BertProcessing':
1603
+ return new BertProcessing(config);
1604
+
1605
+ case 'Sequence':
1606
+ return new PostProcessorSequence(config);
1607
+ default:
1608
+ throw new Error(`Unknown PostProcessor type: ${config.type}`);
1609
+ }
1610
+ }
1611
+
1612
+ /**
1613
+ * Method to be implemented in subclass to apply post-processing on the given tokens.
1614
+ *
1615
+ * @param {Array} tokens The input tokens to be post-processed.
1616
+ * @param {...*} args Additional arguments required by the post-processing logic.
1617
+ * @returns {PostProcessedOutput} The post-processed tokens.
1618
+ * @throws {Error} If the method is not implemented in subclass.
1619
+ */
1620
+ post_process(tokens, ...args) {
1621
+ throw Error("post_process should be implemented in subclass.")
1622
+ }
1623
+
1624
+ /**
1625
+ * Alias for {@link PostProcessor#post_process}.
1626
+ * @param {Array} tokens The text or array of texts to post-process.
1627
+ * @param {...*} args Additional arguments required by the post-processing logic.
1628
+ * @returns {PostProcessedOutput} The post-processed tokens.
1629
+ */
1630
+ _call(tokens, ...args) {
1631
+ return this.post_process(tokens, ...args);
1632
+ }
1633
+ }
1634
+
1635
+ /**
1636
+ * A post-processor that adds special tokens to the beginning and end of the input.
1637
+ */
1638
+ class BertProcessing extends PostProcessor {
1639
+ /**
1640
+ * @param {Object} config The configuration for the post-processor.
1641
+ * @param {string[]} config.cls The special tokens to add to the beginning of the input.
1642
+ * @param {string[]} config.sep The special tokens to add to the end of the input.
1643
+ */
1644
+ constructor(config) {
1645
+ super(config);
1646
+ // TODO use all of config: add_prefix_space, trim_offsets
1647
+
1648
+ this.cls = config.cls[0];
1649
+ this.sep = config.sep[0];
1650
+ }
1651
+
1652
+ /**
1653
+ * Adds the special tokens to the beginning and end of the input.
1654
+ * @param {string[]} tokens The input tokens.
1655
+ * @param {string[]} [tokens_pair=null] An optional second set of input tokens.
1656
+ * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.
1657
+ */
1658
+ post_process(tokens, tokens_pair = null, {
1659
+ add_special_tokens = true,
1660
+ } = {}) {
1661
+ if (add_special_tokens) {
1662
+ tokens = mergeArrays([this.cls], tokens, [this.sep]);
1663
+ }
1664
+
1665
+ let token_type_ids = new Array(tokens.length).fill(0);
1666
+ if (tokens_pair !== null) {
1667
+ // NOTE: It is intended to add 2 EOS tokens after the first set of tokens
1668
+ // https://github.com/huggingface/tokenizers/issues/983
1669
+ const middle = (add_special_tokens && this instanceof RobertaProcessing)
1670
+ ? [this.sep]
1671
+ : [];
1672
+ const after = add_special_tokens ? [this.sep] : [];
1673
+
1674
+ tokens = mergeArrays(tokens, middle, tokens_pair, after);
1675
+ token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));
1676
+ }
1677
+ return { tokens, token_type_ids };
1678
+ }
1679
+ }
1680
+ class RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing
1681
+
1682
+ /**
1683
+ * Post processor that replaces special tokens in a template with actual tokens.
1684
+ * @extends PostProcessor
1685
+ */
1686
+ class TemplateProcessing extends PostProcessor {
1687
+ /**
1688
+ * Creates a new instance of `TemplateProcessing`.
1689
+ * @param {Object} config The configuration options for the post processor.
1690
+ * @param {Array} config.single The template for a single sequence of tokens.
1691
+ * @param {Array} config.pair The template for a pair of sequences of tokens.
1692
+ */
1693
+ constructor(config) {
1694
+ super(config);
1695
+
1696
+ this.single = config.single;
1697
+ this.pair = config.pair;
1698
+ }
1699
+
1700
+ /**
1701
+ * Replaces special tokens in the template with actual tokens.
1702
+ * @param {string[]} tokens The list of tokens for the first sequence.
1703
+ * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1704
+ * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.
1705
+ */
1706
+ post_process(tokens, tokens_pair = null, {
1707
+ add_special_tokens = true,
1708
+ } = {}) {
1709
+ const type = tokens_pair === null ? this.single : this.pair
1710
+
1711
+ let processedTokens = [];
1712
+ let types = [];
1713
+ for (const item of type) {
1714
+ if ('SpecialToken' in item) {
1715
+ if (add_special_tokens) {
1716
+ processedTokens.push(item.SpecialToken.id);
1717
+ types.push(item.SpecialToken.type_id);
1718
+ }
1719
+ } else if ('Sequence' in item) {
1720
+ if (item.Sequence.id === 'A') {
1721
+ processedTokens = mergeArrays(processedTokens, tokens);
1722
+ types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));
1723
+
1724
+ } else if (item.Sequence.id === 'B') {
1725
+ processedTokens = mergeArrays(processedTokens, tokens_pair);
1726
+ types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));
1727
+ }
1728
+ }
1729
+ }
1730
+ return { tokens: processedTokens, token_type_ids: types };
1731
+ }
1732
+ }
1733
+
1734
+ /**
1735
+ * A PostProcessor that returns the given tokens as is.
1736
+ * @extends PostProcessor
1737
+ */
1738
+ class ByteLevelPostProcessor extends PostProcessor {
1739
+ /**
1740
+ * Post process the given tokens.
1741
+ * @param {string[]} tokens The list of tokens for the first sequence.
1742
+ * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1743
+ * @returns {PostProcessedOutput} An object containing the post-processed tokens.
1744
+ */
1745
+ post_process(tokens, tokens_pair = null) {
1746
+ if (tokens_pair) {
1747
+ tokens = mergeArrays(tokens, tokens_pair);
1748
+ }
1749
+ return { tokens };
1750
+ }
1751
+ }
1752
+
1753
+
1754
+ /**
1755
+ * A post-processor that applies multiple post-processors in sequence.
1756
+ */
1757
+ class PostProcessorSequence extends PostProcessor {
1758
+
1759
+ /**
1760
+ * Creates a new instance of PostProcessorSequence.
1761
+ * @param {Object} config The configuration object.
1762
+ * @param {Object[]} config.processors The list of post-processors to apply.
1763
+ */
1764
+ constructor(config) {
1765
+ super(config);
1766
+
1767
+ this.processors = config.processors.map(x => PostProcessor.fromConfig(x));
1768
+ }
1769
+
1770
+ /**
1771
+ * Post process the given tokens.
1772
+ * @param {string[]} tokens The list of tokens for the first sequence.
1773
+ * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1774
+ * @returns {PostProcessedOutput} An object containing the post-processed tokens.
1775
+ */
1776
+ post_process(tokens, tokens_pair = null, options = {}) {
1777
+ let token_type_ids;
1778
+ for (const processor of this.processors) {
1779
+ if (processor instanceof ByteLevelPostProcessor) {
1780
+ // Special case where we need to pass the tokens_pair to the post-processor
1781
+ const output = processor.post_process(tokens);
1782
+ tokens = output.tokens;
1783
+ if (tokens_pair) {
1784
+ const pair_output = processor.post_process(tokens_pair);
1785
+ tokens_pair = pair_output.tokens;
1786
+ }
1787
+ } else {
1788
+ const output = processor.post_process(tokens, tokens_pair, options);
1789
+ tokens = output.tokens;
1790
+ token_type_ids = output.token_type_ids;
1791
+ }
1792
+ }
1793
+ return { tokens, token_type_ids };
1794
+ }
1795
+ }
1796
+
1797
+ /**
1798
+ * The base class for token decoders.
1799
+ * @extends Callable
1800
+ */
1801
+ class Decoder extends Callable {
1802
+
1803
+ /**
1804
+ * Creates an instance of `Decoder`.
1805
+ *
1806
+ * @param {Object} config The configuration object.
1807
+ */
1808
+ constructor(config) {
1809
+ super();
1810
+ this.config = config;
1811
+
1812
+ /** @type {AddedToken[]} */
1813
+ this.added_tokens = [];
1814
+ this.end_of_word_suffix = null;
1815
+ this.trim_offsets = config.trim_offsets;
1816
+ }
1817
+
1818
+ /**
1819
+ * Creates a decoder instance based on the provided configuration.
1820
+ *
1821
+ * @param {Object} config The configuration object.
1822
+ * @returns {Decoder} A decoder instance.
1823
+ * @throws {Error} If an unknown decoder type is provided.
1824
+ */
1825
+ static fromConfig(config) {
1826
+ if (config === null) return null;
1827
+ switch (config.type) {
1828
+ case 'WordPiece':
1829
+ return new WordPieceDecoder(config);
1830
+ case 'Metaspace':
1831
+ return new MetaspaceDecoder(config);
1832
+ case 'ByteLevel':
1833
+ return new ByteLevelDecoder(config);
1834
+
1835
+ case 'Replace':
1836
+ return new ReplaceDecoder(config);
1837
+ case 'ByteFallback':
1838
+ return new ByteFallback(config);
1839
+ case 'Fuse':
1840
+ return new FuseDecoder(config);
1841
+ case 'Strip':
1842
+ return new StripDecoder(config);
1843
+
1844
+ case 'Sequence':
1845
+ return new DecoderSequence(config);
1846
+
1847
+ case 'CTC':
1848
+ return new CTCDecoder(config);
1849
+ case 'BPEDecoder':
1850
+ return new BPEDecoder(config);
1851
+ default:
1852
+ throw new Error(`Unknown Decoder type: ${config.type}`);
1853
+ }
1854
+ }
1855
+
1856
+ /**
1857
+ * Calls the `decode` method.
1858
+ *
1859
+ * @param {string[]} tokens The list of tokens.
1860
+ * @returns {string} The decoded string.
1861
+ */
1862
+ _call(tokens) {
1863
+ return this.decode(tokens);
1864
+ }
1865
+
1866
+ /**
1867
+ * Decodes a list of tokens.
1868
+ * @param {string[]} tokens The list of tokens.
1869
+ * @returns {string} The decoded string.
1870
+ */
1871
+ decode(tokens) {
1872
+ return this.decode_chain(tokens).join('');
1873
+ }
1874
+
1875
+ /**
1876
+ * Apply the decoder to a list of tokens.
1877
+ *
1878
+ * @param {string[]} tokens The list of tokens.
1879
+ * @returns {string[]} The decoded list of tokens.
1880
+ * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
1881
+ */
1882
+ decode_chain(tokens) {
1883
+ throw Error("`decode_chain` should be implemented in subclass.")
1884
+ }
1885
+
1886
+ }
1887
+
1888
+ class ReplaceDecoder extends Decoder {
1889
+
1890
+ /** @type {Decoder['decode_chain']} */
1891
+ decode_chain(tokens) {
1892
+ const pattern = createPattern(this.config.pattern);
1893
+ return pattern === null
1894
+ ? tokens
1895
+ : tokens.map(token => token.replaceAll(pattern, this.config.content))
1896
+ }
1897
+ }
1898
+
1899
+
1900
+ class ByteFallback extends Decoder {
1901
+ constructor(config) {
1902
+ super(config);
1903
+
1904
+ this.text_decoder = new TextDecoder();
1905
+ }
1906
+
1907
+ /** @type {Decoder['decode_chain']} */
1908
+ decode_chain(tokens) {
1909
+
1910
+ const new_tokens = [];
1911
+ let previous_byte_tokens = [];
1912
+
1913
+ for (const token of tokens) {
1914
+ let bytes = null;
1915
+ if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {
1916
+ const byte = parseInt(token.slice(3, 5), 16);
1917
+ if (!isNaN(byte)) {
1918
+ bytes = byte;
1919
+ }
1920
+ }
1921
+ if (bytes !== null) {
1922
+ previous_byte_tokens.push(bytes);
1923
+ } else {
1924
+ if (previous_byte_tokens.length > 0) {
1925
+ const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
1926
+ new_tokens.push(string);
1927
+ previous_byte_tokens = [];
1928
+ }
1929
+ new_tokens.push(token);
1930
+ }
1931
+ }
1932
+ if (previous_byte_tokens.length > 0) {
1933
+ const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
1934
+ new_tokens.push(string);
1935
+ previous_byte_tokens = [];
1936
+ }
1937
+
1938
+ return new_tokens;
1939
+ }
1940
+ }
1941
+
1942
+ /**
1943
+ * Fuse simply fuses all tokens into one big string.
1944
+ * It's usually the last decoding step anyway, but this decoder
1945
+ * exists incase some decoders need to happen after that step
1946
+ */
1947
+ class FuseDecoder extends Decoder {
1948
+
1949
+ /** @type {Decoder['decode_chain']} */
1950
+ decode_chain(tokens) {
1951
+ return [tokens.join('')];
1952
+ }
1953
+ }
1954
+
1955
+
1956
+ class StripDecoder extends Decoder {
1957
+ constructor(config) {
1958
+ super(config);
1959
+
1960
+ this.content = this.config.content;
1961
+ this.start = this.config.start;
1962
+ this.stop = this.config.stop;
1963
+ }
1964
+
1965
+ /** @type {Decoder['decode_chain']} */
1966
+ decode_chain(tokens) {
1967
+ return tokens.map(token => {
1968
+ let start_cut = 0;
1969
+ for (let i = 0; i < this.start; ++i) {
1970
+ if (token[i] === this.content) {
1971
+ start_cut = i + 1;
1972
+ continue;
1973
+ } else {
1974
+ break;
1975
+ }
1976
+ }
1977
+
1978
+ let stop_cut = token.length;
1979
+ for (let i = 0; i < this.stop; ++i) {
1980
+ const index = token.length - i - 1;
1981
+ if (token[index] === this.content) {
1982
+ stop_cut = index;
1983
+ continue;
1984
+ } else {
1985
+ break;
1986
+ }
1987
+ }
1988
+
1989
+ return token.slice(start_cut, stop_cut)
1990
+ });
1991
+ }
1992
+ }
1993
+
1994
+ /**
1995
+ * A decoder that decodes a list of WordPiece tokens into a single string.
1996
+ * @extends Decoder
1997
+ */
1998
+ class WordPieceDecoder extends Decoder {
1999
+
2000
+ /**
2001
+ * Creates a new instance of WordPieceDecoder.
2002
+ * @param {Object} config The configuration object.
2003
+ * @param {string} config.prefix The prefix used for WordPiece encoding.
2004
+ * @param {boolean} config.cleanup Whether to cleanup the decoded string.
2005
+ */
2006
+ constructor(config) {
2007
+ super(config);
2008
+ this.cleanup = config.cleanup;
2009
+ }
2010
+
2011
+ /** @type {Decoder['decode_chain']} */
2012
+ decode_chain(tokens) {
2013
+ return tokens.map((token, i) => {
2014
+ if (i !== 0) {
2015
+ if (token.startsWith(this.config.prefix)) {
2016
+ // NOTE: .replace() is intended; only replace first occurrence
2017
+ token = token.replace(this.config.prefix, '');
2018
+ } else {
2019
+ token = ' ' + token;
2020
+ }
2021
+ }
2022
+ if (this.cleanup) {
2023
+ token = clean_up_tokenization(token)
2024
+ }
2025
+
2026
+ return token;
2027
+ });
2028
+ }
2029
+ }
2030
+
2031
+ /**
2032
+ * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.
2033
+ * @extends Decoder
2034
+ */
2035
+ class ByteLevelDecoder extends Decoder {
2036
+
2037
+ /**
2038
+ * Create a `ByteLevelDecoder` object.
2039
+ * @param {Object} config Configuration object.
2040
+ */
2041
+ constructor(config) {
2042
+ super(config);
2043
+
2044
+ this.byte_decoder = UNICODE_TO_BYTES;
2045
+ this.text_decoder = new TextDecoder("utf-8", {
2046
+ fatal: false,
2047
+ ignoreBOM: true,
2048
+ });
2049
+
2050
+ this.end_of_word_suffix = null;
2051
+ }
2052
+
2053
+ /**
2054
+ * Convert an array of tokens to string by decoding each byte.
2055
+ * @param {string[]} tokens Array of tokens to be decoded.
2056
+ * @returns {string} The decoded string.
2057
+ */
2058
+ convert_tokens_to_string(tokens) {
2059
+ const text = tokens.join('');
2060
+ const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));
2061
+ const decoded_text = this.text_decoder.decode(byteArray);
2062
+ return decoded_text;
2063
+ }
2064
+
2065
+ /** @type {Decoder['decode_chain']} */
2066
+ decode_chain(tokens) {
2067
+ // TODO move to base class (like HF)
2068
+ // tokens === filtered_tokens
2069
+
2070
+ // To avoid mixing byte-level and unicode for byte-level BPT
2071
+ // we need to build string separately for added tokens and byte-level tokens
2072
+ // cf. https://github.com/huggingface/transformers/issues/1133
2073
+ const sub_texts = [];
2074
+ let current_sub_text = [];
2075
+ for (const token of tokens) {
2076
+ // tokens sent here are already filtered, so we don't need to do this
2077
+ // if (skip_special_tokens && this.all_special_ids.includes(token)) {
2078
+ // continue;
2079
+ // }
2080
+
2081
+ if (this.added_tokens.find(x => x.content === token) !== undefined) {
2082
+ if (current_sub_text.length > 0) {
2083
+ sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2084
+ current_sub_text = [];
2085
+ }
2086
+ sub_texts.push(token);
2087
+ } else {
2088
+ current_sub_text.push(token);
2089
+ }
2090
+ }
2091
+ if (current_sub_text.length > 0) {
2092
+ sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2093
+ }
2094
+
2095
+ // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options
2096
+
2097
+ return sub_texts;
2098
+ }
2099
+ }
2100
+
2101
+ /**
2102
+ * The CTC (Connectionist Temporal Classification) decoder.
2103
+ * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs
2104
+ */
2105
+ class CTCDecoder extends Decoder {
2106
+
2107
+ constructor(config) {
2108
+ super(config);
2109
+
2110
+ this.pad_token = this.config.pad_token;
2111
+ this.word_delimiter_token = this.config.word_delimiter_token;
2112
+ this.cleanup = this.config.cleanup;
2113
+ }
2114
+ /**
2115
+ * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
2116
+ * @param {string[]} tokens Array of tokens to be decoded.
2117
+ * @returns {string} The decoded string.
2118
+ */
2119
+ convert_tokens_to_string(tokens) {
2120
+ if (tokens.length === 0) return '';
2121
+
2122
+ // group same tokens into non-repeating tokens in CTC style decoding
2123
+ const grouped_tokens = [tokens[0]];
2124
+ for (let i = 1; i < tokens.length; ++i) {
2125
+ if (tokens[i] !== grouped_tokens.at(-1)) {
2126
+ grouped_tokens.push(tokens[i]);
2127
+ }
2128
+ }
2129
+
2130
+ // filter self.pad_token which is used as CTC-blank token
2131
+ const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);
2132
+
2133
+ let text = filtered_tokens.join('');
2134
+ if (this.cleanup) {
2135
+ // cleanup and replace delimiter token
2136
+ text = clean_up_tokenization(text)
2137
+ .replaceAll(this.word_delimiter_token, ' ')
2138
+ .trim();
2139
+ }
2140
+ return text;
2141
+ }
2142
+
2143
+
2144
+ /** @type {Decoder['decode_chain']} */
2145
+ decode_chain(tokens) {
2146
+ return [this.convert_tokens_to_string(tokens)];
2147
+ }
2148
+ }
2149
+
2150
+ /**
2151
+ * Apply a sequence of decoders.
2152
+ * @extends Decoder
2153
+ */
2154
+ class DecoderSequence extends Decoder {
2155
+
2156
+ /**
2157
+ * Creates a new instance of DecoderSequence.
2158
+ * @param {Object} config The configuration object.
2159
+ * @param {Object[]} config.decoders The list of decoders to apply.
2160
+ */
2161
+ constructor(config) {
2162
+ super(config);
2163
+ this.decoders = config.decoders.map(x => Decoder.fromConfig(x));
2164
+ }
2165
+
2166
+ /** @type {Decoder['decode_chain']} */
2167
+ decode_chain(tokens) {
2168
+ // Use reduce to apply each decoder to the tokens
2169
+ return this.decoders.reduce((toks, decoder) => {
2170
+ return decoder.decode_chain(toks);
2171
+ }, tokens);
2172
+ }
2173
+
2174
+ }
2175
+
2176
+ class BPEDecoder extends Decoder {
2177
+ constructor(config) {
2178
+ super(config);
2179
+
2180
+ this.suffix = this.config.suffix;
2181
+ }
2182
+ /** @type {Decoder['decode_chain']} */
2183
+ decode_chain(tokens) {
2184
+ return tokens.map((token, i) => {
2185
+ return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')
2186
+ });
2187
+ }
2188
+ }
2189
+
2190
+ // Custom decoder for VITS
2191
+ class VitsDecoder extends Decoder {
2192
+ /** @type {Decoder['decode_chain']} */
2193
+ decode_chain(tokens) {
2194
+ let decoded = '';
2195
+ for (let i = 1; i < tokens.length; i += 2) {
2196
+ decoded += tokens[i];
2197
+ }
2198
+ return [decoded];
2199
+ }
2200
+ }
2201
+
2202
+
2203
+ /**
2204
+ * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,
2205
+ * and returns a list of tokens.
2206
+ * @extends PreTokenizer
2207
+ */
2208
+ class MetaspacePreTokenizer extends PreTokenizer {
2209
+ /**
2210
+ * @param {Object} config The configuration object for the MetaspacePreTokenizer.
2211
+ * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.
2212
+ * @param {string} config.replacement The character to replace spaces with.
2213
+ * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.
2214
+ * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.
2215
+ */
2216
+ constructor(config) {
2217
+ super();
2218
+
2219
+ this.addPrefixSpace = config.add_prefix_space;
2220
+ this.replacement = config.replacement;
2221
+ this.strRep = config.str_rep || this.replacement;
2222
+ this.prepend_scheme = config.prepend_scheme ?? 'always';
2223
+ }
2224
+
2225
+ /**
2226
+ * This method takes a string, replaces spaces with the replacement character,
2227
+ * adds a prefix space if requested, and returns a new list of tokens.
2228
+ * @param {string} text The text to pre-tokenize.
2229
+ * @param {Object} [options] The options for the pre-tokenization.
2230
+ * @param {number} [options.section_index] The index of the section to pre-tokenize.
2231
+ * @returns {string[]} A new list of pre-tokenized tokens.
2232
+ */
2233
+ pre_tokenize_text(text, {
2234
+ section_index = undefined,
2235
+ } = {}) {
2236
+
2237
+ let normalized = text.replaceAll(' ', this.strRep);
2238
+
2239
+ if (
2240
+ // We add a prefix space if:
2241
+ // (1) The addPrefixSpace option is enabled and the normalized
2242
+ // token does not already start with the replacement character.
2243
+ (this.addPrefixSpace && !normalized.startsWith(this.replacement))
2244
+
2245
+ // and (2) either:
2246
+ // (a) prepend_scheme is 'always'
2247
+ // (b) prepend_scheme is 'first' and this is the first section
2248
+ && (
2249
+ this.prepend_scheme === 'always' ||
2250
+ (this.prepend_scheme === 'first' && section_index === 0)
2251
+ )
2252
+ ) {
2253
+ normalized = this.strRep + normalized;
2254
+ }
2255
+ return [normalized];
2256
+ }
2257
+ }
2258
+
2259
+ /**
2260
+ * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.
2261
+ * @extends Decoder
2262
+ */
2263
+ class MetaspaceDecoder extends Decoder {
2264
+ /**
2265
+ * Constructs a new MetaspaceDecoder object.
2266
+ * @param {Object} config The configuration object for the MetaspaceDecoder.
2267
+ * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.
2268
+ * @param {string} config.replacement The string to replace spaces with.
2269
+ */
2270
+ constructor(config) {
2271
+ super(config);
2272
+
2273
+ this.addPrefixSpace = config.add_prefix_space;
2274
+ this.replacement = config.replacement;
2275
+ }
2276
+
2277
+ /** @type {Decoder['decode_chain']} */
2278
+ decode_chain(tokens) {
2279
+ const result = [];
2280
+ for (let i = 0; i < tokens.length; ++i) {
2281
+ let normalized = tokens[i].replaceAll(this.replacement, ' ');
2282
+ if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {
2283
+ normalized = normalized.substring(1);
2284
+ }
2285
+ result.push(normalized);
2286
+ }
2287
+ return result;
2288
+ }
2289
+ }
2290
+
2291
+ /**
2292
+ * A normalizer that applies a precompiled charsmap.
2293
+ * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.
2294
+ * @extends Normalizer
2295
+ * @param {Object} config The configuration object for the Precompiled normalizer.
2296
+ * @param {Object} config.precompiled_charsmap The precompiled charsmap object.
2297
+ */
2298
+ class Precompiled extends Normalizer {
2299
+ /**
2300
+ * Create a new instance of Precompiled normalizer.
2301
+ * @param {Object} config The configuration object.
2302
+ * @param {any} config.precompiled_charsmap Precompiled chars mapping.
2303
+ */
2304
+ constructor(config) {
2305
+ super(config);
2306
+ this.charsmap = config.precompiled_charsmap;
2307
+ }
2308
+
2309
+ /**
2310
+ * Normalizes the given text by applying the precompiled charsmap.
2311
+ * @param {string} text The text to normalize.
2312
+ * @returns {string} The normalized text.
2313
+ */
2314
+ normalize(text) {
2315
+ // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),
2316
+ // there are 5 pre-defined normalization rules:
2317
+ // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)
2318
+ // 2. nfkc: original NFKC normalization.
2319
+ // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)
2320
+ // 4. nfkc_cf: nfkc + Unicode case folding.
2321
+ // 5. identity: no normalization
2322
+ //
2323
+ // For now, we only implement the default (nmt_nfkc).
2324
+ // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.
2325
+ // TODO: detect when a different `this.charsmap` is used.
2326
+
2327
+ text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ''); // Remove control characters
2328
+ text = text.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, '\u0020'); // Replace certain characters with a space
2329
+
2330
+ if (text.includes('\uFF5E')) {
2331
+ // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.
2332
+ // For some reason, the "Fullwidth Tilde" character (\uFF5E) should not be converted to the standard Tilde character (\u007E).
2333
+ // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,
2334
+ // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.
2335
+ const parts = text.split('\uFF5E');
2336
+ text = parts.map(part => part.normalize('NFKC')).join('\uFF5E');
2337
+ } else {
2338
+ text = text.normalize('NFKC');
2339
+ }
2340
+
2341
+ return text;
2342
+ }
2343
+ }
2344
+
2345
+ /**
2346
+ * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.
2347
+ * @extends PreTokenizer
2348
+ */
2349
+ class PreTokenizerSequence extends PreTokenizer {
2350
+ /**
2351
+ * Creates an instance of PreTokenizerSequence.
2352
+ * @param {Object} config The configuration object for the pre-tokenizer sequence.
2353
+ * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.
2354
+ */
2355
+ constructor(config) {
2356
+ super();
2357
+ this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));
2358
+ }
2359
+
2360
+ /**
2361
+ * Applies each pre-tokenizer in the sequence to the input text in turn.
2362
+ * @param {string} text The text to pre-tokenize.
2363
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
2364
+ * @returns {string[]} The pre-tokenized text.
2365
+ */
2366
+ pre_tokenize_text(text, options) {
2367
+ // Use reduce to apply each tokenizer to the text
2368
+ return this.tokenizers.reduce((preTokenizedText, tokenizer) => {
2369
+ return tokenizer.pre_tokenize(preTokenizedText, options);
2370
+ }, [text]);
2371
+ }
2372
+ }
2373
+
2374
+ /**
2375
+ * Splits on word boundaries (using the following regular expression: `\w+|[^\w\s]+`).
2376
+ */
2377
+ class WhitespacePreTokenizer extends PreTokenizer {
2378
+ /**
2379
+ * Creates an instance of WhitespacePreTokenizer.
2380
+ * @param {Object} config The configuration object for the pre-tokenizer.
2381
+ */
2382
+ constructor(config) {
2383
+ super();
2384
+ }
2385
+ /**
2386
+ * Pre-tokenizes the input text by splitting it on word boundaries.
2387
+ * @param {string} text The text to be pre-tokenized.
2388
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
2389
+ * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
2390
+ */
2391
+ pre_tokenize_text(text, options) {
2392
+ return text.match(/\w+|[^\w\s]+/g) || [];
2393
+ }
2394
+ }
2395
+
2396
+ /**
2397
+ * Splits a string of text by whitespace characters into individual tokens.
2398
+ * @extends PreTokenizer
2399
+ */
2400
+ class WhitespaceSplit extends PreTokenizer {
2401
+ /**
2402
+ * Creates an instance of WhitespaceSplit.
2403
+ * @param {Object} config The configuration object for the pre-tokenizer.
2404
+ */
2405
+ constructor(config) {
2406
+ super();
2407
+ }
2408
+ /**
2409
+ * Pre-tokenizes the input text by splitting it on whitespace characters.
2410
+ * @param {string} text The text to be pre-tokenized.
2411
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
2412
+ * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
2413
+ */
2414
+ pre_tokenize_text(text, options) {
2415
+ return whitespace_split(text);
2416
+ }
2417
+ }
2418
+
2419
+ // NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)
2420
+ class ReplacePreTokenizer extends PreTokenizer {
2421
+ /**
2422
+ * @param {Object} config The configuration options for the pre-tokenizer.
2423
+ * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
2424
+ * @param {string} config.content What to replace the pattern with.
2425
+ */
2426
+ constructor(config) {
2427
+ super();
2428
+ this.config = config;
2429
+ this.pattern = createPattern(this.config.pattern);
2430
+ this.content = this.config.content;
2431
+ }
2432
+
2433
+ /**
2434
+ * Pre-tokenizes the input text by replacing certain characters.
2435
+ * @param {string} text The text to be pre-tokenized.
2436
+ * @param {Object} [options] Additional options for the pre-tokenization logic.
2437
+ * @returns {string[]} An array of tokens produced by replacing certain characters.
2438
+ */
2439
+ pre_tokenize_text(text, options) {
2440
+ if (this.pattern === null) {
2441
+ return [text];
2442
+ }
2443
+ return [text.replaceAll(this.pattern, this.config.content)];
2444
+ }
2445
+ }
2446
+
2447
+ const SPECIAL_TOKEN_ATTRIBUTES = [
2448
+ 'bos_token',
2449
+ 'eos_token',
2450
+ 'unk_token',
2451
+ 'sep_token',
2452
+ 'pad_token',
2453
+ 'cls_token',
2454
+ 'mask_token',
2455
+ // additional_special_tokens (TODO)
2456
+ ]
2457
+
2458
+ /**
2459
+ *
2460
+ * Helper function for padding values of an object, which are each arrays.
2461
+ * NOTE: No additional checks are made here for validity of arguments.
2462
+ * @param {Record<string, any[]>} item The input object.
2463
+ * @param {number} length The length to pad to.
2464
+ * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.
2465
+ * @param {string} side Which side to pad the array.
2466
+ * @private
2467
+ */
2468
+ function padHelper(item, length, value_fn, side) {
2469
+ for (const key of Object.keys(item)) {
2470
+ const diff = length - item[key].length;
2471
+ const value = value_fn(key);
2472
+
2473
+ const padData = new Array(diff).fill(value);
2474
+ item[key] = side === 'right'
2475
+ ? mergeArrays(item[key], padData)
2476
+ : mergeArrays(padData, item[key]);
2477
+ }
2478
+ }
2479
+
2480
+ /**
2481
+ * Helper function for truncating values of an object, which are each arrays.
2482
+ * NOTE: No additional checks are made here for validity of arguments.
2483
+ * @param {Record<string, any[]>} item The input object.
2484
+ * @param {number} length The length to truncate to.
2485
+ * @private
2486
+ */
2487
+ function truncateHelper(item, length) {
2488
+ // Setting .length to a lower value truncates the array in-place:
2489
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
2490
+ for (const key of Object.keys(item)) {
2491
+ item[key].length = length;
2492
+ }
2493
+ }
2494
+
2495
+
2496
+ /**
2497
+ * @typedef {Object} Message
2498
+ * @property {string} role The role of the message (e.g., "user" or "assistant" or "system").
2499
+ * @property {string} content The content of the message.
2500
+ */
2501
+
2502
+ export class PreTrainedTokenizer extends Callable {
2503
+ return_token_type_ids = false;
2504
+
2505
+ padding_side = 'right';
2506
+ /**
2507
+ * Create a new PreTrainedTokenizer instance.
2508
+ * @param {Object} tokenizerJSON The JSON of the tokenizer.
2509
+ * @param {Object} tokenizerConfig The config of the tokenizer.
2510
+ */
2511
+ constructor(tokenizerJSON, tokenizerConfig) {
2512
+ super();
2513
+
2514
+ this._tokenizer_config = tokenizerConfig;
2515
+
2516
+ // Construct parts of the tokenizer from the JSON
2517
+ this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);
2518
+ this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);
2519
+ this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);
2520
+ this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);
2521
+ this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);
2522
+
2523
+ // Add added_tokens to model
2524
+ this.special_tokens = [];
2525
+ this.all_special_ids = [];
2526
+
2527
+ /** @type {AddedToken[]} */
2528
+ this.added_tokens = [];
2529
+ for (const addedToken of tokenizerJSON.added_tokens) {
2530
+ const token = new AddedToken(addedToken);
2531
+ this.added_tokens.push(token);
2532
+
2533
+ this.model.tokens_to_ids.set(token.content, token.id);
2534
+ this.model.vocab[token.id] = token.content;
2535
+
2536
+ if (token.special) {
2537
+ this.special_tokens.push(token.content);
2538
+ this.all_special_ids.push(token.id);
2539
+ }
2540
+ }
2541
+
2542
+ // Update additional_special_tokens
2543
+ this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];
2544
+ this.special_tokens.push(...this.additional_special_tokens);
2545
+ this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates
2546
+
2547
+ if (this.decoder) {
2548
+ // Slight hack, but it prevents code duplication:
2549
+ this.decoder.added_tokens = this.added_tokens;
2550
+
2551
+ // Another slight hack to add `end_of_word_suffix` (if present) to the decoder
2552
+ // This is needed for cases where BPE model and ByteLevel decoder are used
2553
+ // For more information, see https://github.com/xenova/transformers.js/issues/74
2554
+ // TODO: save this to the decoder when exporting?
2555
+ this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;
2556
+ }
2557
+
2558
+
2559
+ this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(
2560
+ this.added_tokens
2561
+ // Sort by length (desc) to avoid early partial matches
2562
+ .toSorted((a, b) => b.content.length - a.content.length)
2563
+ .map(x => `${x.lstrip ? '\\s*' : ''}(${escapeRegExp(x.content)})${x.rstrip ? '\\s*' : ''}`)
2564
+ .join('|')
2565
+ ) : null;
2566
+
2567
+ // Set mask token if present (otherwise will be undefined, which is fine)
2568
+ this.mask_token = this.getToken('mask_token');
2569
+ this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);
2570
+
2571
+ this.pad_token = this.getToken('pad_token', 'eos_token');
2572
+ this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);
2573
+
2574
+ this.sep_token = this.getToken('sep_token');
2575
+ this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);
2576
+
2577
+ this.unk_token = this.getToken('unk_token');
2578
+ this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);
2579
+
2580
+ this.model_max_length = tokenizerConfig.model_max_length;
2581
+
2582
+ /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */
2583
+ this.remove_space = tokenizerConfig.remove_space;
2584
+
2585
+ this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;
2586
+ this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;
2587
+
2588
+ if (tokenizerConfig.padding_side) {
2589
+ this.padding_side = tokenizerConfig.padding_side;
2590
+ }
2591
+
2592
+ this.legacy = false;
2593
+
2594
+ this.chat_template = tokenizerConfig.chat_template ?? null;
2595
+ if (Array.isArray(this.chat_template)) {
2596
+ // Chat templates are stored as lists of dicts with fixed key names,
2597
+ // we reconstruct that into a single dict while loading them.
2598
+ const chat_template = Object.create(null);
2599
+ for (const { name, template } of this.chat_template) {
2600
+ if (typeof name !== 'string' || typeof template !== 'string') {
2601
+ throw new Error('Chat template must be a list of objects with "name" and "template" properties');
2602
+ }
2603
+ chat_template[name] = template;
2604
+ }
2605
+ this.chat_template = chat_template;
2606
+ }
2607
+ this._compiled_template_cache = new Map();
2608
+ }
2609
+
2610
+ /**
2611
+ * Returns the value of the first matching key in the tokenizer config object.
2612
+ * @param {...string} keys One or more keys to search for in the tokenizer config object.
2613
+ * @returns {string|null} The value associated with the first matching key, or null if no match is found.
2614
+ * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
2615
+ * @private
2616
+ */
2617
+ getToken(...keys) {
2618
+ for (const key of keys) {
2619
+ const item = this._tokenizer_config[key];
2620
+
2621
+ if (!item) continue;
2622
+
2623
+ if (typeof item === 'object') {
2624
+ if (item.__type === 'AddedToken') {
2625
+ return item.content;
2626
+ } else {
2627
+ throw Error(`Unknown token: ${item}`);
2628
+ }
2629
+ } else {
2630
+ return item;
2631
+ }
2632
+ }
2633
+ return null;
2634
+ }
2635
+
2636
+ /**
2637
+ * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`.
2638
+ *
2639
+ * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
2640
+ * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
2641
+ *
2642
+ * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
2643
+ * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
2644
+ */
2645
+ static async from_pretrained(pretrained_model_name_or_path, {
2646
+ progress_callback = null,
2647
+ config = null,
2648
+ cache_dir = null,
2649
+ local_files_only = false,
2650
+ revision = 'main',
2651
+ legacy = null,
2652
+ } = {}) {
2653
+
2654
+ const info = await loadTokenizer(pretrained_model_name_or_path, {
2655
+ progress_callback,
2656
+ config,
2657
+ cache_dir,
2658
+ local_files_only,
2659
+ revision,
2660
+ legacy,
2661
+ })
2662
+
2663
+ // @ts-ignore
2664
+ return new this(...info);
2665
+ }
2666
+
2667
+ /**
2668
+ * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
2669
+ *
2670
+ * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
2671
+ * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
2672
+ * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
2673
+ * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
2674
+ */
2675
+
2676
+ /**
2677
+ * Encode/tokenize the given text(s).
2678
+ * @param {string|string[]} text The text to tokenize.
2679
+ * @param {Object} options An optional object containing the following properties:
2680
+ * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
2681
+ * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
2682
+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2683
+ * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
2684
+ * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
2685
+ * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
2686
+ * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.
2687
+ * @returns {BatchEncoding} Object to be passed to the model.
2688
+ */
2689
+ _call(
2690
+ // Required positional arguments
2691
+ text,
2692
+
2693
+ // Optional keyword arguments
2694
+ {
2695
+ text_pair = null,
2696
+ add_special_tokens = true,
2697
+ padding = false,
2698
+ truncation = null,
2699
+ max_length = null,
2700
+ return_tensor = true, // Different to HF
2701
+ return_token_type_ids = null,
2702
+ } = {},
2703
+ ) {
2704
+
2705
+ const isBatched = Array.isArray(text);
2706
+
2707
+ /** @type {EncodingSingle[]} */
2708
+ let encodedTokens;
2709
+
2710
+ if (isBatched) {
2711
+ if (text.length === 0) {
2712
+ throw Error('text array must be non-empty')
2713
+ }
2714
+
2715
+ if (text_pair !== null) {
2716
+ if (!Array.isArray(text_pair)) {
2717
+ throw Error('text_pair must also be an array')
2718
+
2719
+ } else if (text.length !== text_pair.length) {
2720
+ throw Error('text and text_pair must have the same length')
2721
+ }
2722
+
2723
+ encodedTokens = text.map(
2724
+ (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids })
2725
+ )
2726
+
2727
+ } else {
2728
+ encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids }));
2729
+ }
2730
+
2731
+ } else {
2732
+ if (text === null || text === undefined) {
2733
+ throw Error('text may not be null or undefined')
2734
+ }
2735
+
2736
+ if (Array.isArray(text_pair)) {
2737
+ throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')
2738
+ }
2739
+
2740
+ // For single input, we just wrap in an array, and then unwrap later.
2741
+ encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })];
2742
+ }
2743
+ // At this point, tokens is batched: [batch_size, tokens]
2744
+ // However, array may be jagged. So, we pad to max_length
2745
+
2746
+ if (max_length === null) {
2747
+ if (padding === 'max_length') {
2748
+ max_length = this.model_max_length;
2749
+ } else {
2750
+ // Calculate max length from sequences
2751
+ max_length = max(encodedTokens.map(x => x.input_ids.length))[0];
2752
+ }
2753
+ } else {
2754
+ if (!truncation) {
2755
+ console.warn(`Truncation was not explicitly activated but \`max_length\` is provided a specific value, please use \`truncation=true\` to explicitly truncate examples to max length.`)
2756
+ }
2757
+ }
2758
+
2759
+ // Ensure it is less than model max length
2760
+ max_length = Math.min(max_length, this.model_max_length ?? Infinity);
2761
+
2762
+ if (padding || truncation) {
2763
+
2764
+ // Perform padding and/or truncation
2765
+ for (let i = 0; i < encodedTokens.length; ++i) {
2766
+ if (encodedTokens[i].input_ids.length === max_length) {
2767
+ continue;
2768
+
2769
+ } else if (encodedTokens[i].input_ids.length > max_length) {
2770
+ // possibly truncate
2771
+ if (truncation) {
2772
+ truncateHelper(encodedTokens[i], max_length);
2773
+ }
2774
+
2775
+ } else { // t.length < max_length
2776
+ // possibly pad
2777
+ if (padding) {
2778
+ padHelper(
2779
+ encodedTokens[i],
2780
+ max_length,
2781
+ key => key === 'input_ids' ? this.pad_token_id : 0,
2782
+ this.padding_side
2783
+ );
2784
+ }
2785
+ }
2786
+ }
2787
+ }
2788
+
2789
+ const result = {};
2790
+
2791
+ if (return_tensor) {
2792
+ if (!(padding && truncation)) {
2793
+ // Not, guaranteed that all items have same length, so
2794
+ // we perform additional check
2795
+
2796
+ if (
2797
+ encodedTokens.some(x => {
2798
+ for (const key of Object.keys(x)) {
2799
+ if (x[key].length !== encodedTokens[0][key]?.length) {
2800
+ return true;
2801
+ }
2802
+ }
2803
+ return false;
2804
+ })
2805
+ ) {
2806
+ throw Error(
2807
+ "Unable to create tensor, you should probably activate truncation and/or padding " +
2808
+ "with 'padding=true' and 'truncation=true' to have batched tensors with the same length."
2809
+ )
2810
+ }
2811
+ }
2812
+
2813
+ // Now we actually convert to tensor
2814
+ // NOTE: In the same way as the python library, we return a batched tensor, regardless of
2815
+ // whether we have a single input or multiple inputs.
2816
+ const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];
2817
+
2818
+ for (const key of Object.keys(encodedTokens[0])) {
2819
+ result[key] = new Tensor('int64',
2820
+ BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),
2821
+ dims
2822
+ );
2823
+ }
2824
+
2825
+ } else {
2826
+ for (const key of Object.keys(encodedTokens[0])) {
2827
+ result[key] = encodedTokens.map(x => x[key]);
2828
+ }
2829
+
2830
+ // If not returning a tensor, we match the input type
2831
+ if (!isBatched) {
2832
+ // Input was not batched, so we unwrap
2833
+ for (const key of Object.keys(result)) {
2834
+ result[key] = result[key][0];
2835
+ }
2836
+ }
2837
+ }
2838
+
2839
+ return /** @type {BatchEncoding} */(result);
2840
+ }
2841
+
2842
+ /**
2843
+ * Encodes a single text using the preprocessor pipeline of the tokenizer.
2844
+ *
2845
+ * @param {string|null} text The text to encode.
2846
+ * @returns {string[]|null} The encoded tokens.
2847
+ */
2848
+ _encode_text(text) {
2849
+ if (text === null) return null;
2850
+
2851
+ // Actual function which does encoding, for a single text
2852
+ // First, we take care of special tokens. Needed to avoid issues arising from
2853
+ // normalization and/or pretokenization (which may not preserve special tokens)
2854
+ const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text];
2855
+
2856
+ const tokens = sections.map((x, section_index) => {
2857
+ const addedToken = this.added_tokens.find(t => t.content === x);
2858
+ if (addedToken !== undefined) {
2859
+ // Ignore added tokens
2860
+ return x
2861
+ } else {
2862
+ if (this.remove_space === true) {
2863
+ x = x.trim().split(/\s+/).join(' ');
2864
+ }
2865
+ if (this.do_lowercase_and_remove_accent) {
2866
+ x = lowercase_and_remove_accent(x);
2867
+ }
2868
+
2869
+ if (this.normalizer !== null) {
2870
+ x = this.normalizer(x);
2871
+ }
2872
+
2873
+ // If, after normalization, this section is empty (e.g., trimming whitespace),
2874
+ // we return an empty array
2875
+ if (x.length === 0) {
2876
+ return [];
2877
+ }
2878
+
2879
+ const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {
2880
+ section_index,
2881
+ }) : [x];
2882
+
2883
+ const tokens = this.model(sectionTokens);
2884
+
2885
+ return tokens;
2886
+ }
2887
+ }).flat();
2888
+
2889
+ return tokens;
2890
+ }
2891
+
2892
+ /**
2893
+ * Encodes a single text or a pair of texts using the model's tokenizer.
2894
+ *
2895
+ * @param {string} text The text to encode.
2896
+ * @param {Object} options An optional object containing the following properties:
2897
+ * @param {string} [options.text_pair=null] The optional second text to encode.
2898
+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2899
+ * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
2900
+ * @returns {EncodingSingle} An object containing the encoded text.
2901
+ * @private
2902
+ */
2903
+ _encode_plus(text, {
2904
+ text_pair = null,
2905
+ add_special_tokens = true,
2906
+ return_token_type_ids = null,
2907
+ } = {}) {
2908
+
2909
+ const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens });
2910
+
2911
+ const input_ids = this.model.convert_tokens_to_ids(tokens);
2912
+
2913
+ const result = {
2914
+ input_ids,
2915
+ attention_mask: new Array(input_ids.length).fill(1),
2916
+ }
2917
+ if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) {
2918
+ result.token_type_ids = token_type_ids;
2919
+ }
2920
+ return result;
2921
+ }
2922
+
2923
+ /**
2924
+ * Internal helper function to tokenize a text, and optionally a pair of texts.
2925
+ * @param {string} text The text to tokenize.
2926
+ * @param {Object} options An optional object containing the following properties:
2927
+ * @param {string} [options.pair=null] The optional second text to tokenize.
2928
+ * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.
2929
+ * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs.
2930
+ */
2931
+ _tokenize_helper(text, {
2932
+ pair = null,
2933
+ add_special_tokens = false,
2934
+ } = {}) {
2935
+ const tokens = this._encode_text(text);
2936
+ const tokens2 = this._encode_text(pair);
2937
+
2938
+ return this.post_processor
2939
+ ? this.post_processor(tokens, tokens2, { add_special_tokens })
2940
+ : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };
2941
+ }
2942
+
2943
+ /**
2944
+ * Converts a string into a sequence of tokens.
2945
+ * @param {string} text The sequence to be encoded.
2946
+ * @param {Object} options An optional object containing the following properties:
2947
+ * @param {string} [options.pair] A second sequence to be encoded with the first.
2948
+ * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.
2949
+ * @returns {string[]} The list of tokens.
2950
+ */
2951
+ tokenize(text, {
2952
+ pair = null,
2953
+ add_special_tokens = false,
2954
+ } = {}) {
2955
+ return this._tokenize_helper(text, { pair, add_special_tokens }).tokens;
2956
+ }
2957
+
2958
+ /**
2959
+ * Encodes a single text or a pair of texts using the model's tokenizer.
2960
+ *
2961
+ * @param {string} text The text to encode.
2962
+ * @param {Object} options An optional object containing the following properties:
2963
+ * @param {string} [options.text_pair=null] The optional second text to encode.
2964
+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2965
+ * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
2966
+ * @returns {number[]} An array of token IDs representing the encoded text(s).
2967
+ */
2968
+ encode(text, {
2969
+ text_pair = null,
2970
+ add_special_tokens = true,
2971
+ return_token_type_ids = null,
2972
+ } = {}) {
2973
+ return this._encode_plus(text, {
2974
+ text_pair,
2975
+ add_special_tokens,
2976
+ return_token_type_ids,
2977
+ }).input_ids;
2978
+ }
2979
+
2980
+ /**
2981
+ * Decode a batch of tokenized sequences.
2982
+ * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.
2983
+ * @param {Object} decode_args (Optional) Object with decoding arguments.
2984
+ * @returns {string[]} List of decoded sequences.
2985
+ */
2986
+ batch_decode(batch, decode_args = {}) {
2987
+ if (batch instanceof Tensor) {
2988
+ batch = batch.tolist();
2989
+ }
2990
+ return batch.map(x => this.decode(x, decode_args));
2991
+ }
2992
+
2993
+ /**
2994
+ * Decodes a sequence of token IDs back to a string.
2995
+ *
2996
+ * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode.
2997
+ * @param {Object} [decode_args={}]
2998
+ * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.
2999
+ * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.
3000
+ *
3001
+ * @returns {string} The decoded string.
3002
+ * @throws {Error} If `token_ids` is not a non-empty array of integers.
3003
+ */
3004
+ decode(
3005
+ token_ids,
3006
+ decode_args = {},
3007
+ ) {
3008
+ if (token_ids instanceof Tensor) {
3009
+ token_ids = prepareTensorForDecode(token_ids);
3010
+ }
3011
+
3012
+ if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {
3013
+ throw Error("token_ids must be a non-empty array of integers.");
3014
+ }
3015
+
3016
+ return this.decode_single(token_ids, decode_args)
3017
+ }
3018
+
3019
+ /**
3020
+ * Decode a single list of token ids to a string.
3021
+ * @param {number[]|bigint[]} token_ids List of token ids to decode
3022
+ * @param {Object} decode_args Optional arguments for decoding
3023
+ * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding
3024
+ * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.
3025
+ * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.
3026
+ * @returns {string} The decoded string
3027
+ */
3028
+ decode_single(
3029
+ token_ids,
3030
+ {
3031
+ skip_special_tokens = false,
3032
+ clean_up_tokenization_spaces = null,
3033
+ }
3034
+ ) {
3035
+ let tokens = this.model.convert_ids_to_tokens(token_ids);
3036
+ if (skip_special_tokens) {
3037
+ tokens = tokens.filter(x => !this.special_tokens.includes(x));
3038
+ }
3039
+
3040
+ // If `this.decoder` is null, we just join tokens with a space:
3041
+ // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835
3042
+ /** @type {string} */
3043
+ let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');
3044
+
3045
+ // Slight hack, but prevents having to pass `skip_special_tokens` to
3046
+ // each call to `decode`, which would lead to code duplication.
3047
+ if (this.decoder && this.decoder.end_of_word_suffix) {
3048
+ decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');
3049
+ if (skip_special_tokens) {
3050
+ decoded = decoded.trim();
3051
+ }
3052
+ }
3053
+
3054
+ if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {
3055
+ decoded = clean_up_tokenization(decoded);
3056
+ }
3057
+
3058
+ return decoded;
3059
+ }
3060
+ /**
3061
+ * Converts a list of message objects with `"role"` and `"content"` keys to a list of token
3062
+ * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to
3063
+ * determine the format and control tokens to use when converting.
3064
+ *
3065
+ * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.
3066
+ *
3067
+ * **Example:** Applying a chat template to a conversation.
3068
+ *
3069
+ * ```javascript
3070
+ * import { AutoTokenizer } from "@huggingface/transformers";
3071
+ *
3072
+ * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1");
3073
+ *
3074
+ * const chat = [
3075
+ * { "role": "user", "content": "Hello, how are you?" },
3076
+ * { "role": "assistant", "content": "I'm doing great. How can I help you today?" },
3077
+ * { "role": "user", "content": "I'd like to show off how chat templating works!" },
3078
+ * ]
3079
+ *
3080
+ * const text = tokenizer.apply_chat_template(chat, { tokenize: false });
3081
+ * // "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"
3082
+ *
3083
+ * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });
3084
+ * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]
3085
+ * ```
3086
+ *
3087
+ * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys,
3088
+ * representing the chat history so far.
3089
+ * @param {Object} options An optional object containing the following properties:
3090
+ * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If
3091
+ * this is not passed, the model's chat template will be used instead.
3092
+ * @param {Object[]} [options.tools=null]
3093
+ * A list of tools (callable functions) that will be accessible to the model. If the template does not
3094
+ * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,
3095
+ * giving the name, description and argument types for the tool. See our
3096
+ * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)
3097
+ * for more information.
3098
+ * @param {Record<string, string>[]} [options.documents=null]
3099
+ * A list of dicts representing documents that will be accessible to the model if it is performing RAG
3100
+ * (retrieval-augmented generation). If the template does not support RAG, this argument will have no
3101
+ * effect. We recommend that each document should be a dict containing "title" and "text" keys. Please
3102
+ * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)
3103
+ * for examples of passing documents with chat templates.
3104
+ * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate
3105
+ * the start of an assistant message. This is useful when you want to generate a response from the model.
3106
+ * Note that this argument will be passed to the chat template, and so it must be supported in the
3107
+ * template for this argument to have any effect.
3108
+ * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.
3109
+ * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.
3110
+ * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.
3111
+ * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.
3112
+ * If not specified, the tokenizer's `max_length` attribute will be used as a default.
3113
+ * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.
3114
+ * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false.
3115
+ * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.
3116
+ * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output.
3117
+ */
3118
+ apply_chat_template(conversation, {
3119
+ tools = null,
3120
+ documents = null,
3121
+ chat_template = null,
3122
+ add_generation_prompt = false,
3123
+ tokenize = true,
3124
+ padding = false,
3125
+ truncation = false,
3126
+ max_length = null,
3127
+ return_tensor = true,
3128
+ return_dict = false,
3129
+ tokenizer_kwargs = {},
3130
+ ...kwargs
3131
+ } = {}) {
3132
+
3133
+ // First, handle the cases when the model has a dict of multiple templates
3134
+ if (
3135
+ (this.chat_template && typeof this.chat_template === 'object')
3136
+ || this.chat_template === null
3137
+ ) {
3138
+ const template_dict = this.chat_template;
3139
+
3140
+ if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {
3141
+ // The user can pass the name of a template to the chat template argument instead of an entire template
3142
+ chat_template = template_dict[chat_template];
3143
+ } else if (chat_template === null && 'default' in template_dict) {
3144
+ chat_template = template_dict['default'];
3145
+ } else if (chat_template === null) {
3146
+ throw Error(
3147
+ `This model has multiple chat templates with no default specified! Please either pass a chat ` +
3148
+ `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +
3149
+ `template names are ${Object.keys(template_dict).sort()}.`
3150
+ )
3151
+ }
3152
+ } else {
3153
+ // These are the cases when the model has a single template
3154
+ // priority: `chat_template` argument > `tokenizer.chat_template`
3155
+ if (this.chat_template) {
3156
+ chat_template = this.chat_template;
3157
+ } else {
3158
+ throw Error(
3159
+ "Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template " +
3160
+ "argument was passed! For information about writing templates and setting the " +
3161
+ "tokenizer.chat_template attribute, please see the documentation at " +
3162
+ "https://huggingface.co/docs/transformers/main/en/chat_templating"
3163
+ )
3164
+ }
3165
+ }
3166
+ if (typeof chat_template !== 'string') {
3167
+ throw Error(`chat_template must be a string, but got ${typeof chat_template}`);
3168
+ }
3169
+
3170
+ // Compilation function uses a cache to avoid recompiling the same template
3171
+ let compiledTemplate = this._compiled_template_cache.get(chat_template);
3172
+ if (compiledTemplate === undefined) {
3173
+ compiledTemplate = new Template(chat_template);
3174
+ this._compiled_template_cache.set(chat_template, compiledTemplate);
3175
+ }
3176
+
3177
+ const special_tokens_map = Object.create(null);
3178
+ for (const key of SPECIAL_TOKEN_ATTRIBUTES) {
3179
+ const value = this.getToken(key);
3180
+ if (value) {
3181
+ special_tokens_map[key] = value;
3182
+ }
3183
+ }
3184
+
3185
+ const rendered = compiledTemplate.render({
3186
+ messages: conversation,
3187
+ add_generation_prompt,
3188
+ tools,
3189
+ documents,
3190
+ ...special_tokens_map,
3191
+ ...kwargs,
3192
+ });
3193
+
3194
+ if (tokenize) {
3195
+ const out = this._call(rendered, {
3196
+ add_special_tokens: false,
3197
+ padding,
3198
+ truncation,
3199
+ max_length,
3200
+ return_tensor,
3201
+ ...tokenizer_kwargs,
3202
+ });
3203
+ return return_dict ? out : out.input_ids;
3204
+ }
3205
+
3206
+ return rendered;
3207
+ }
3208
+ }
3209
+
3210
+ /**
3211
+ * BertTokenizer is a class used to tokenize text for BERT models.
3212
+ * @extends PreTrainedTokenizer
3213
+ */
3214
+ export class BertTokenizer extends PreTrainedTokenizer {
3215
+ return_token_type_ids = true;
3216
+ }
3217
+ /**
3218
+ * Albert tokenizer
3219
+ * @extends PreTrainedTokenizer
3220
+ */
3221
+ export class AlbertTokenizer extends PreTrainedTokenizer {
3222
+ return_token_type_ids = true;
3223
+ }
3224
+ export class MobileBertTokenizer extends PreTrainedTokenizer {
3225
+ return_token_type_ids = true;
3226
+ }
3227
+ export class SqueezeBertTokenizer extends PreTrainedTokenizer {
3228
+ return_token_type_ids = true;
3229
+ }
3230
+ export class DebertaTokenizer extends PreTrainedTokenizer {
3231
+ return_token_type_ids = true;
3232
+ }
3233
+ export class DebertaV2Tokenizer extends PreTrainedTokenizer {
3234
+ return_token_type_ids = true;
3235
+ }
3236
+ export class HerbertTokenizer extends PreTrainedTokenizer {
3237
+ return_token_type_ids = true;
3238
+ }
3239
+ export class ConvBertTokenizer extends PreTrainedTokenizer {
3240
+ return_token_type_ids = true;
3241
+ }
3242
+ export class RoFormerTokenizer extends PreTrainedTokenizer {
3243
+ return_token_type_ids = true;
3244
+ }
3245
+ export class DistilBertTokenizer extends PreTrainedTokenizer { }
3246
+ export class CamembertTokenizer extends PreTrainedTokenizer { }
3247
+ export class XLMTokenizer extends PreTrainedTokenizer {
3248
+ return_token_type_ids = true;
3249
+
3250
+ constructor(tokenizerJSON, tokenizerConfig) {
3251
+ super(tokenizerJSON, tokenizerConfig);
3252
+ console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')
3253
+ }
3254
+ }
3255
+ export class ElectraTokenizer extends PreTrainedTokenizer {
3256
+ return_token_type_ids = true;
3257
+ }
3258
+
3259
+ export class T5Tokenizer extends PreTrainedTokenizer { }
3260
+ export class GPT2Tokenizer extends PreTrainedTokenizer { }
3261
+ export class BartTokenizer extends PreTrainedTokenizer { }
3262
+ export class MBartTokenizer extends PreTrainedTokenizer {
3263
+ constructor(tokenizerJSON, tokenizerConfig) {
3264
+ super(tokenizerJSON, tokenizerConfig);
3265
+
3266
+ this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;
3267
+ this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));
3268
+ this.lang_to_token = x => x; // Identity function
3269
+ }
3270
+
3271
+ /**
3272
+ * Helper function to build translation inputs for an `MBartTokenizer`.
3273
+ * @param {string|string[]} raw_inputs The text to tokenize.
3274
+ * @param {Object} tokenizer_options Options to be sent to the tokenizer
3275
+ * @param {Object} generate_kwargs Generation options.
3276
+ * @returns {Object} Object to be passed to the model.
3277
+ */
3278
+ _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
3279
+ return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
3280
+ }
3281
+ }
3282
+ export class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer
3283
+
3284
+ export class RobertaTokenizer extends PreTrainedTokenizer { }
3285
+
3286
+ export class BloomTokenizer extends PreTrainedTokenizer {
3287
+
3288
+ constructor(tokenizerJSON, tokenizerConfig) {
3289
+ // Override the default (invalid) regex of the pretokenizer.
3290
+ // For more information, see https://github.com/xenova/transformers.js/issues/94
3291
+ const splitChars = '.,!?\u2026\u3002\uff0c\u3001\u0964\u06d4\u060c';
3292
+ const patternObject = tokenizerJSON.pre_tokenizer?.pretokenizers[0]?.pattern;
3293
+ if (patternObject && patternObject.Regex === ` ?[^(\\s|[${splitChars}])]+`) {
3294
+ patternObject.Regex = ` ?[^\\s${splitChars}]+`;
3295
+ }
3296
+ super(tokenizerJSON, tokenizerConfig);
3297
+ }
3298
+ }
3299
+
3300
+ const SPIECE_UNDERLINE = "▁";
3301
+
3302
+ export class LlamaTokenizer extends PreTrainedTokenizer {
3303
+
3304
+ padding_side = 'left';
3305
+
3306
+ constructor(tokenizerJSON, tokenizerConfig) {
3307
+ super(tokenizerJSON, tokenizerConfig);
3308
+
3309
+ this.legacy = tokenizerConfig.legacy ?? true;
3310
+ if (!this.legacy) {
3311
+ // See https://github.com/huggingface/transformers/pull/24565 for more information
3312
+ this.normalizer = null;
3313
+ this.pre_tokenizer = new MetaspacePreTokenizer({
3314
+ replacement: SPIECE_UNDERLINE,
3315
+ add_prefix_space: true,
3316
+ prepend_scheme: "first",
3317
+ });
3318
+ }
3319
+ }
3320
+
3321
+ /**
3322
+ * Helper function to handle legacy encoding of SPM tokenizers.
3323
+ * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387
3324
+ * @param {string} text The text to encode.
3325
+ * @returns {string[]} The encoded tokens.
3326
+ */
3327
+ _encode_text(text) {
3328
+ if (text === null) return null;
3329
+
3330
+ if (this.legacy || text.length === 0) {
3331
+ return super._encode_text(text);
3332
+ }
3333
+
3334
+ let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " "));
3335
+ if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {
3336
+ tokens = tokens.slice(1);
3337
+ }
3338
+ return tokens;
3339
+ }
3340
+ }
3341
+ export class CodeLlamaTokenizer extends PreTrainedTokenizer { }
3342
+
3343
+ export class XLMRobertaTokenizer extends PreTrainedTokenizer { }
3344
+ export class MPNetTokenizer extends PreTrainedTokenizer { }
3345
+
3346
+ export class FalconTokenizer extends PreTrainedTokenizer { }
3347
+
3348
+ export class GPTNeoXTokenizer extends PreTrainedTokenizer { }
3349
+
3350
+ export class EsmTokenizer extends PreTrainedTokenizer { }
3351
+
3352
+ export class Qwen2Tokenizer extends PreTrainedTokenizer { }
3353
+
3354
+ export class GemmaTokenizer extends PreTrainedTokenizer { }
3355
+
3356
+ export class Grok1Tokenizer extends PreTrainedTokenizer { }
3357
+
3358
+ /**
3359
+ * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.
3360
+ * @param {PreTrainedTokenizer} self The tokenizer instance.
3361
+ * @param {string|string[]} raw_inputs The text to tokenize.
3362
+ * @param {Object} tokenizer_options Options to be sent to the tokenizer
3363
+ * @param {Object} generate_kwargs Generation options.
3364
+ * @returns {Object} Object to be passed to the model.
3365
+ * @private
3366
+ */
3367
+ function _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {
3368
+ if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {
3369
+ throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')
3370
+ }
3371
+ if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {
3372
+ throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')
3373
+ }
3374
+ if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {
3375
+ throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')
3376
+ }
3377
+ const src_lang_token = generate_kwargs.src_lang;
3378
+ const tgt_lang_token = generate_kwargs.tgt_lang;
3379
+
3380
+ // Check that the target language is valid:
3381
+ if (!self.language_codes.includes(tgt_lang_token)) {
3382
+ throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);
3383
+ }
3384
+
3385
+ // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.
3386
+ if (src_lang_token !== undefined) {
3387
+ // Check that the source language is valid:
3388
+ if (!self.language_codes.includes(src_lang_token)) {
3389
+ throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);
3390
+ }
3391
+
3392
+ // In the same way as the Python library, we override the post-processor
3393
+ // to force the source language to be first:
3394
+ for (const item of self.post_processor.config.single) {
3395
+ if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {
3396
+ item.SpecialToken.id = self.lang_to_token(src_lang_token);
3397
+ break;
3398
+ }
3399
+ }
3400
+ // TODO: Do the same for pair?
3401
+ }
3402
+
3403
+ // Override the `forced_bos_token_id` to force the correct language
3404
+ generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];
3405
+
3406
+ return self._call(raw_inputs, tokenizer_options);
3407
+ }
3408
+
3409
+ /**
3410
+ * The NllbTokenizer class is used to tokenize text for NLLB ("No Language Left Behind") models.
3411
+ *
3412
+ * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project
3413
+ * that open-sources models capable of delivering high-quality translations directly
3414
+ * between any pair of 200+ languages — including low-resource languages like Asturian,
3415
+ * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,
3416
+ * regardless of their language preferences. For more information, check out their
3417
+ * [paper](https://arxiv.org/abs/2207.04672).
3418
+ *
3419
+ * For a list of supported languages (along with their language codes),
3420
+ * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}
3421
+ */
3422
+ export class NllbTokenizer extends PreTrainedTokenizer {
3423
+
3424
+ constructor(tokenizerJSON, tokenizerConfig) {
3425
+ super(tokenizerJSON, tokenizerConfig);
3426
+
3427
+ this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;
3428
+ this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));
3429
+ this.lang_to_token = x => x; // Identity function
3430
+ }
3431
+
3432
+ /**
3433
+ * Helper function to build translation inputs for an `NllbTokenizer`.
3434
+ * @param {string|string[]} raw_inputs The text to tokenize.
3435
+ * @param {Object} tokenizer_options Options to be sent to the tokenizer
3436
+ * @param {Object} generate_kwargs Generation options.
3437
+ * @returns {Object} Object to be passed to the model.
3438
+ */
3439
+ _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
3440
+ return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
3441
+ }
3442
+ }
3443
+
3444
+ /**
3445
+ * The M2M100Tokenizer class is used to tokenize text for M2M100 ("Many-to-Many") models.
3446
+ *
3447
+ * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many
3448
+ * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125)
3449
+ * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.
3450
+ *
3451
+ * For a list of supported languages (along with their language codes),
3452
+ * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}
3453
+ */
3454
+ export class M2M100Tokenizer extends PreTrainedTokenizer {
3455
+ constructor(tokenizerJSON, tokenizerConfig) {
3456
+ super(tokenizerJSON, tokenizerConfig);
3457
+
3458
+ this.languageRegex = /^__[a-z]{2,3}__$/;
3459
+ this.language_codes = this.special_tokens
3460
+ .filter(x => this.languageRegex.test(x))
3461
+ .map(x => x.slice(2, -2));
3462
+ this.lang_to_token = x => `__${x}__`;
3463
+ }
3464
+
3465
+ /**
3466
+ * Helper function to build translation inputs for an `M2M100Tokenizer`.
3467
+ * @param {string|string[]} raw_inputs The text to tokenize.
3468
+ * @param {Object} tokenizer_options Options to be sent to the tokenizer
3469
+ * @param {Object} generate_kwargs Generation options.
3470
+ * @returns {Object} Object to be passed to the model.
3471
+ */
3472
+ _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
3473
+ return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
3474
+ }
3475
+ }
3476
+
3477
+ /**
3478
+ * WhisperTokenizer tokenizer
3479
+ * @extends PreTrainedTokenizer
3480
+ */
3481
+ export class WhisperTokenizer extends PreTrainedTokenizer {
3482
+
3483
+ get timestamp_begin() {
3484
+ return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1;
3485
+ }
3486
+
3487
+ /**
3488
+ * Decodes automatic speech recognition (ASR) sequences.
3489
+ * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.
3490
+ * @param {Object} options The options to use for decoding.
3491
+ * @returns {Array<string|{chunks?: undefined|Array<{language: string|null, timestamp: Array<number|null>, text: string}>}>} The decoded sequences.
3492
+ */
3493
+ _decode_asr(sequences, {
3494
+ return_timestamps = false,
3495
+ return_language = false,
3496
+ time_precision = null,
3497
+ force_full_sequences = true
3498
+ } = {}) {
3499
+ // Set force_full_sequences=false if you want streaming
3500
+ // TODO add support for `return_language`
3501
+
3502
+ // Internal method meant to only be used by asr pipeline.
3503
+ // Handles all the little quirks specific to whisper to handle
3504
+ // the various options not allowed in other seq2seq models
3505
+
3506
+ // =========== Overview ============
3507
+ // - iterate over all outputs
3508
+ // - all tokens within output
3509
+ // - Each token can be
3510
+ // - language token
3511
+ // - special token
3512
+ // - timestamp token
3513
+ // - text token
3514
+ // - We accumulate the text tokens.
3515
+ // - We split on end timestamps
3516
+ // - Lots of complexity comes from stride and timestamps
3517
+
3518
+ if (time_precision === null) {
3519
+ throw Error("Must specify time_precision")
3520
+ }
3521
+ let last_language = null;
3522
+
3523
+ const returnWordTimestamps = return_timestamps === "word";
3524
+
3525
+ function new_chunk() {
3526
+ return { "language": last_language, "timestamp": [null, null], "text": "" };
3527
+ }
3528
+
3529
+ // Welcome to the state machine!
3530
+ const chunks = [];
3531
+ let chunk = new_chunk();
3532
+ let time_offset = 0.0;
3533
+ const timestamp_begin = this.timestamp_begin;
3534
+
3535
+ let previous_tokens = [];
3536
+ let previous_token_timestamps = [];
3537
+
3538
+ let skip = false;
3539
+ let right_stride_start = null;
3540
+
3541
+
3542
+ const all_special_ids = new Set(this.all_special_ids);
3543
+
3544
+ for (const output of sequences) {
3545
+ // NOTE: python version has batches, so it uses [0]
3546
+ const token_ids = output.tokens;
3547
+ const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;
3548
+
3549
+ // These keep track of timestamps within strides, which need
3550
+ // to be skipped and resolve all tokens in a single chunk.
3551
+ let last_timestamp = null;
3552
+ let first_timestamp = timestamp_begin;
3553
+
3554
+ if ("stride" in output) {
3555
+ const [chunk_len, stride_left, stride_right] = output.stride;
3556
+
3557
+ // Offset the timings to account for the other `model_outputs`.
3558
+ time_offset -= stride_left;
3559
+ right_stride_start = chunk_len - stride_right;
3560
+
3561
+ // Keeping track of timestamps within strides
3562
+ // We're going to NOT split on those, and delay until we're
3563
+ // out of BOTH stride. Otherwise lots of issues occur and
3564
+ // corner cases
3565
+ if (stride_left) {
3566
+ first_timestamp = stride_left / time_precision + timestamp_begin;
3567
+ }
3568
+
3569
+ if (stride_right) {
3570
+ for (let i = token_ids.length - 1; i >= 0; --i) {
3571
+ const token = Number(token_ids[i]);
3572
+ if (token >= timestamp_begin) {
3573
+ // There can be several token in the right stride
3574
+ // But the last one is ALWAYS going to be skipped
3575
+ if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {
3576
+ break;
3577
+ }
3578
+ last_timestamp = token;
3579
+ }
3580
+ }
3581
+ }
3582
+ }
3583
+
3584
+ let current_tokens = [];
3585
+ let current_token_timestamps = [];
3586
+
3587
+ // - all tokens within output
3588
+ for (let i = 0; i < token_ids.length; ++i) {
3589
+ const token = Number(token_ids[i]);
3590
+ // 4 possible states for each token
3591
+ // - 1/ Language code
3592
+ // - 2/ all other special tokens (which we ignore)
3593
+ // - 3/ Timestamp
3594
+ // - 4/ Regular text
3595
+
3596
+ if (all_special_ids.has(token)) {
3597
+ const text = this.decode([token]);
3598
+ const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));
3599
+
3600
+ if (language !== undefined) {
3601
+ // 1/ Indeed some language
3602
+ // TODO Handle when language is different from the previous
3603
+ // one, and we cannot use timestamped tokens to create chunks
3604
+ if (last_language !== null && language !== last_language && !return_timestamps) {
3605
+ previous_tokens.push(current_tokens);
3606
+ const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];
3607
+ const resolved_text = this.decode(resolved_tokens);
3608
+ chunk.text = resolved_text;
3609
+ chunks.push(chunk);
3610
+
3611
+ // Flush all our temporary context
3612
+ previous_tokens = [];
3613
+ current_tokens = [];
3614
+ chunk = new_chunk();
3615
+ }
3616
+
3617
+ last_language = chunk.language = language;
3618
+ } else {
3619
+ // 2/ This is a regular special token, ignoring it
3620
+ }
3621
+ } else if (token >= timestamp_begin) {
3622
+ // 3/ Timestamp token
3623
+ const time = (token - timestamp_begin) * time_precision + time_offset;
3624
+ const rounded_time = round(time, 2);
3625
+
3626
+ if (last_timestamp !== null && token >= last_timestamp) {
3627
+ // Whisper outputted a timestamp token, but it falls within
3628
+ // our stride, so we're going to skip it for the time being
3629
+ // and resolve this later
3630
+ // Skip is necessary because timestamp tokens always come
3631
+ // by pair, so we need to skip the next one too (which would mark the start of another chunk).
3632
+ skip = true;
3633
+ } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {
3634
+ skip = false;
3635
+ } else if (chunk.timestamp[0] === null) {
3636
+ chunk.timestamp[0] = rounded_time;
3637
+ } else {
3638
+ // This is the end of the timestamp chunk
3639
+ if (rounded_time === chunk.timestamp[0]) {
3640
+ // This is a bug in timestamp token output
3641
+ // where we're taking the duplicate token
3642
+ // as a stop where it should be a start.
3643
+ // This is an issue in the underlying model output
3644
+ // Let's just skip it so it becomes de-factor a start agin
3645
+ } else {
3646
+ chunk.timestamp[1] = rounded_time;
3647
+
3648
+ // Handling merges
3649
+ previous_tokens.push(current_tokens)
3650
+
3651
+ if (returnWordTimestamps) {
3652
+ previous_token_timestamps.push(current_token_timestamps);
3653
+ }
3654
+ const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(
3655
+ previous_tokens, previous_token_timestamps
3656
+ )
3657
+
3658
+ const resolved_text = this.decode(resolved_tokens)
3659
+ chunk.text = resolved_text
3660
+
3661
+ if (returnWordTimestamps) {
3662
+ chunk.words = this.collateWordTimestamps(
3663
+ resolved_tokens, resolved_token_timestamps, last_language,
3664
+ )
3665
+ }
3666
+
3667
+ chunks.push(chunk)
3668
+
3669
+ // Flush all our temporary context
3670
+ previous_tokens = []
3671
+ current_tokens = []
3672
+ previous_token_timestamps = []
3673
+ current_token_timestamps = []
3674
+ chunk = new_chunk()
3675
+ }
3676
+ }
3677
+
3678
+ } else {
3679
+ // 4/ Regular token
3680
+ // We just append to the list of all tokens so we can handle
3681
+ // merges later and decode into text.
3682
+ current_tokens.push(token)
3683
+
3684
+ if (returnWordTimestamps) {
3685
+ let start_time = round(token_timestamps[i] + time_offset, 2);
3686
+
3687
+ let end_time;
3688
+ if (i + 1 < token_timestamps.length) {
3689
+ end_time = round(token_timestamps[i + 1] + time_offset, 2);
3690
+
3691
+ // Do not allow punctuation-only tokens to have a duration.
3692
+ // This prevents long pauses from messing up the timestamps.
3693
+ const decoded_text = this.decode([token]);
3694
+ if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) {
3695
+ // Add `time_precision` to avoid overlapping timestamps
3696
+ end_time = round(Math.min(start_time + time_precision, end_time), 2);
3697
+ }
3698
+ } else {
3699
+ // should never happen
3700
+ end_time = null;
3701
+ }
3702
+ current_token_timestamps.push([start_time, end_time]);
3703
+ }
3704
+
3705
+ }
3706
+ }
3707
+
3708
+ if ('stride' in output) {
3709
+ const [chunk_len, stride_left, stride_right] = output.stride;
3710
+ time_offset += chunk_len - stride_right
3711
+ }
3712
+
3713
+ // Leftover tokens
3714
+ if (current_tokens.length > 0) {
3715
+ previous_tokens.push(current_tokens)
3716
+ if (returnWordTimestamps) {
3717
+ previous_token_timestamps.push(current_token_timestamps);
3718
+ }
3719
+ } else if (previous_tokens.every(p => p.length === 0)) {
3720
+ // Flushing previous tokens (END)"
3721
+ chunk = new_chunk()
3722
+ previous_tokens = []
3723
+ current_tokens = []
3724
+ previous_token_timestamps = [];
3725
+ current_token_timestamps = [];
3726
+ }
3727
+
3728
+ }
3729
+
3730
+ if (previous_tokens.length > 0) {
3731
+ if (force_full_sequences && return_timestamps) {
3732
+ // Last token should always be timestamps, so there shouldn't be
3733
+ // leftover
3734
+ throw new Error(
3735
+ "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. " +
3736
+ "Also make sure WhisperTimeStampLogitsProcessor was used during generation."
3737
+ );
3738
+ }
3739
+
3740
+ // Happens when we don't use timestamps
3741
+ const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);
3742
+
3743
+ // Flushing previous tokens (FINAL)
3744
+ const resolved_text = this.decode(resolved_tokens);
3745
+ chunk.text = resolved_text;
3746
+ if (returnWordTimestamps) {
3747
+ chunk.words = this.collateWordTimestamps(
3748
+ resolved_tokens, resolved_token_timestamps, last_language,
3749
+ )
3750
+ }
3751
+ chunks.push(chunk);
3752
+ }
3753
+
3754
+ let optional = Object.create(null);
3755
+
3756
+ // Preparing and cleaning up the pipeline output
3757
+ const full_text = chunks.map(chunk => chunk.text).join('');
3758
+ if (return_timestamps || return_language) {
3759
+ for (let i = 0; i < chunks.length; ++i) {
3760
+ const chunk = chunks[i];
3761
+ if (!return_timestamps) {
3762
+ delete chunk["timestamp"];
3763
+ }
3764
+
3765
+ if (!return_language) {
3766
+ delete chunk["language"];
3767
+ }
3768
+ }
3769
+ if (returnWordTimestamps) {
3770
+ const new_chunks = [];
3771
+ for (const chunk of chunks) {
3772
+ for (const word of chunk.words) {
3773
+ new_chunks.push(word);
3774
+ }
3775
+ }
3776
+ optional = { "chunks": new_chunks };
3777
+ } else {
3778
+ optional = { "chunks": chunks };
3779
+ }
3780
+ }
3781
+ return [full_text, optional];
3782
+
3783
+ }
3784
+
3785
+ /**
3786
+ * Finds the longest common sequence among the provided sequences.
3787
+ * @param {number[][]} sequences An array of sequences of token ids to compare.
3788
+ * @returns {number[][]} The longest common sequence found.
3789
+ * @throws {Error} If there is a bug within the function.
3790
+ * @private
3791
+ */
3792
+ findLongestCommonSequence(sequences, token_timestamp_sequences = null) {
3793
+ // It would be much harder to do O(n) because of fault tolerance.
3794
+ // We actually have a really good property which is that the total sequence
3795
+ // MUST be those subsequences in order.
3796
+ // If token_timestamp_sequences is provided, will split those sequences in
3797
+ // exactly the same way.
3798
+ let leftSequence = sequences[0];
3799
+ let leftLength = leftSequence.length;
3800
+ let totalSequence = [];
3801
+
3802
+ const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;
3803
+ let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;
3804
+ let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;
3805
+ for (let i = 1; i < sequences.length; ++i) {
3806
+ const rightSequence = sequences[i];
3807
+ let max = 0.0;
3808
+ let maxIndices = [leftLength, leftLength, 0, 0];
3809
+ // Here we're sliding matches
3810
+ // [a, b, c, d]
3811
+ // [c, d, f]
3812
+ // = [c] == [d]
3813
+
3814
+ // [a, b, c, d]
3815
+ // [c, d, f]
3816
+ // = [c, d] == [c, d]
3817
+
3818
+
3819
+ // [a, b, c, d]
3820
+ // [c, d, f]
3821
+
3822
+ // = [b, c, d] == [c, d, f]
3823
+
3824
+ // [a, b, c, d]
3825
+ // [c, d, f]
3826
+
3827
+ // [a, b, c] == [c, d, f]
3828
+
3829
+ // [a, b, c, d]
3830
+ // [d, f]
3831
+
3832
+ // [a, b] == [d, f]
3833
+
3834
+ // [a, b, c, d]
3835
+ // [f]
3836
+
3837
+ // [a] == [f]
3838
+
3839
+ const rightLength = rightSequence.length;
3840
+ for (let j = 1; j < leftLength + rightLength; ++j) {
3841
+ // Slightly convoluted because we don't want out of bound indices
3842
+ // This will be necessary for a small conflict resolution optimization
3843
+ // later
3844
+ const leftStart = Math.max(0, leftLength - j);
3845
+ const leftStop = Math.min(leftLength, leftLength + rightLength - j);
3846
+ const left = leftSequence.slice(leftStart, leftStop);
3847
+ const rightStart = Math.max(0, j - leftLength);
3848
+ const rightStop = Math.min(rightLength, j);
3849
+ const right = rightSequence.slice(rightStart, rightStop);
3850
+ if (left.length !== right.length) {
3851
+ throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");
3852
+ }
3853
+
3854
+ let matches;
3855
+ if (use_token_timestamp_sequences) {
3856
+ // Get length of longest subsequence of tokens that match
3857
+ // and have timestamps that are in order
3858
+ matches = left.filter((elem, idx) => (
3859
+ elem === right[idx]
3860
+ && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx]
3861
+ )).length;
3862
+ } else {
3863
+ matches = left.filter((elem, idx) => elem === right[idx]).length;
3864
+ }
3865
+
3866
+ // epsilon to favor long perfect matches
3867
+ const eps = j / 10000.0;
3868
+ const matching = matches / j + eps;
3869
+ if (matches > 1 && matching > max) {
3870
+ max = matching;
3871
+ maxIndices = [leftStart, leftStop, rightStart, rightStop];
3872
+ }
3873
+ }
3874
+ const [leftStart, leftStop, rightStart, rightStop] = maxIndices;
3875
+ const leftMid = Math.floor((leftStop + leftStart) / 2);
3876
+ const rightMid = Math.floor((rightStop + rightStart) / 2);
3877
+ totalSequence.push(...leftSequence.slice(0, leftMid));
3878
+ leftSequence = rightSequence.slice(rightMid);
3879
+ leftLength = leftSequence.length;
3880
+
3881
+ if (use_token_timestamp_sequences) {
3882
+ total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));
3883
+ left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);
3884
+ }
3885
+ }
3886
+ totalSequence.push(...leftSequence);
3887
+
3888
+ if (use_token_timestamp_sequences) {
3889
+ total_token_timestamp_sequence.push(...left_token_timestamp_sequence);
3890
+ return [totalSequence, total_token_timestamp_sequence];
3891
+ } else {
3892
+ return [totalSequence, []];
3893
+ }
3894
+ }
3895
+
3896
+ /** @private */
3897
+ collateWordTimestamps(tokens, token_timestamps, language) {
3898
+
3899
+ const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);
3900
+
3901
+ const timings = [];
3902
+ for (let i = 0; i < words.length; ++i) {
3903
+ const indices = token_indices[i];
3904
+ timings.push({
3905
+ text: words[i],
3906
+ timestamp: [
3907
+ token_timestamps[indices.at(0)][0],
3908
+ token_timestamps[indices.at(-1)][1],
3909
+ ],
3910
+ });
3911
+ }
3912
+ return timings;
3913
+ }
3914
+
3915
+ /**
3916
+ * Groups tokens by word. Returns a tuple containing a list of strings with the words,
3917
+ * and a list of `token_id` sequences with the tokens making up each word.
3918
+ * @param {number[]} tokens
3919
+ * @param {string} [language]
3920
+ * @param {string} prepend_punctionations
3921
+ * @param {string} append_punctuations
3922
+ *
3923
+ * @private
3924
+ */
3925
+ combineTokensIntoWords(tokens, language, prepend_punctionations = "\"'“¡¿([{-", append_punctuations = "\"'.。,,!!??::”)]}、") {
3926
+ language = language ?? 'english';
3927
+
3928
+ let words, word_tokens, token_indices;
3929
+
3930
+ if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) {
3931
+ // These languages don't typically use spaces.
3932
+ [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)
3933
+ } else {
3934
+ [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)
3935
+ }
3936
+
3937
+ return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);
3938
+ }
3939
+
3940
+ /** @type {PreTrainedTokenizer['decode']} */
3941
+ decode(
3942
+ token_ids,
3943
+ decode_args,
3944
+ ) {
3945
+ let text;
3946
+ // @ts-ignore
3947
+ if (decode_args?.decode_with_timestamps) {
3948
+ if (token_ids instanceof Tensor) {
3949
+ token_ids = prepareTensorForDecode(token_ids);
3950
+ }
3951
+ text = this.decodeWithTimestamps(token_ids, decode_args);
3952
+ } else {
3953
+ text = super.decode(token_ids, decode_args);
3954
+ }
3955
+ // TODO: implement offsets
3956
+ // if (decode_args.output_offsets) {
3957
+ // let offsets = this.computeOffsets
3958
+ // }
3959
+ return text;
3960
+ }
3961
+
3962
+ /**
3963
+ * @param {number[]|bigint[]} token_ids List of token IDs to decode.
3964
+ * @param {Object} decode_args Optional arguments for decoding
3965
+ * @private
3966
+ */
3967
+ decodeWithTimestamps(token_ids, decode_args) {
3968
+ const time_precision = decode_args?.time_precision ?? 0.02;
3969
+
3970
+ const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;
3971
+ /**@type {Array} */
3972
+ let outputs = [[]];
3973
+ for (let token of token_ids) {
3974
+ token = Number(token);
3975
+ if (token >= timestamp_begin) {
3976
+ const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2);
3977
+ outputs.push(`<|${timestamp}|>`);
3978
+ outputs.push([]);
3979
+ } else {
3980
+ outputs[outputs.length - 1].push(token);
3981
+ }
3982
+ }
3983
+ outputs = outputs.map(
3984
+ s => typeof s === 'string' ? s : super.decode(s, decode_args)
3985
+ )
3986
+
3987
+ return outputs.join('');
3988
+ }
3989
+
3990
+ /**
3991
+ * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.
3992
+ * @param {number[]} tokens
3993
+ * @returns {*}
3994
+ * @private
3995
+ */
3996
+ splitTokensOnUnicode(tokens) {
3997
+ const decoded_full = this.decode(tokens, {
3998
+ // @ts-ignore
3999
+ decode_with_timestamps: true,
4000
+ });
4001
+ const replacement_char = '\uFFFD';
4002
+
4003
+ const words = []
4004
+ const word_tokens = []
4005
+ const token_indices = []
4006
+ let current_tokens = []
4007
+ let current_indices = []
4008
+ let unicode_offset = 0
4009
+
4010
+ for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {
4011
+ const token = tokens[token_idx];
4012
+
4013
+ current_tokens.push(token);
4014
+ current_indices.push(token_idx);
4015
+
4016
+ const decoded = this.decode(current_tokens, {
4017
+ // @ts-ignore
4018
+ decode_with_timestamps: true,
4019
+ });
4020
+
4021
+ if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {
4022
+ words.push(decoded)
4023
+ word_tokens.push(current_tokens)
4024
+ token_indices.push(current_indices)
4025
+ current_tokens = []
4026
+ current_indices = []
4027
+ unicode_offset += decoded.length;
4028
+ }
4029
+
4030
+ }
4031
+
4032
+ return [words, word_tokens, token_indices]
4033
+ }
4034
+
4035
+ /**
4036
+ * Combine tokens into words by splitting at whitespace and punctuation tokens.
4037
+ * @param {number[]} tokens
4038
+ * @private
4039
+ */
4040
+ splitTokensOnSpaces(tokens) {
4041
+
4042
+ const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);
4043
+
4044
+ const words = []
4045
+ const word_tokens = []
4046
+ const token_indices = []
4047
+
4048
+ const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');
4049
+
4050
+ for (let i = 0; i < subwords.length; ++i) {
4051
+
4052
+ const subword = subwords[i];
4053
+ const subword_tokens = subword_tokens_list[i];
4054
+ const subword_indices = subword_indices_list[i];
4055
+
4056
+ // @ts-ignore
4057
+ const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');
4058
+ const with_space = subword.startsWith(' ');
4059
+ const trimmed = subword.trim();
4060
+ const punctuation = punctuationRegex.test(trimmed);
4061
+
4062
+ if (special || with_space || punctuation || words.length === 0) {
4063
+ words.push(subword);
4064
+ word_tokens.push(subword_tokens);
4065
+ token_indices.push(subword_indices);
4066
+ } else {
4067
+ const ix = words.length - 1;
4068
+ words[ix] += subword;
4069
+ word_tokens[ix].push(...subword_tokens);
4070
+ token_indices[ix].push(...subword_indices);
4071
+ }
4072
+ }
4073
+
4074
+ return [words, word_tokens, token_indices];
4075
+
4076
+ }
4077
+
4078
+ /**
4079
+ * Merges punctuation tokens with neighboring words.
4080
+ * @param {string[]} words
4081
+ * @param {number[][]} tokens
4082
+ * @param {number[][]} indices
4083
+ * @param {string} prepended
4084
+ * @param {string} appended
4085
+ * @private
4086
+ */
4087
+ mergePunctuations(words, tokens, indices, prepended, appended) {
4088
+
4089
+ const newWords = structuredClone(words);
4090
+ const newTokens = structuredClone(tokens);
4091
+ const newIndices = structuredClone(indices);
4092
+
4093
+
4094
+ // prepend punctuations
4095
+ let i = newWords.length - 2;
4096
+ let j = newWords.length - 1;
4097
+
4098
+ while (i >= 0) {
4099
+ if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {
4100
+ newWords[j] = newWords[i] + newWords[j];
4101
+ newTokens[j] = mergeArrays(newTokens[i], newTokens[j]);
4102
+ newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);
4103
+ newWords[i] = '';
4104
+ newTokens[i] = [];
4105
+ newIndices[i] = [];
4106
+ } else {
4107
+ j = i;
4108
+ }
4109
+ --i;
4110
+ }
4111
+
4112
+ // append punctuations
4113
+ i = 0;
4114
+ j = 1;
4115
+ while (j < newWords.length) {
4116
+ if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {
4117
+ newWords[i] += newWords[j];
4118
+ newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);
4119
+ newIndices[i] = mergeArrays(newIndices[i], newIndices[j]);
4120
+ newWords[j] = '';
4121
+ newTokens[j] = [];
4122
+ newIndices[j] = [];
4123
+ } else {
4124
+ i = j;
4125
+ }
4126
+ ++j;
4127
+ }
4128
+
4129
+ return [
4130
+ newWords.filter(x => x),
4131
+ newTokens.filter(x => x.length > 0),
4132
+ newIndices.filter(x => x.length > 0),
4133
+ ]
4134
+ }
4135
+
4136
+ /**
4137
+ * Helper function to build translation inputs for a `WhisperTokenizer`,
4138
+ * depending on the language, task, and whether to predict timestamp tokens.
4139
+ *
4140
+ * Used to override the prefix tokens appended to the start of the label sequence.
4141
+ *
4142
+ * **Example: Get ids for a language**
4143
+ * ```javascript
4144
+ * // instantiate the tokenizer and set the prefix token to Spanish
4145
+ * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny');
4146
+ * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' });
4147
+ * // [(1, 50262), (2, 50363)]
4148
+ * ```
4149
+ *
4150
+ * @param {Object} options Options to generate the decoder prompt.
4151
+ * @param {string} [options.language] The language of the transcription text.
4152
+ * The corresponding language id token is appended to the start of the sequence for multilingual
4153
+ * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended
4154
+ * to the start of sequence.
4155
+ * @param {string} [options.task] Task identifier to append at the start of sequence (if any).
4156
+ * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and
4157
+ * "translate" for speech translation.
4158
+ * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence.
4159
+ * @returns {number[][]} The decoder prompt ids.
4160
+ */
4161
+ get_decoder_prompt_ids({
4162
+ language = null,
4163
+ task = null,
4164
+ no_timestamps = true,
4165
+ } = {}) {
4166
+
4167
+ // <|lang_id|> <|task|> <|notimestamps|>
4168
+
4169
+ const forced_decoder_ids = [];
4170
+
4171
+ if (language) {
4172
+ // User wishes to specify the language
4173
+ const language_code = whisper_language_to_code(language);
4174
+ const language_token_id = this.model.tokens_to_ids.get(`<|${language_code}|>`);
4175
+ if (language_token_id === undefined) {
4176
+ throw new Error(`Unable to find language "${language_code}" in model vocabulary. Please report this issue at ${GITHUB_ISSUE_URL}.`)
4177
+ }
4178
+
4179
+ forced_decoder_ids.push(language_token_id);
4180
+ } else {
4181
+ // No token will be forced, which leaves the model to predict the language
4182
+ forced_decoder_ids.push(null);
4183
+ }
4184
+
4185
+ if (task) {
4186
+ task = task.toLowerCase();
4187
+ if (task !== 'transcribe' && task !== 'translate') {
4188
+ throw new Error(`Task "${task}" is not supported. Must be one of: ["transcribe", "translate"]`);
4189
+ }
4190
+
4191
+ const task_token_id = this.model.tokens_to_ids.get(`<|${task}|>`);
4192
+ if (task_token_id === undefined) {
4193
+ throw new Error(`Unable to find task "${task}" in model vocabulary. Please report this issue at ${GITHUB_ISSUE_URL}.`)
4194
+ }
4195
+
4196
+ forced_decoder_ids.push(task_token_id);
4197
+ } else {
4198
+ // No token will be forced, which leaves the model to predict the task
4199
+ forced_decoder_ids.push(null);
4200
+ }
4201
+
4202
+ if (no_timestamps) {
4203
+ const no_timestamps_id = this.model.tokens_to_ids.get(`<|notimestamps|>`);
4204
+ if (no_timestamps_id === undefined) {
4205
+ throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${GITHUB_ISSUE_URL}.`);
4206
+ }
4207
+
4208
+ forced_decoder_ids.push(no_timestamps_id);
4209
+ }
4210
+
4211
+ return forced_decoder_ids.map((x, i) => [i + 1, x]).filter(x => x[1] !== null);
4212
+
4213
+ }
4214
+ }
4215
+ export class CodeGenTokenizer extends PreTrainedTokenizer { }
4216
+ export class CLIPTokenizer extends PreTrainedTokenizer { }
4217
+ export class SiglipTokenizer extends PreTrainedTokenizer { }
4218
+
4219
+ /**
4220
+ * @todo This model is not yet supported by Hugging Face's "fast" tokenizers library (https://github.com/huggingface/tokenizers).
4221
+ * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.
4222
+ */
4223
+ export class MarianTokenizer extends PreTrainedTokenizer {
4224
+ /**
4225
+ * Create a new MarianTokenizer instance.
4226
+ * @param {Object} tokenizerJSON The JSON of the tokenizer.
4227
+ * @param {Object} tokenizerConfig The config of the tokenizer.
4228
+ */
4229
+ constructor(tokenizerJSON, tokenizerConfig) {
4230
+ super(tokenizerJSON, tokenizerConfig);
4231
+
4232
+ this.languageRegex = /^(>>\w+<<)\s*/g;
4233
+
4234
+ this.supported_language_codes = this.model.vocab.filter(
4235
+ x => this.languageRegex.test(x)
4236
+ );
4237
+
4238
+ console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')
4239
+ }
4240
+
4241
+ /**
4242
+ * Encodes a single text. Overriding this method is necessary since the language codes
4243
+ * must be removed before encoding with sentencepiece model.
4244
+ * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213
4245
+ *
4246
+ * @param {string|null} text The text to encode.
4247
+ * @returns {Array} The encoded tokens.
4248
+ */
4249
+ _encode_text(text) {
4250
+ if (text === null) return null;
4251
+
4252
+ // Check if text starts with language code:
4253
+ const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);
4254
+
4255
+ if (remainder.length === 0) {
4256
+ // No language code, encode normally
4257
+ return super._encode_text(matchInfo);
4258
+
4259
+ } else if (remainder.length === 2) {
4260
+ // Text starts with language code, so we do not encode it with sentencepiece.
4261
+ const [language, text] = remainder;
4262
+
4263
+ if (!this.supported_language_codes.includes(language)) {
4264
+ console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)
4265
+ }
4266
+ return mergeArrays([language], super._encode_text(text));
4267
+ }
4268
+ }
4269
+
4270
+ }
4271
+
4272
+ export class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }
4273
+
4274
+ export class BlenderbotTokenizer extends PreTrainedTokenizer { }
4275
+ export class BlenderbotSmallTokenizer extends PreTrainedTokenizer { }
4276
+
4277
+ export class SpeechT5Tokenizer extends PreTrainedTokenizer { }
4278
+
4279
+ export class NougatTokenizer extends PreTrainedTokenizer { }
4280
+
4281
+ export class VitsTokenizer extends PreTrainedTokenizer {
4282
+
4283
+ constructor(tokenizerJSON, tokenizerConfig) {
4284
+ super(tokenizerJSON, tokenizerConfig);
4285
+
4286
+ // Custom decoder function
4287
+ this.decoder = new VitsDecoder({});
4288
+ }
4289
+ }
4290
+
4291
+ export class CohereTokenizer extends PreTrainedTokenizer { }
4292
+
4293
+ /**
4294
+ * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.
4295
+ * The chosen tokenizer class is determined by the type specified in the tokenizer config.
4296
+ *
4297
+ * @example
4298
+ * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
4299
+ */
4300
+ export class AutoTokenizer {
4301
+ static TOKENIZER_CLASS_MAPPING = {
4302
+ T5Tokenizer,
4303
+ DistilBertTokenizer,
4304
+ CamembertTokenizer,
4305
+ DebertaTokenizer,
4306
+ DebertaV2Tokenizer,
4307
+ BertTokenizer,
4308
+ HerbertTokenizer,
4309
+ ConvBertTokenizer,
4310
+ RoFormerTokenizer,
4311
+ XLMTokenizer,
4312
+ ElectraTokenizer,
4313
+ MobileBertTokenizer,
4314
+ SqueezeBertTokenizer,
4315
+ AlbertTokenizer,
4316
+ GPT2Tokenizer,
4317
+ BartTokenizer,
4318
+ MBartTokenizer,
4319
+ MBart50Tokenizer,
4320
+ RobertaTokenizer,
4321
+ WhisperTokenizer,
4322
+ CodeGenTokenizer,
4323
+ CLIPTokenizer,
4324
+ SiglipTokenizer,
4325
+ MarianTokenizer,
4326
+ BloomTokenizer,
4327
+ NllbTokenizer,
4328
+ M2M100Tokenizer,
4329
+ LlamaTokenizer,
4330
+ CodeLlamaTokenizer,
4331
+ XLMRobertaTokenizer,
4332
+ MPNetTokenizer,
4333
+ FalconTokenizer,
4334
+ GPTNeoXTokenizer,
4335
+ EsmTokenizer,
4336
+ Wav2Vec2CTCTokenizer,
4337
+ BlenderbotTokenizer,
4338
+ BlenderbotSmallTokenizer,
4339
+ SpeechT5Tokenizer,
4340
+ NougatTokenizer,
4341
+ VitsTokenizer,
4342
+ Qwen2Tokenizer,
4343
+ GemmaTokenizer,
4344
+ Grok1Tokenizer,
4345
+ CohereTokenizer,
4346
+
4347
+ // Base case:
4348
+ PreTrainedTokenizer,
4349
+ }
4350
+
4351
+
4352
+ /**
4353
+ * Instantiate one of the tokenizer classes of the library from a pretrained model.
4354
+ *
4355
+ * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object
4356
+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
4357
+ *
4358
+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
4359
+ * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.
4360
+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
4361
+ * user or organization name, like `dbmdz/bert-base-german-cased`.
4362
+ * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.
4363
+ * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
4364
+ *
4365
+ * @returns {Promise<PreTrainedTokenizer>} A new instance of the PreTrainedTokenizer class.
4366
+ */
4367
+ static async from_pretrained(pretrained_model_name_or_path, {
4368
+ progress_callback = null,
4369
+ config = null,
4370
+ cache_dir = null,
4371
+ local_files_only = false,
4372
+ revision = 'main',
4373
+ legacy = null,
4374
+ } = {}) {
4375
+
4376
+ const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {
4377
+ progress_callback,
4378
+ config,
4379
+ cache_dir,
4380
+ local_files_only,
4381
+ revision,
4382
+ legacy,
4383
+ })
4384
+
4385
+ // Some tokenizers are saved with the "Fast" suffix, so we remove that if present.
4386
+ const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';
4387
+
4388
+ let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];
4389
+ if (!cls) {
4390
+ console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`);
4391
+ cls = PreTrainedTokenizer;
4392
+ }
4393
+ return new cls(tokenizerJSON, tokenizerConfig);
4394
+ }
4395
+ }