@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,671 @@
1
+
2
+ /**
3
+ * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)
4
+ *
5
+ * @module utils/hub
6
+ */
7
+
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+
11
+ import { env } from '../env.js';
12
+ import { dispatchCallback } from './core.js';
13
+
14
+ /**
15
+ * @typedef {Object} PretrainedOptions Options for loading a pretrained model.
16
+ * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.
17
+ * @property {Object} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:
18
+ * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).
19
+ * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.
20
+ * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
21
+ * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model).
22
+ * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id,
23
+ * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
24
+ * NOTE: This setting is ignored for local requests.
25
+ */
26
+
27
+ /**
28
+ * @typedef {Object} ModelSpecificPretrainedOptions Options for loading a pretrained model.
29
+ * @property {string} [subfolder='onnx'] In case the relevant files are located inside a subfolder of the model repo on huggingface.co,
30
+ * you can specify the folder name here.
31
+ * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
32
+ * @property {import("./devices.js").DeviceType|Record<string, import("./devices.js").DeviceType>} [device=null] The device to run the model on. If not specified, the device will be chosen from the environment settings.
33
+ * @property {import("./dtypes.js").DataType|Record<string, import("./dtypes.js").DataType>} [dtype=null] The data type to use for the model. If not specified, the data type will be chosen from the environment settings.
34
+ * @property {boolean|Record<string, boolean>} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).
35
+ * @property {Object} [session_options] (Optional) User-specified session options passed to the runtime. If not provided, suitable defaults will be chosen.
36
+ */
37
+
38
+ /**
39
+ * @typedef {PretrainedOptions & ModelSpecificPretrainedOptions} PretrainedModelOptions Options for loading a pretrained model.
40
+ */
41
+
42
+ class FileResponse {
43
+ /**
44
+ * Mapping from file extensions to MIME types.
45
+ */
46
+ _CONTENT_TYPE_MAP = {
47
+ 'txt': 'text/plain',
48
+ 'html': 'text/html',
49
+ 'css': 'text/css',
50
+ 'js': 'text/javascript',
51
+ 'json': 'application/json',
52
+ 'png': 'image/png',
53
+ 'jpg': 'image/jpeg',
54
+ 'jpeg': 'image/jpeg',
55
+ 'gif': 'image/gif',
56
+ }
57
+ /**
58
+ * Creates a new `FileResponse` object.
59
+ * @param {string|URL} filePath
60
+ */
61
+ constructor(filePath) {
62
+ this.filePath = filePath;
63
+ this.headers = new Headers();
64
+
65
+ this.exists = fs.existsSync(filePath);
66
+ if (this.exists) {
67
+ this.status = 200;
68
+ this.statusText = 'OK';
69
+
70
+ let stats = fs.statSync(filePath);
71
+ this.headers.set('content-length', stats.size.toString());
72
+
73
+ this.updateContentType();
74
+
75
+ let self = this;
76
+ this.body = new ReadableStream({
77
+ start(controller) {
78
+ self.arrayBuffer().then(buffer => {
79
+ controller.enqueue(new Uint8Array(buffer));
80
+ controller.close();
81
+ })
82
+ }
83
+ });
84
+ } else {
85
+ this.status = 404;
86
+ this.statusText = 'Not Found';
87
+ this.body = null;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Updates the 'content-type' header property of the response based on the extension of
93
+ * the file specified by the filePath property of the current object.
94
+ * @returns {void}
95
+ */
96
+ updateContentType() {
97
+ // Set content-type header based on file extension
98
+ const extension = this.filePath.toString().split('.').pop().toLowerCase();
99
+ this.headers.set('content-type', this._CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');
100
+ }
101
+
102
+ /**
103
+ * Clone the current FileResponse object.
104
+ * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
105
+ */
106
+ clone() {
107
+ let response = new FileResponse(this.filePath);
108
+ response.exists = this.exists;
109
+ response.status = this.status;
110
+ response.statusText = this.statusText;
111
+ response.headers = new Headers(this.headers);
112
+ return response;
113
+ }
114
+
115
+ /**
116
+ * Reads the contents of the file specified by the filePath property and returns a Promise that
117
+ * resolves with an ArrayBuffer containing the file's contents.
118
+ * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
119
+ * @throws {Error} If the file cannot be read.
120
+ */
121
+ async arrayBuffer() {
122
+ const data = await fs.promises.readFile(this.filePath);
123
+ return data.buffer;
124
+ }
125
+
126
+ /**
127
+ * Reads the contents of the file specified by the filePath property and returns a Promise that
128
+ * resolves with a Blob containing the file's contents.
129
+ * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
130
+ * @throws {Error} If the file cannot be read.
131
+ */
132
+ async blob() {
133
+ const data = await fs.promises.readFile(this.filePath);
134
+ return new Blob([data], { type: this.headers.get('content-type') });
135
+ }
136
+
137
+ /**
138
+ * Reads the contents of the file specified by the filePath property and returns a Promise that
139
+ * resolves with a string containing the file's contents.
140
+ * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
141
+ * @throws {Error} If the file cannot be read.
142
+ */
143
+ async text() {
144
+ const data = await fs.promises.readFile(this.filePath, 'utf8');
145
+ return data;
146
+ }
147
+
148
+ /**
149
+ * Reads the contents of the file specified by the filePath property and returns a Promise that
150
+ * resolves with a parsed JavaScript object containing the file's contents.
151
+ *
152
+ * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
153
+ * @throws {Error} If the file cannot be read.
154
+ */
155
+ async json() {
156
+ return JSON.parse(await this.text());
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Determines whether the given string is a valid URL.
162
+ * @param {string|URL} string The string to test for validity as an URL.
163
+ * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list.
164
+ * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list.
165
+ * @returns {boolean} True if the string is a valid URL, false otherwise.
166
+ */
167
+ function isValidUrl(string, protocols = null, validHosts = null) {
168
+ let url;
169
+ try {
170
+ url = new URL(string);
171
+ } catch (_) {
172
+ return false;
173
+ }
174
+ if (protocols && !protocols.includes(url.protocol)) {
175
+ return false;
176
+ }
177
+ if (validHosts && !validHosts.includes(url.hostname)) {
178
+ return false;
179
+ }
180
+ return true;
181
+ }
182
+
183
+ /**
184
+ * Helper function to get a file, using either the Fetch API or FileSystem API.
185
+ *
186
+ * @param {URL|string} urlOrPath The URL/path of the file to get.
187
+ * @returns {Promise<FileResponse|Response>} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).
188
+ */
189
+ export async function getFile(urlOrPath) {
190
+
191
+ if (env.useFS && !isValidUrl(urlOrPath, ['http:', 'https:', 'blob:'])) {
192
+ return new FileResponse(urlOrPath);
193
+
194
+ } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {
195
+ const IS_CI = !!process.env?.TESTING_REMOTELY;
196
+ const version = env.version;
197
+
198
+ const headers = new Headers();
199
+ headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);
200
+
201
+ // Check whether we are making a request to the Hugging Face Hub.
202
+ const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']);
203
+ if (isHFURL) {
204
+ // If an access token is present in the environment variables,
205
+ // we add it to the request headers.
206
+ // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).
207
+ const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;
208
+ if (token) {
209
+ headers.set('Authorization', `Bearer ${token}`);
210
+ }
211
+ }
212
+ return fetch(urlOrPath, { headers });
213
+ } else {
214
+ // Running in a browser-environment, so we use default headers
215
+ // NOTE: We do not allow passing authorization headers in the browser,
216
+ // since this would require exposing the token to the client.
217
+ return fetch(urlOrPath);
218
+ }
219
+ }
220
+
221
+ const ERROR_MAPPING = {
222
+ // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)
223
+ 400: 'Bad request error occurred while trying to load file',
224
+ 401: 'Unauthorized access to file',
225
+ 403: 'Forbidden access to file',
226
+ 404: 'Could not locate file',
227
+ 408: 'Request timeout error occurred while trying to load file',
228
+
229
+ // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)
230
+ 500: 'Internal server error error occurred while trying to load file',
231
+ 502: 'Bad gateway error occurred while trying to load file',
232
+ 503: 'Service unavailable error occurred while trying to load file',
233
+ 504: 'Gateway timeout error occurred while trying to load file',
234
+ }
235
+ /**
236
+ * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.
237
+ * @param {number} status The HTTP status code of the error.
238
+ * @param {string} remoteURL The URL of the file that could not be loaded.
239
+ * @param {boolean} fatal Whether to raise an error if the file could not be loaded.
240
+ * @returns {null} Returns `null` if `fatal = true`.
241
+ * @throws {Error} If `fatal = false`.
242
+ */
243
+ function handleError(status, remoteURL, fatal) {
244
+ if (!fatal) {
245
+ // File was not loaded correctly, but it is optional.
246
+ // TODO in future, cache the response?
247
+ return null;
248
+ }
249
+
250
+ const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;
251
+ throw Error(`${message}: "${remoteURL}".`);
252
+ }
253
+
254
+ class FileCache {
255
+ /**
256
+ * Instantiate a `FileCache` object.
257
+ * @param {string} path
258
+ */
259
+ constructor(path) {
260
+ this.path = path;
261
+ }
262
+
263
+ /**
264
+ * Checks whether the given request is in the cache.
265
+ * @param {string} request
266
+ * @returns {Promise<FileResponse | undefined>}
267
+ */
268
+ async match(request) {
269
+
270
+ let filePath = path.join(this.path, request);
271
+ let file = new FileResponse(filePath);
272
+
273
+ if (file.exists) {
274
+ return file;
275
+ } else {
276
+ return undefined;
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Adds the given response to the cache.
282
+ * @param {string} request
283
+ * @param {Response|FileResponse} response
284
+ * @returns {Promise<void>}
285
+ */
286
+ async put(request, response) {
287
+ const buffer = Buffer.from(await response.arrayBuffer());
288
+
289
+ let outputPath = path.join(this.path, request);
290
+
291
+ try {
292
+ await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });
293
+ await fs.promises.writeFile(outputPath, buffer);
294
+
295
+ } catch (err) {
296
+ console.warn('An error occurred while writing the file to cache:', err)
297
+ }
298
+ }
299
+
300
+ // TODO add the rest?
301
+ // addAll(requests: RequestInfo[]): Promise<void>;
302
+ // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
303
+ // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Request>>;
304
+ // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
305
+ // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Response>>;
306
+ }
307
+
308
+ /**
309
+ *
310
+ * @param {FileCache|Cache} cache The cache to search
311
+ * @param {string[]} names The names of the item to search for
312
+ * @returns {Promise<FileResponse|Response|undefined>} The item from the cache, or undefined if not found.
313
+ */
314
+ async function tryCache(cache, ...names) {
315
+ for (let name of names) {
316
+ try {
317
+ let result = await cache.match(name);
318
+ if (result) return result;
319
+ } catch (e) {
320
+ continue;
321
+ }
322
+ }
323
+ return undefined;
324
+ }
325
+
326
+ /**
327
+ *
328
+ * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.
329
+ * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.
330
+ *
331
+ * @param {string} path_or_repo_id This can be either:
332
+ * - a string, the *model id* of a model repo on huggingface.co.
333
+ * - a path to a *directory* potentially containing the file.
334
+ * @param {string} filename The name of the file to locate in `path_or_repo`.
335
+ * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.
336
+ * @param {PretrainedOptions} [options] An object containing optional parameters.
337
+ *
338
+ * @throws Will throw an error if the file is not found and `fatal` is true.
339
+ * @returns {Promise<Uint8Array>} A Promise that resolves with the file content as a buffer.
340
+ */
341
+ export async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {
342
+
343
+ if (!env.allowLocalModels) {
344
+ // User has disabled local models, so we just make sure other settings are correct.
345
+
346
+ if (options.local_files_only) {
347
+ throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).")
348
+ } else if (!env.allowRemoteModels) {
349
+ throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")
350
+ }
351
+ }
352
+
353
+ // Initiate file retrieval
354
+ dispatchCallback(options.progress_callback, {
355
+ status: 'initiate',
356
+ name: path_or_repo_id,
357
+ file: filename
358
+ })
359
+
360
+ // First, check if the a caching backend is available
361
+ // If no caching mechanism available, will download the file every time
362
+ let cache;
363
+ if (!cache && env.useBrowserCache) {
364
+ if (typeof caches === 'undefined') {
365
+ throw Error('Browser cache is not available in this environment.')
366
+ }
367
+ try {
368
+ // In some cases, the browser cache may be visible, but not accessible due to security restrictions.
369
+ // For example, when running an application in an iframe, if a user attempts to load the page in
370
+ // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':
371
+ // An attempt was made to break through the security policy of the user agent.`
372
+ // So, instead of crashing, we just ignore the error and continue without using the cache.
373
+ cache = await caches.open('transformers-cache');
374
+ } catch (e) {
375
+ console.warn('An error occurred while opening the browser cache:', e);
376
+ }
377
+ }
378
+
379
+ if (!cache && env.useFSCache) {
380
+ // TODO throw error if not available
381
+
382
+ // If `cache_dir` is not specified, use the default cache directory
383
+ cache = new FileCache(options.cache_dir ?? env.cacheDir);
384
+ }
385
+
386
+ if (!cache && env.useCustomCache) {
387
+ // Allow the user to specify a custom cache system.
388
+ if (!env.customCache) {
389
+ throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')
390
+ }
391
+
392
+ // Check that the required methods are defined:
393
+ if (!env.customCache.match || !env.customCache.put) {
394
+ throw new Error(
395
+ "`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. " +
396
+ "For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache"
397
+ )
398
+ }
399
+ cache = env.customCache;
400
+ }
401
+
402
+ const revision = options.revision ?? 'main';
403
+
404
+ let requestURL = pathJoin(path_or_repo_id, filename);
405
+ let localPath = pathJoin(env.localModelPath, requestURL);
406
+
407
+ let remoteURL = pathJoin(
408
+ env.remoteHost,
409
+ env.remotePathTemplate
410
+ .replaceAll('{model}', path_or_repo_id)
411
+ .replaceAll('{revision}', encodeURIComponent(revision)),
412
+ filename
413
+ );
414
+
415
+ // Choose cache key for filesystem cache
416
+ // When using the main revision (default), we use the request URL as the cache key.
417
+ // If a specific revision is requested, we account for this in the cache key.
418
+ let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename);
419
+
420
+ /** @type {string} */
421
+ let cacheKey;
422
+ let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;
423
+
424
+ // Whether to cache the final response in the end.
425
+ let toCacheResponse = false;
426
+
427
+ /** @type {Response|FileResponse|undefined} */
428
+ let response;
429
+
430
+ if (cache) {
431
+ // A caching system is available, so we try to get the file from it.
432
+ // 1. We first try to get from cache using the local path. In some environments (like deno),
433
+ // non-URL cache keys are not allowed. In these cases, `response` will be undefined.
434
+ // 2. If no response is found, we try to get from cache using the remote URL or file system cache.
435
+ response = await tryCache(cache, localPath, proposedCacheKey);
436
+ }
437
+
438
+ const cacheHit = response !== undefined;
439
+
440
+ if (response === undefined) {
441
+ // Caching not available, or file is not cached, so we perform the request
442
+
443
+ if (env.allowLocalModels) {
444
+ // Accessing local models is enabled, so we try to get the file locally.
445
+ // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.
446
+ const isURL = isValidUrl(requestURL, ['http:', 'https:']);
447
+ if (!isURL) {
448
+ try {
449
+ response = await getFile(localPath);
450
+ cacheKey = localPath; // Update the cache key to be the local path
451
+ } catch (e) {
452
+ // Something went wrong while trying to get the file locally.
453
+ // NOTE: error handling is done in the next step (since `response` will be undefined)
454
+ console.warn(`Unable to load from local path "${localPath}": "${e}"`);
455
+ }
456
+ } else if (options.local_files_only) {
457
+ throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`);
458
+ } else if (!env.allowRemoteModels) {
459
+ throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`);
460
+ }
461
+ }
462
+
463
+ if (response === undefined || response.status === 404) {
464
+ // File not found locally. This means either:
465
+ // - The user has disabled local file access (`env.allowLocalModels=false`)
466
+ // - the path is a valid HTTP url (`response === undefined`)
467
+ // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)
468
+
469
+ if (options.local_files_only || !env.allowRemoteModels) {
470
+ // User requested local files only, but the file is not found locally.
471
+ if (fatal) {
472
+ throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`);
473
+ } else {
474
+ // File not found, but this file is optional.
475
+ // TODO in future, cache the response?
476
+ return null;
477
+ }
478
+ }
479
+
480
+ // File not found locally, so we try to download it from the remote server
481
+ response = await getFile(remoteURL);
482
+
483
+ if (response.status !== 200) {
484
+ return handleError(response.status, remoteURL, fatal);
485
+ }
486
+
487
+ // Success! We use the proposed cache key from earlier
488
+ cacheKey = proposedCacheKey;
489
+ }
490
+
491
+ // Only cache the response if:
492
+ toCacheResponse =
493
+ cache // 1. A caching system is available
494
+ && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)
495
+ && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`)
496
+ && response.status === 200 // 4. request was successful (status code 200)
497
+ }
498
+
499
+ // Start downloading
500
+ dispatchCallback(options.progress_callback, {
501
+ status: 'download',
502
+ name: path_or_repo_id,
503
+ file: filename
504
+ })
505
+
506
+ const progressInfo = {
507
+ status: 'progress',
508
+ name: path_or_repo_id,
509
+ file: filename
510
+ }
511
+
512
+ /** @type {Uint8Array} */
513
+ let buffer;
514
+
515
+ if (!options.progress_callback) {
516
+ // If no progress callback is specified, we can use the `.arrayBuffer()`
517
+ // method to read the response.
518
+ buffer = new Uint8Array(await response.arrayBuffer());
519
+
520
+ } else if (
521
+ cacheHit // The item is being read from the cache
522
+ &&
523
+ typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox
524
+ ) {
525
+ // Due to bug in Firefox, we cannot display progress when loading from cache.
526
+ // Fortunately, since this should be instantaneous, this should not impact users too much.
527
+ buffer = new Uint8Array(await response.arrayBuffer());
528
+
529
+ // For completeness, we still fire the final progress callback
530
+ dispatchCallback(options.progress_callback, {
531
+ ...progressInfo,
532
+ progress: 100,
533
+ loaded: buffer.length,
534
+ total: buffer.length,
535
+ })
536
+ } else {
537
+ buffer = await readResponse(response, data => {
538
+ dispatchCallback(options.progress_callback, {
539
+ ...progressInfo,
540
+ ...data,
541
+ })
542
+ })
543
+ }
544
+
545
+ if (
546
+ // Only cache web responses
547
+ // i.e., do not cache FileResponses (prevents duplication)
548
+ toCacheResponse && cacheKey
549
+ &&
550
+ // Check again whether request is in cache. If not, we add the response to the cache
551
+ (await cache.match(cacheKey) === undefined)
552
+ ) {
553
+ // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files
554
+ await cache.put(cacheKey, new Response(buffer, {
555
+ headers: response.headers
556
+ }))
557
+ .catch(err => {
558
+ // Do not crash if unable to add to cache (e.g., QuotaExceededError).
559
+ // Rather, log a warning and proceed with execution.
560
+ console.warn(`Unable to add response to browser cache: ${err}.`);
561
+ });
562
+
563
+ }
564
+
565
+ dispatchCallback(options.progress_callback, {
566
+ status: 'done',
567
+ name: path_or_repo_id,
568
+ file: filename
569
+ });
570
+
571
+ return buffer;
572
+ }
573
+
574
+ /**
575
+ * Fetches a JSON file from a given path and file name.
576
+ *
577
+ * @param {string} modelPath The path to the directory containing the file.
578
+ * @param {string} fileName The name of the file to fetch.
579
+ * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.
580
+ * @param {PretrainedOptions} [options] An object containing optional parameters.
581
+ * @returns {Promise<Object>} The JSON data parsed into a JavaScript object.
582
+ * @throws Will throw an error if the file is not found and `fatal` is true.
583
+ */
584
+ export async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {
585
+ let buffer = await getModelFile(modelPath, fileName, fatal, options);
586
+ if (buffer === null) {
587
+ // Return empty object
588
+ return {}
589
+ }
590
+
591
+ let decoder = new TextDecoder('utf-8');
592
+ let jsonData = decoder.decode(buffer);
593
+
594
+ return JSON.parse(jsonData);
595
+ }
596
+
597
+ /**
598
+ * Read and track progress when reading a Response object
599
+ *
600
+ * @param {any} response The Response object to read
601
+ * @param {function} progress_callback The function to call with progress updates
602
+ * @returns {Promise<Uint8Array>} A Promise that resolves with the Uint8Array buffer
603
+ */
604
+ async function readResponse(response, progress_callback) {
605
+
606
+ const contentLength = response.headers.get('Content-Length');
607
+ if (contentLength === null) {
608
+ console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')
609
+ }
610
+ let total = parseInt(contentLength ?? '0');
611
+ let buffer = new Uint8Array(total);
612
+ let loaded = 0;
613
+
614
+ const reader = response.body.getReader();
615
+ async function read() {
616
+ const { done, value } = await reader.read();
617
+ if (done) return;
618
+
619
+ let newLoaded = loaded + value.length;
620
+ if (newLoaded > total) {
621
+ total = newLoaded;
622
+
623
+ // Adding the new data will overflow buffer.
624
+ // In this case, we extend the buffer
625
+ let newBuffer = new Uint8Array(total);
626
+
627
+ // copy contents
628
+ newBuffer.set(buffer);
629
+
630
+ buffer = newBuffer;
631
+ }
632
+ buffer.set(value, loaded)
633
+ loaded = newLoaded;
634
+
635
+ const progress = (loaded / total) * 100;
636
+
637
+ // Call your function here
638
+ progress_callback({
639
+ progress: progress,
640
+ loaded: loaded,
641
+ total: total,
642
+ })
643
+
644
+ return read();
645
+ }
646
+
647
+ // Actually read
648
+ await read();
649
+
650
+ return buffer;
651
+ }
652
+
653
+ /**
654
+ * Joins multiple parts of a path into a single path, while handling leading and trailing slashes.
655
+ *
656
+ * @param {...string} parts Multiple parts of a path.
657
+ * @returns {string} A string representing the joined path.
658
+ */
659
+ function pathJoin(...parts) {
660
+ // https://stackoverflow.com/a/55142565
661
+ parts = parts.map((part, index) => {
662
+ if (index) {
663
+ part = part.replace(new RegExp('^/'), '');
664
+ }
665
+ if (index !== parts.length - 1) {
666
+ part = part.replace(new RegExp('/$'), '');
667
+ }
668
+ return part;
669
+ })
670
+ return parts.join('/');
671
+ }