spec-cat 0.1.0 → 0.1.2

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