@p2arthur/webinference-sdk 0.0.0-stage → 0.1.1
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.
- package/CHANGELOG.md +18 -0
- package/README.md +215 -2
- package/dist/image.worker-Bw4MnkKd.js +15 -0
- package/dist/index.js +938 -0
- package/dist/inference.worker-ObNSBgG3.js +15 -0
- package/dist/laya.worker-DgRSLTIF.js +15 -0
- package/dist/model-catalog-D6UCYXpI.js +3 -0
- package/dist/onnx-chat.worker-BbP3C_6v.js +15 -0
- package/index.d.ts +248 -0
- package/package.json +58 -4
- package/third-party-licenses/google-litert.txt +201 -0
- package/third-party-licenses/huggingface-jinja.txt +21 -0
- package/third-party-licenses/huggingface-tokenizers.txt +201 -0
- package/third-party-licenses/noble-hashes.txt +21 -0
- package/third-party-licenses/onnx-runtime-notices.txt +6369 -0
- package/third-party-licenses/onnx-runtime.txt +21 -0
- package/third-party-licenses/transformers.js.txt +202 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,938 @@
|
|
|
1
|
+
// src/device.js
|
|
2
|
+
async function e() {
|
|
3
|
+
let e = globalThis.navigator, [t, n] = await Promise.allSettled([e?.gpu?.requestAdapter({ powerPreference: "high-performance" }), e?.storage?.estimate?.()]), r = t.status === "fulfilled" ? t.value : null, i = n.status === "fulfilled" ? n.value : null;
|
|
4
|
+
return {
|
|
5
|
+
webgpu: !!r,
|
|
6
|
+
shaderFp16: r?.features.has("shader-f16") ?? !1,
|
|
7
|
+
subgroups: r?.features.has("subgroups") ?? !1,
|
|
8
|
+
maxBufferBytes: r?.limits.maxBufferSize ?? null,
|
|
9
|
+
deviceMemoryGiB: e?.deviceMemory ?? null,
|
|
10
|
+
storageAvailableBytes: i?.quota === void 0 ? null : Math.max(0, i.quota - (i.usage ?? 0))
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
// src/errors.js
|
|
14
|
+
var t = class extends Error {
|
|
15
|
+
constructor(e, t, { operation: n, repo: r, cause: i, details: a } = {}) {
|
|
16
|
+
super(t, { cause: i }), this.name = "ModelError", this.code = e, this.operation = n, this.repo = r, a && (this.details = a);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
function n(e, n, r) {
|
|
20
|
+
return new t("ABORTED", "The model operation was canceled.", {
|
|
21
|
+
operation: n,
|
|
22
|
+
repo: r,
|
|
23
|
+
cause: e.reason
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function r(e, t, r) {
|
|
27
|
+
if (e?.aborted) throw n(e, t, r);
|
|
28
|
+
}
|
|
29
|
+
// src/model-registry.js
|
|
30
|
+
var i = "https://huggingface.co", a = /^[\w.-]+\/[\w.-]+$/, o = /^[a-f0-9]{40}$/, s = /^[a-f0-9]{64}$/, c = /^(?!.*(?:^|\/)\.{1,2}(?:\/|$))[\w.@-]+(?:\/[\w.@-]+)*$/, l = {
|
|
31
|
+
"litert-chat": { task: "chat" },
|
|
32
|
+
"onnx-chat": { task: "chat" },
|
|
33
|
+
"laya-choice": { task: "classification" },
|
|
34
|
+
"janus-image": { task: "image" },
|
|
35
|
+
"sd-turbo": { task: "image" }
|
|
36
|
+
}, u = [
|
|
37
|
+
"config.json",
|
|
38
|
+
"tokenizer.json",
|
|
39
|
+
"tokenizer_config.json",
|
|
40
|
+
"onnx/model_fp16.onnx",
|
|
41
|
+
"onnx/model_fp16.onnx_data"
|
|
42
|
+
], d = [
|
|
43
|
+
"config.json",
|
|
44
|
+
"tokenizer.json",
|
|
45
|
+
"tokenizer_config.json",
|
|
46
|
+
"processor_config.json",
|
|
47
|
+
"preprocessor_config.json",
|
|
48
|
+
"onnx/prepare_inputs_embeds_q4.onnx",
|
|
49
|
+
"onnx/language_model_q4f16.onnx",
|
|
50
|
+
"onnx/lm_head_fp16.onnx",
|
|
51
|
+
"onnx/gen_head_fp16.onnx",
|
|
52
|
+
"onnx/gen_img_embeds_fp16.onnx",
|
|
53
|
+
"onnx/image_decode.onnx"
|
|
54
|
+
], f = [
|
|
55
|
+
"text_encoder/model.onnx",
|
|
56
|
+
"unet/model.onnx",
|
|
57
|
+
"vae_decoder/model.onnx"
|
|
58
|
+
], p = ["tokenizer/tokenizer.json", "tokenizer/tokenizer_config.json"], m = "local/model", h = [
|
|
59
|
+
"config.json",
|
|
60
|
+
"tokenizer.json",
|
|
61
|
+
"tokenizer_config.json"
|
|
62
|
+
], g = /* @__PURE__ */ new Set([
|
|
63
|
+
"bloom",
|
|
64
|
+
"falcon",
|
|
65
|
+
"gemma",
|
|
66
|
+
"gemma2",
|
|
67
|
+
"gemma3_text",
|
|
68
|
+
"gpt2",
|
|
69
|
+
"gpt_bigcode",
|
|
70
|
+
"gpt_neox",
|
|
71
|
+
"gptj",
|
|
72
|
+
"granite",
|
|
73
|
+
"llama",
|
|
74
|
+
"mistral",
|
|
75
|
+
"olmo",
|
|
76
|
+
"olmo2",
|
|
77
|
+
"opt",
|
|
78
|
+
"phi",
|
|
79
|
+
"phi3",
|
|
80
|
+
"qwen2",
|
|
81
|
+
"qwen3",
|
|
82
|
+
"smollm3",
|
|
83
|
+
"stablelm",
|
|
84
|
+
"starcoder2"
|
|
85
|
+
]);
|
|
86
|
+
function _(e) {
|
|
87
|
+
return g.has(e?.model_type) && !e.is_encoder_decoder && (!Array.isArray(e.architectures) || e.architectures.some((e) => /(?:CausalLM|LMHeadModel)$/.test(e)));
|
|
88
|
+
}
|
|
89
|
+
function v(e) {
|
|
90
|
+
let t = /^onnx\/(model|decoder_model_merged)(?:_(q4f16|q4|quantized|fp16))?\.onnx$/.exec(e);
|
|
91
|
+
if (t) return {
|
|
92
|
+
modelFile: t[1],
|
|
93
|
+
dtype: t[2] === "quantized" ? "q8" : t[2] ?? "fp32"
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function y(e, t) {
|
|
97
|
+
let n = `${e}_data`, r = t.filter((e) => e === n || e.startsWith(`${n}_`) && /^[1-9]\d*$/.test(e.slice(n.length + 1)));
|
|
98
|
+
if (!r.length) return [];
|
|
99
|
+
let i = r.map((e, t) => t === 0 ? n : `${n}_${t}`);
|
|
100
|
+
return i.every((e) => r.includes(e)) ? i : void 0;
|
|
101
|
+
}
|
|
102
|
+
function b(e, t) {
|
|
103
|
+
let n = e["transformers.js_config"]?.use_external_data_format, r = typeof n == "object" && n ? n[t.split("/").at(-1)] ?? n[v(t).modelFile] : n;
|
|
104
|
+
return r === !0 ? 1 : Number(r) || 0;
|
|
105
|
+
}
|
|
106
|
+
function x(e) {
|
|
107
|
+
return typeof e == "string" && a.test(e) && e.split("/").every((e) => c.test(e));
|
|
108
|
+
}
|
|
109
|
+
function S(e) {
|
|
110
|
+
return typeof e == "string" && c.test(e);
|
|
111
|
+
}
|
|
112
|
+
function C(e, t, n) {
|
|
113
|
+
return `${i}/${e}/resolve/${t}/${n.split("/").map(encodeURIComponent).join("/")}`;
|
|
114
|
+
}
|
|
115
|
+
function w(e) {
|
|
116
|
+
let t = e?.source === "local";
|
|
117
|
+
if (!e || e.version !== 1 || !Object.hasOwn(l, e.adapter) || (t ? e.repo !== "local/model" || e.revision !== void 0 : !x(e.repo) || typeof e.revision != "string" || !o.test(e.revision)) || !Array.isArray(e.files) || e.files.length === 0 || e.files.length > 24 || !e.files.every((e) => e && S(e.path) && Number.isSafeInteger(e.size) && e.size > 0 && (e.sha256 === void 0 || typeof e.sha256 == "string" && s.test(e.sha256)))) return !1;
|
|
118
|
+
let n = new Set(e.files.map(({ path: e }) => e));
|
|
119
|
+
if (n.size !== e.files.length) return !1;
|
|
120
|
+
switch (e.adapter) {
|
|
121
|
+
case "litert-chat": return e.files.length === 1 && /\.litertlm$/i.test(e.files[0].path) && (t || s.test(e.files[0].sha256));
|
|
122
|
+
case "onnx-chat": {
|
|
123
|
+
let t = e.files[0].path;
|
|
124
|
+
return !!(v(t) && h.every((e) => n.has(e)) && y(t, [...n]));
|
|
125
|
+
}
|
|
126
|
+
case "laya-choice": return u.every((e) => n.has(e));
|
|
127
|
+
case "janus-image": return d.every((e) => n.has(e));
|
|
128
|
+
case "sd-turbo": return f.every((e) => n.has(e)) && (t ? p.every((e) => n.has(e)) : e.repo.toLowerCase() === "schmuell/sd-turbo-ort-web");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function T(e) {
|
|
132
|
+
let t = ["litert-chat", "onnx-chat"].includes(e.adapter) ? `/${e.files[0].path}` : "";
|
|
133
|
+
return `hub:${e.adapter}:${e.repo}@${e.revision}${t}`;
|
|
134
|
+
}
|
|
135
|
+
function E(e) {
|
|
136
|
+
return e.adapter === "onnx-chat" ? `${e.repo.split("/").at(-1)} · ${v(e.files[0].path)?.dtype.toUpperCase()}` : e.adapter === "litert-chat" ? e.files[0].path.split("/").at(-1).replace(/\.litertlm$/i, "") : e.repo;
|
|
137
|
+
}
|
|
138
|
+
function D(e) {
|
|
139
|
+
return e.files.reduce((e, t) => e + t.size, 0);
|
|
140
|
+
}
|
|
141
|
+
function O(e) {
|
|
142
|
+
let t = e?.laya;
|
|
143
|
+
return !!(t && e.model_type === "modernbert" && t.split_words === !1 && t.qtypes?.choice === 0 && Number.isInteger(t.max_len) && t.max_len >= 128 && Number.isInteger(t.max_option_tokens) && t.max_option_tokens > 0 && Number.isFinite(t.temperature_by_options?.["choice:3-5"]) && t.temperature_by_options["choice:3-5"] > 0);
|
|
144
|
+
}
|
|
145
|
+
function k(e) {
|
|
146
|
+
return e?.model_type === "multi_modality" && Array.isArray(e.architectures) && e.architectures.includes("MultiModalityCausalLM");
|
|
147
|
+
}
|
|
148
|
+
// src/hub-inspector.js
|
|
149
|
+
function A(e) {
|
|
150
|
+
let t;
|
|
151
|
+
try {
|
|
152
|
+
t = new URL(e.trim());
|
|
153
|
+
} catch {
|
|
154
|
+
throw Error("Paste a Hugging Face model URL, such as https://huggingface.co/owner/model.");
|
|
155
|
+
}
|
|
156
|
+
if (t.origin !== "https://huggingface.co" || t.username || t.password) throw Error("Use a public model URL on huggingface.co.");
|
|
157
|
+
let n = t.pathname.replace(/^\/|\/$/g, "").split("/").map(decodeURIComponent), r = n.slice(0, 2).join("/");
|
|
158
|
+
if (!x(r) || [
|
|
159
|
+
"datasets",
|
|
160
|
+
"spaces",
|
|
161
|
+
"collections",
|
|
162
|
+
"api"
|
|
163
|
+
].includes(n[0])) throw Error("This link needs to point to a Hugging Face model repository or model file.");
|
|
164
|
+
if (n.length === 2) return { repo: r };
|
|
165
|
+
let [, , i, a, ...o] = n;
|
|
166
|
+
if (![
|
|
167
|
+
"tree",
|
|
168
|
+
"blob",
|
|
169
|
+
"resolve"
|
|
170
|
+
].includes(i) || !a || a.length > 200 || /[?#\\]/.test(a)) throw Error("Use a repository, revision, or model file link from Hugging Face.");
|
|
171
|
+
let s = o.join("/");
|
|
172
|
+
if (s && !S(s) || i !== "tree" && !s) throw Error("This model file link is incomplete.");
|
|
173
|
+
return i === "tree" ? {
|
|
174
|
+
repo: r,
|
|
175
|
+
revision: a,
|
|
176
|
+
folder: s
|
|
177
|
+
} : {
|
|
178
|
+
repo: r,
|
|
179
|
+
revision: a,
|
|
180
|
+
path: s
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
function j(e, t) {
|
|
184
|
+
return fetch(e, {
|
|
185
|
+
signal: t,
|
|
186
|
+
credentials: "omit",
|
|
187
|
+
headers: { Accept: "application/json" }
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
async function M(e, t) {
|
|
191
|
+
let n = `https://huggingface.co/api/models/${e.repo}`, r = await j(`${e.revision ? `${n}/revision/${encodeURIComponent(e.revision)}` : n}?blobs=true`, t);
|
|
192
|
+
if ([
|
|
193
|
+
401,
|
|
194
|
+
403,
|
|
195
|
+
404
|
|
196
|
+
].includes(r.status)) throw Error("Hugging Face could not open this public repository or revision. Check the link and its access settings.");
|
|
197
|
+
if (r.status === 429) throw Error("Hugging Face rate-limited the request. Try again in a moment.");
|
|
198
|
+
if (!r.ok) throw Error(`Hugging Face returned HTTP ${r.status}. Try again.`);
|
|
199
|
+
let i = await r.json(), a = x(i.id) ? i.id : e.repo, o = i.sha;
|
|
200
|
+
if (!/^[a-f0-9]{40}$/.test(o)) throw Error("The Hub did not return a commit for this model.");
|
|
201
|
+
let s = Array.isArray(i.tags) ? i.tags : [], c = s.find((e) => typeof e == "string" && e.startsWith("base_model:quantized:"))?.slice(21), l = {
|
|
202
|
+
repo: a,
|
|
203
|
+
revision: o,
|
|
204
|
+
task: i.pipeline_tag,
|
|
205
|
+
files: 0,
|
|
206
|
+
candidates: [],
|
|
207
|
+
issues: [],
|
|
208
|
+
upstream: c
|
|
209
|
+
};
|
|
210
|
+
if (i.gated || i.private) return l.verdict = "Access required", l.canFindRelated = !0, l.issues.push("This repository requires Hugging Face access. Use a public browser export. This demo imports without account credentials."), l;
|
|
211
|
+
let p = new Map((i.siblings ?? []).map((e) => [e.rfilename, e]));
|
|
212
|
+
if (l.files = p.size, e.path && !p.has(e.path)) return l.verdict = "File missing", l.issues.push(`This revision does not contain ${e.path}. Check the file path or use the repository URL.`), l;
|
|
213
|
+
function m(e, t) {
|
|
214
|
+
let n = {
|
|
215
|
+
version: 1,
|
|
216
|
+
adapter: e,
|
|
217
|
+
repo: a,
|
|
218
|
+
revision: o,
|
|
219
|
+
files: t.map((e) => {
|
|
220
|
+
let t = p.get(e);
|
|
221
|
+
return {
|
|
222
|
+
path: e,
|
|
223
|
+
size: t?.size,
|
|
224
|
+
...t?.lfs?.sha256 ? { sha256: t.lfs.sha256 } : {}
|
|
225
|
+
};
|
|
226
|
+
})
|
|
227
|
+
};
|
|
228
|
+
w(n) ? l.candidates.push(n) : l.issues.push(`Hugging Face did not provide the required size or checksum metadata for ${t[0]}.`);
|
|
229
|
+
}
|
|
230
|
+
function g(e) {
|
|
231
|
+
let t = e.filter((e) => !p.has(e));
|
|
232
|
+
return t.length && (l.verdict = "Files missing"), t;
|
|
233
|
+
}
|
|
234
|
+
let S = [...p.keys()], T = (t) => (!e.path || t === e.path) && (!e.folder || t.startsWith(`${e.folder}/`)), E = S.filter(T);
|
|
235
|
+
if (e.folder && !E.length) return l.issues.push("This folder has no files at the selected revision. Try the repository URL."), l;
|
|
236
|
+
let D = S.filter((e) => /-(web|gpu)\.litertlm$/i.test(e));
|
|
237
|
+
if (D.length === 0 && E.some((e) => /\.litertlm$/i.test(e))) {
|
|
238
|
+
let e = s.includes("webgpu") || s.includes("browser");
|
|
239
|
+
if (!e && a.startsWith("litert-community/")) {
|
|
240
|
+
let n = await j("https://huggingface.co/api/collections/litert-community/web-llm-models", t);
|
|
241
|
+
n.ok && (e = (await n.json()).items?.some((e) => e.repoType === "model" && e.id === a));
|
|
242
|
+
}
|
|
243
|
+
e && D.push(...E.filter((e) => /\.litertlm$/i.test(e) && !/(?:^|[-_])npu(?:[-_.]|$)/i.test(e)).sort((e, t) => p.get(e).size - p.get(t).size));
|
|
244
|
+
}
|
|
245
|
+
for (let e of D.filter(T).sort((e, t) => Number(!/-web\.litertlm$/i.test(e)) - Number(!/-web\.litertlm$/i.test(t)))) m("litert-chat", [e]);
|
|
246
|
+
let A = [
|
|
247
|
+
"q4",
|
|
248
|
+
"q4f16",
|
|
249
|
+
"q8",
|
|
250
|
+
"fp16",
|
|
251
|
+
"fp32"
|
|
252
|
+
], M = S.filter((t) => v(t) && (T(t) || e.path?.startsWith(`${t}_data`))).sort((e, t) => A.indexOf(v(e).dtype) - A.indexOf(v(t).dtype)), N = /laya/i.test(a) || s.includes("laya") || p.has("onnx/model_fp16.onnx_data"), P = /janus/i.test(a) || s.includes("multi_modality") || p.has("onnx/prepare_inputs_embeds_q4.onnx"), F = !e.path || e.path.endsWith(".onnx") || e.path.endsWith(".onnx_data"), I = (t) => !e.folder || t.some(T);
|
|
253
|
+
if (F && !p.has("config.json") && (N || P || M.length) && l.issues.push("The ONNX adapter needs a root config.json describing the model architecture."), F && (N || P || M.length) && p.has("config.json")) {
|
|
254
|
+
let n = p.get("config.json").size;
|
|
255
|
+
if (!Number.isSafeInteger(n) || n > 256e3) l.issues.push("The Hub config is missing size metadata or exceeds the inspection limit.");
|
|
256
|
+
else {
|
|
257
|
+
let n = await j(C(a, o, "config.json"), t), r = n.ok ? await n.json().catch(() => null) : null;
|
|
258
|
+
if (O(r)) {
|
|
259
|
+
let t = g(u);
|
|
260
|
+
t.length ? l.issues.push(`The Laya adapter needs these files: ${t.join(", ")}.`) : (!e.path || u.includes(e.path)) && I(u) && m("laya-choice", u);
|
|
261
|
+
} else if (k(r)) {
|
|
262
|
+
let t = g(d);
|
|
263
|
+
t.length ? l.issues.push(`The Janus adapter needs these files: ${t.join(", ")}.`) : (!e.path || d.includes(e.path)) && I(d) && m("janus-image", d);
|
|
264
|
+
} else if (M.length && _(r)) {
|
|
265
|
+
let e = g(h);
|
|
266
|
+
if (e.length) l.issues.push(`The ONNX chat adapter needs these files: ${e.join(", ")}.`);
|
|
267
|
+
else for (let e of M) {
|
|
268
|
+
let t = y(e, S);
|
|
269
|
+
if (!t) {
|
|
270
|
+
l.verdict = "Files missing", l.issues.push(`The external weight files for ${e} are incomplete.`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
let n = b(r, e);
|
|
274
|
+
if (t.length < n) {
|
|
275
|
+
l.verdict = "Files missing", l.issues.push(`${e} expects ${n} external weight files. The repository lists ${t.length}.`);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
let i = ["generation_config.json", "chat_template.jinja"].filter((e) => p.has(e));
|
|
279
|
+
m("onnx-chat", [
|
|
280
|
+
e,
|
|
281
|
+
...h,
|
|
282
|
+
...t,
|
|
283
|
+
...i
|
|
284
|
+
]);
|
|
285
|
+
}
|
|
286
|
+
} else N && (/laya/i.test(a) || s.includes("laya")) ? l.issues.push("The Laya adapter needs the English ModernBERT choice configuration and the matching FP16 ONNX export.") : P && l.issues.push("The Janus adapter needs a MultiModalityCausalLM configuration and its matching ONNX pipeline.");
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (F && a.toLowerCase() === "schmuell/sd-turbo-ort-web" && (!e.path || f.includes(e.path)) && I(f)) {
|
|
290
|
+
let e = g(f);
|
|
291
|
+
e.length ? l.issues.push(`The SD-Turbo adapter needs these files: ${e.join(", ")}.`) : m("sd-turbo", f);
|
|
292
|
+
}
|
|
293
|
+
if (!l.candidates.length && !l.issues.length) {
|
|
294
|
+
if (E.some((e) => /\.litertlm$/i.test(e))) l.issues.push("A LiteRT-LM file was found. Link to a browser export, or tag the repository webgpu if its checkpoint was built for the browser.");
|
|
295
|
+
else if (E.some((e) => /\.onnx$/i.test(e))) l.issues.push("ONNX files were found, but the architecture or graph layout does not match a supported adapter.");
|
|
296
|
+
else if (E.some((e) => /\.(safetensors|gguf|bin)$/i.test(e))) {
|
|
297
|
+
let e = [
|
|
298
|
+
"SafeTensors",
|
|
299
|
+
"GGUF",
|
|
300
|
+
"BIN"
|
|
301
|
+
].filter((e) => E.some((t) => t.toLowerCase().endsWith(`.${e.toLowerCase()}`)));
|
|
302
|
+
l.issues.push(`Found ${e.join(" and ")} weights. This runtime needs a browser-compatible ONNX or LiteRT-LM export.`);
|
|
303
|
+
} else l.issues.push("No supported model files were found at this link. Try the model repository URL or a browser export.");
|
|
304
|
+
}
|
|
305
|
+
return l.canFindRelated = E.some((e) => /\.(onnx|litertlm|safetensors|gguf|bin)$/i.test(e)), l;
|
|
306
|
+
}
|
|
307
|
+
async function N(e, t, n) {
|
|
308
|
+
let r = t.path || t.folder ? await M({
|
|
309
|
+
repo: t.repo,
|
|
310
|
+
revision: t.revision
|
|
311
|
+
}, n) : null;
|
|
312
|
+
if (r?.candidates.length) return [r];
|
|
313
|
+
let i = x(e.upstream) ? e.upstream : e.repo, a = await Promise.allSettled(["transformers.js", "litert-lm"].map(async (t) => {
|
|
314
|
+
let r = new URLSearchParams({
|
|
315
|
+
limit: "4",
|
|
316
|
+
sort: "downloads",
|
|
317
|
+
direction: "-1"
|
|
318
|
+
});
|
|
319
|
+
r.append("filter", `base_model:quantized:${i}`), r.append("filter", t);
|
|
320
|
+
let a = await j(`https://huggingface.co/api/models?${r}`, n);
|
|
321
|
+
if (!a.ok) return [];
|
|
322
|
+
let o = await a.json();
|
|
323
|
+
return Array.isArray(o) ? o.filter((t) => x(t.id) && !t.gated && !t.private && t.id.toLowerCase() !== e.repo.toLowerCase() && t.tags?.includes(`base_model:quantized:${i}`)) : [];
|
|
324
|
+
})), o = [...new Set(a.flatMap((e) => e.status === "fulfilled" ? e.value.map((e) => e.id) : []))];
|
|
325
|
+
return (await Promise.allSettled(o.map((e) => M({ repo: e }, n)))).flatMap((e) => e.status === "fulfilled" && e.value.candidates.length ? [e.value] : []).slice(0, 3);
|
|
326
|
+
}
|
|
327
|
+
async function P(e, { signal: t, findRelated: n = !0 } = {}) {
|
|
328
|
+
let r = await M(e, t);
|
|
329
|
+
return n && !r.candidates.length && r.canFindRelated && (r.alternatives = await N(r, e, t).catch((e) => {
|
|
330
|
+
if (t?.aborted) throw e;
|
|
331
|
+
return [];
|
|
332
|
+
})), r;
|
|
333
|
+
}
|
|
334
|
+
// src/model-discovery.js
|
|
335
|
+
var F = "https://huggingface.co/models?library=transformers.js&pipeline_tag=text-generation&other=onnx&num_parameters=min:0,max:3B&sort=downloads";
|
|
336
|
+
function I({ version: e, adapter: t, repo: n, revision: r, files: i }, a) {
|
|
337
|
+
let o = {
|
|
338
|
+
adapter: t,
|
|
339
|
+
repo: n,
|
|
340
|
+
revision: r,
|
|
341
|
+
files: i.map(({ path: e, size: t, sha256: n }) => Object.freeze({
|
|
342
|
+
path: e,
|
|
343
|
+
size: t,
|
|
344
|
+
...n ? { sha256: n } : {}
|
|
345
|
+
}))
|
|
346
|
+
}, s = t === "onnx-chat" ? v(i[0].path).dtype : void 0, c = l[t].task, u = a ? {
|
|
347
|
+
...a,
|
|
348
|
+
source: "local",
|
|
349
|
+
name: s ? `${a.name} · ${s.toUpperCase()}` : a.name
|
|
350
|
+
} : {
|
|
351
|
+
repo: n,
|
|
352
|
+
revision: r,
|
|
353
|
+
id: T(o),
|
|
354
|
+
name: E(o)
|
|
355
|
+
};
|
|
356
|
+
return Object.freeze({
|
|
357
|
+
version: e,
|
|
358
|
+
adapter: t,
|
|
359
|
+
...u,
|
|
360
|
+
files: Object.freeze(o.files),
|
|
361
|
+
bytes: D(o),
|
|
362
|
+
task: c,
|
|
363
|
+
variant: s,
|
|
364
|
+
requiresFp16: s === "q4f16" || s === "fp16" || c !== "chat"
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
async function L({ task: e, search: t, maxDownloadBytes: n = 1e400 } = {}) {
|
|
368
|
+
let { default: r } = await import("./model-catalog-D6UCYXpI.js"), i = t?.toLowerCase().trim();
|
|
369
|
+
return r.filter((t) => (!e || l[t.adapter].task === e) && (!i || t.repo.toLowerCase().includes(i)) && D(t) <= n).map((e) => I(e));
|
|
370
|
+
}
|
|
371
|
+
function R(e) {
|
|
372
|
+
return {
|
|
373
|
+
repo: e.repo,
|
|
374
|
+
revision: e.revision,
|
|
375
|
+
status: e.candidates.length ? "ready" : e.verdict === "Access required" ? "access-required" : "unsupported",
|
|
376
|
+
models: e.candidates.map((e) => I(e)),
|
|
377
|
+
issues: e.issues.slice(),
|
|
378
|
+
alternatives: (e.alternatives ?? []).map(R)
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
async function z(e, { signal: n, findRelated: i = !0 } = {}) {
|
|
382
|
+
let a = "inspectModel";
|
|
383
|
+
r(n, a);
|
|
384
|
+
let o;
|
|
385
|
+
try {
|
|
386
|
+
if (o = typeof e == "string" ? A(e) : void 0, !o) throw Error("Use a public Hugging Face model URL.");
|
|
387
|
+
} catch (e) {
|
|
388
|
+
throw new t("INVALID_MODEL", e.message, {
|
|
389
|
+
operation: a,
|
|
390
|
+
cause: e
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
return R(await P(o, {
|
|
395
|
+
signal: n,
|
|
396
|
+
findRelated: i
|
|
397
|
+
}));
|
|
398
|
+
} catch (e) {
|
|
399
|
+
r(n, a, o.repo);
|
|
400
|
+
let i = e instanceof TypeError ? "Check your internet connection and retry." : e.message;
|
|
401
|
+
throw new t("HUB_REQUEST_FAILED", `Could not inspect ${o.repo}. ${i}`, {
|
|
402
|
+
operation: a,
|
|
403
|
+
repo: o.repo,
|
|
404
|
+
cause: e
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
// src/local-models.js
|
|
409
|
+
var B = "scanLocalModels", V = /* @__PURE__ */ new WeakMap(), H = /(?:\.(?:json|jinja|litertlm|onnx|gguf|safetensors|bin)|\.onnx_data(?:_\d+)?|^sha256-[a-f0-9]{64})$/i, ee = /(?:^|\/)((?:onnx|text_encoder|unet|vae_decoder|tokenizer)\/[^/]+)$/, U = ["generation_config.json", "chat_template.jinja"];
|
|
410
|
+
function W(e) {
|
|
411
|
+
return V.get(e);
|
|
412
|
+
}
|
|
413
|
+
async function* te(e, t, n) {
|
|
414
|
+
let i = [{
|
|
415
|
+
directory: e,
|
|
416
|
+
prefix: e.name
|
|
417
|
+
}];
|
|
418
|
+
for (; i.length;) {
|
|
419
|
+
let { directory: e, prefix: a } = i.pop();
|
|
420
|
+
for await (let o of e.values()) {
|
|
421
|
+
r(t, B);
|
|
422
|
+
let e = `${a}/${o.name}`;
|
|
423
|
+
if (o.kind === "directory") i.push({
|
|
424
|
+
directory: o,
|
|
425
|
+
prefix: e
|
|
426
|
+
});
|
|
427
|
+
else if (H.test(o.name)) {
|
|
428
|
+
let t = await o.getFile().catch(() => {
|
|
429
|
+
n.push(`Could not read ${e}.`);
|
|
430
|
+
});
|
|
431
|
+
t && (yield [e, t]);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function* ne(e) {
|
|
437
|
+
for (let n of e) {
|
|
438
|
+
if (!(n instanceof Blob) || typeof n.name != "string") throw new t("INVALID_ARGUMENT", "Pass a folder handle or an iterable of selected File objects.", { operation: B });
|
|
439
|
+
H.test(n.name) && (yield [n.webkitRelativePath || n.name, n]);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
async function re(e, { signal: n, task: i } = {}) {
|
|
443
|
+
r(n, B);
|
|
444
|
+
let a = e?.kind === "directory" && typeof e.values == "function";
|
|
445
|
+
if (!a && typeof e?.[Symbol.iterator] != "function") throw new t("INVALID_ARGUMENT", "Pass a folder handle or an iterable of selected File objects.", { operation: B });
|
|
446
|
+
let o = /* @__PURE__ */ new Map(), s = [], c = [], l = /* @__PURE__ */ new Set();
|
|
447
|
+
function g(e, t, n, r, a) {
|
|
448
|
+
let o = new Map(r.map((e) => [e, n.get(e)])), l = {
|
|
449
|
+
version: 1,
|
|
450
|
+
source: "local",
|
|
451
|
+
adapter: e,
|
|
452
|
+
repo: m,
|
|
453
|
+
files: [...o].map(([e, t]) => ({
|
|
454
|
+
path: e,
|
|
455
|
+
size: t?.size
|
|
456
|
+
}))
|
|
457
|
+
};
|
|
458
|
+
if (!w(l)) {
|
|
459
|
+
c.push(`${t || a || "Selected files"} contains an empty or invalid ${e} model file.`);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
let u = I(l, {
|
|
463
|
+
id: `local:${e}:${t}/${a ?? r[0]}`,
|
|
464
|
+
name: a ?? (t.split("/").at(-1) || e),
|
|
465
|
+
folder: t
|
|
466
|
+
});
|
|
467
|
+
i && u.task !== i || (V.set(u, {
|
|
468
|
+
registration: l,
|
|
469
|
+
files: o
|
|
470
|
+
}), s.push(u));
|
|
471
|
+
}
|
|
472
|
+
function x(e, t, n) {
|
|
473
|
+
let r = n.filter((e) => !t.has(e));
|
|
474
|
+
return r.length && c.push(`${e || "Selected files"} is missing ${r.join(", ")}.`), !r.length;
|
|
475
|
+
}
|
|
476
|
+
try {
|
|
477
|
+
let t = a ? te(e, n, c) : ne(e);
|
|
478
|
+
for await (let [e, a] of t) {
|
|
479
|
+
r(n, B);
|
|
480
|
+
let t = a.name;
|
|
481
|
+
if (/\.litertlm$/i.test(t)) {
|
|
482
|
+
if (i && i !== "chat") continue;
|
|
483
|
+
let o = await a.slice(0, 8).text().catch(() => "");
|
|
484
|
+
r(n, B), o !== "LITERTLM" || /(?:^|[-_])npu(?:[-_.]|$)/i.test(t) ? c.push(`${e} does not look like a WebGPU-compatible LiteRT-LM checkpoint.`) : g("litert-chat", e.slice(0, e.length - t.length).replace(/\/$/, ""), /* @__PURE__ */ new Map([["model.litertlm", a]]), ["model.litertlm"], t);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
let s = /\.(gguf|safetensors|bin)$/i.exec(t)?.[1]?.toLowerCase();
|
|
488
|
+
if (s || /^sha256-[a-f0-9]{64}$/i.test(t)) {
|
|
489
|
+
l.add(s ?? "Ollama-style blobs");
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
let u = ee.exec(e)?.[1] ?? t, d = e.slice(0, e.length - u.length).replace(/\/$/, "");
|
|
493
|
+
o.has(d) || o.set(d, /* @__PURE__ */ new Map()), o.get(d).set(u, a);
|
|
494
|
+
}
|
|
495
|
+
for (let [e, t] of o) {
|
|
496
|
+
r(n, B);
|
|
497
|
+
let a = f.some((e) => t.has(e));
|
|
498
|
+
if (a && (!i || i === "image")) {
|
|
499
|
+
let n = [...f, ...p];
|
|
500
|
+
x(e, t, n) && g("sd-turbo", e, t, n);
|
|
501
|
+
}
|
|
502
|
+
let o = [...t.keys()];
|
|
503
|
+
if (!o.some((e) => /^onnx\/.*\.onnx$/.test(e))) {
|
|
504
|
+
o.some((e) => e.endsWith(".onnx")) && !a && c.push(`${e || "Selected files"} has ONNX weights in an unsupported layout. Keep the export’s config, tokenizer, and graph folders together.`);
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
let s = t.get("config.json");
|
|
508
|
+
if (!s || s.size > 256e3) {
|
|
509
|
+
c.push(`${e || "Selected files"} needs a readable config.json alongside its onnx folder.`);
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
let l = await s.text().then(JSON.parse).catch(() => null);
|
|
513
|
+
r(n, B);
|
|
514
|
+
let m = U.filter((e) => t.has(e));
|
|
515
|
+
if (O(l)) (!i || i === "classification") && x(e, t, u) && g("laya-choice", e, t, u);
|
|
516
|
+
else if (k(l)) (!i || i === "image") && x(e, t, d) && g("janus-image", e, t, [...d, ...m]);
|
|
517
|
+
else if (_(l) && o.some(v)) {
|
|
518
|
+
if (i && i !== "chat" || !x(e, t, h)) continue;
|
|
519
|
+
for (let n of o.filter(v)) {
|
|
520
|
+
let r = y(n, o);
|
|
521
|
+
!r || r.length < b(l, n) ? c.push(`${e}/${n} is missing external ONNX weights.`) : g("onnx-chat", e, t, [
|
|
522
|
+
n,
|
|
523
|
+
...h,
|
|
524
|
+
...r,
|
|
525
|
+
...m
|
|
526
|
+
]);
|
|
527
|
+
}
|
|
528
|
+
} else c.push(`${e || "Selected files"} does not match a supported ONNX adapter.`);
|
|
529
|
+
}
|
|
530
|
+
} catch (e) {
|
|
531
|
+
throw r(n, B), e instanceof t ? e : new t("LOCAL_READ_FAILED", "Could not read the selected files. Check folder permissions and select the folder again.", {
|
|
532
|
+
operation: B,
|
|
533
|
+
cause: e
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
return l.size && c.push(`Found ${[...l].join(", ")} files. Choose an ONNX or LiteRT-LM browser export.`), !s.length && !c.length && c.push(`The selection contains no supported ${i ? `${i} ` : ""}model exports.`), {
|
|
537
|
+
models: s,
|
|
538
|
+
issues: c
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
// src/model-session.js
|
|
542
|
+
function G(e, n, r, i) {
|
|
543
|
+
if (typeof e != "string" || !e.trim()) throw new t("INVALID_ARGUMENT", `${n} must be a non-empty string.`, {
|
|
544
|
+
operation: r,
|
|
545
|
+
repo: i
|
|
546
|
+
});
|
|
547
|
+
return e.trim();
|
|
548
|
+
}
|
|
549
|
+
function K(e, n, { cache: r, chatSettings: i } = {}) {
|
|
550
|
+
let { task: a, repo: o, adapter: s } = e, c = {
|
|
551
|
+
task: a,
|
|
552
|
+
model: e,
|
|
553
|
+
cache: r,
|
|
554
|
+
dispose: n.dispose
|
|
555
|
+
};
|
|
556
|
+
return a === "chat" ? {
|
|
557
|
+
...c,
|
|
558
|
+
chatSettings: i,
|
|
559
|
+
async chat(e, { signal: t, onToken: r, onFinish: a } = {}) {
|
|
560
|
+
let s = G(e, "Prompt", "chat", o), c = "";
|
|
561
|
+
return n.run("chat", {
|
|
562
|
+
type: "generate",
|
|
563
|
+
prompt: s
|
|
564
|
+
}, t, (e, t) => {
|
|
565
|
+
e.type === "delta" && (c += e.text, r?.(e.text)), e.type === "done" && (a?.({
|
|
566
|
+
finishReason: e.finishReason ?? "unknown",
|
|
567
|
+
...i,
|
|
568
|
+
...e.settings
|
|
569
|
+
}), t(c));
|
|
570
|
+
});
|
|
571
|
+
},
|
|
572
|
+
async reset({ signal: e, instructions: r, history: i = [] } = {}) {
|
|
573
|
+
let a = "reset", s = r === void 0 ? void 0 : G(r, "Instructions", a, o);
|
|
574
|
+
if (!Array.isArray(i) || i.length % 2 != 0) throw new t("INVALID_ARGUMENT", "History must contain complete user and assistant turns.", {
|
|
575
|
+
operation: a,
|
|
576
|
+
repo: o
|
|
577
|
+
});
|
|
578
|
+
let c = Array.from(i, (e, n) => {
|
|
579
|
+
let r = n % 2 ? "assistant" : "user";
|
|
580
|
+
if (e?.role !== r) throw new t("INVALID_ARGUMENT", "History must alternate user and assistant messages.", {
|
|
581
|
+
operation: a,
|
|
582
|
+
repo: o
|
|
583
|
+
});
|
|
584
|
+
return {
|
|
585
|
+
role: r,
|
|
586
|
+
content: G(e.content, "Message content", a, o)
|
|
587
|
+
};
|
|
588
|
+
});
|
|
589
|
+
return n.run(a, {
|
|
590
|
+
type: "reset",
|
|
591
|
+
instructions: s,
|
|
592
|
+
history: c
|
|
593
|
+
}, e, (e, t) => {
|
|
594
|
+
e.type === "reset" && t();
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
} : a === "image" ? {
|
|
598
|
+
...c,
|
|
599
|
+
async generateImage(e, { signal: r, seed: i, onProgress: a } = {}) {
|
|
600
|
+
let c = G(e, "Prompt", "generateImage", o);
|
|
601
|
+
if (i !== void 0 && (s !== "sd-turbo" || !Number.isInteger(i) || i < 0 || i > 0xffffffff)) throw new t("INVALID_ARGUMENT", "SD-Turbo accepts integer seeds from 0 to 4294967295. Janus chooses its own seed.", {
|
|
602
|
+
operation: "generateImage",
|
|
603
|
+
repo: o
|
|
604
|
+
});
|
|
605
|
+
let l = s === "sd-turbo" ? i ?? crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] : void 0;
|
|
606
|
+
return n.run("generateImage", {
|
|
607
|
+
type: "generate",
|
|
608
|
+
prompt: c,
|
|
609
|
+
seed: l
|
|
610
|
+
}, r, (e, t) => {
|
|
611
|
+
if (e.type === "generate-progress" && a?.({
|
|
612
|
+
fraction: e.fraction,
|
|
613
|
+
label: e.label
|
|
614
|
+
}), e.type === "result") {
|
|
615
|
+
let { blob: n, width: r, height: i } = e;
|
|
616
|
+
t({
|
|
617
|
+
blob: n,
|
|
618
|
+
width: r,
|
|
619
|
+
height: i,
|
|
620
|
+
...l === void 0 ? {} : { seed: l }
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
} : {
|
|
626
|
+
...c,
|
|
627
|
+
async classify(e, r, { signal: i, question: a = "Which category best matches this text?", onProgress: s } = {}) {
|
|
628
|
+
let c = "classify", l = Array.isArray(e) && Array.from(e);
|
|
629
|
+
if (!l || !l.every((e) => typeof e == "string" && e.trim())) throw new t("INVALID_ARGUMENT", "Texts must be an array of non-empty strings.", {
|
|
630
|
+
operation: c,
|
|
631
|
+
repo: o
|
|
632
|
+
});
|
|
633
|
+
if (!Array.isArray(r) || r.length < 3 || r.length > 5) throw new t("INVALID_ARGUMENT", "Provide three to five classification choices.", {
|
|
634
|
+
operation: c,
|
|
635
|
+
repo: o
|
|
636
|
+
});
|
|
637
|
+
let u = Array.from(r, (e) => typeof e == "string" ? { label: G(e, "Choice", c, o) } : {
|
|
638
|
+
label: G(e?.label, "Choice label", c, o),
|
|
639
|
+
description: e.description === void 0 ? void 0 : G(e.description, "Choice description", c, o)
|
|
640
|
+
}), d = u.map(({ label: e }) => e);
|
|
641
|
+
if (new Set(d).size !== d.length) throw new t("INVALID_ARGUMENT", "Give each classification choice a distinct label.", {
|
|
642
|
+
operation: c,
|
|
643
|
+
repo: o
|
|
644
|
+
});
|
|
645
|
+
let f = G(a, "Question", c, o), p = [], m = {
|
|
646
|
+
type: "run",
|
|
647
|
+
messages: l,
|
|
648
|
+
choices: u.map(({ label: e, description: t }) => t ? `${e}: ${t}` : e),
|
|
649
|
+
question: f
|
|
650
|
+
};
|
|
651
|
+
return n.run(c, m, i, (e, t) => {
|
|
652
|
+
if (e.type === "batch") {
|
|
653
|
+
for (let t of e.records) p.push({
|
|
654
|
+
index: t.route,
|
|
655
|
+
label: d[t.route],
|
|
656
|
+
scores: t.probabilities,
|
|
657
|
+
truncated: t.truncated
|
|
658
|
+
});
|
|
659
|
+
s?.({
|
|
660
|
+
completed: p.length,
|
|
661
|
+
total: l.length
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
e.type === "done" && t(p);
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
// src/cache-store.js
|
|
670
|
+
var q = "browser-model-sdk-weights-v1", J = "transformers-cache", Y = {
|
|
671
|
+
repo: "Xenova/clip-vit-base-patch32",
|
|
672
|
+
revision: "6b7c523703ae26e39be4b03774966f8571c7f523",
|
|
673
|
+
files: [{
|
|
674
|
+
path: "tokenizer.json",
|
|
675
|
+
size: 2224119
|
|
676
|
+
}, {
|
|
677
|
+
path: "tokenizer_config.json",
|
|
678
|
+
size: 775
|
|
679
|
+
}]
|
|
680
|
+
};
|
|
681
|
+
function ie(e) {
|
|
682
|
+
return `browser-model-sdk-${e}.litertlm`;
|
|
683
|
+
}
|
|
684
|
+
function ae(e) {
|
|
685
|
+
if (e.source === "local") return e.files;
|
|
686
|
+
let t = e.files.map((t) => {
|
|
687
|
+
let n = e.adapter === "litert-chat" ? "opfs" : e.adapter === "sd-turbo" || e.adapter === "laya-choice" && t.path.startsWith("onnx/") ? q : J;
|
|
688
|
+
return {
|
|
689
|
+
...t,
|
|
690
|
+
store: n,
|
|
691
|
+
url: C(e.repo, e.revision, t.path)
|
|
692
|
+
};
|
|
693
|
+
});
|
|
694
|
+
if (e.adapter === "sd-turbo") for (let e of Y.files) t.push({
|
|
695
|
+
...e,
|
|
696
|
+
path: `tokenizer/${e.path}`,
|
|
697
|
+
store: J,
|
|
698
|
+
url: C(Y.repo, Y.revision, e.path)
|
|
699
|
+
});
|
|
700
|
+
return t;
|
|
701
|
+
}
|
|
702
|
+
// src/preflight.js
|
|
703
|
+
function X(e, n) {
|
|
704
|
+
if (![
|
|
705
|
+
"prefer",
|
|
706
|
+
"require",
|
|
707
|
+
"memory-only"
|
|
708
|
+
].includes(e)) throw new t("INVALID_ARGUMENT", "Cache must be prefer, require, or memory-only.", { operation: n });
|
|
709
|
+
}
|
|
710
|
+
async function Z(t, n) {
|
|
711
|
+
let r = globalThis.navigator, i = await e(), a = {
|
|
712
|
+
secureContext: !0,
|
|
713
|
+
webgpu: !0,
|
|
714
|
+
webassembly: !0,
|
|
715
|
+
worker: !0,
|
|
716
|
+
shaderFp16: t.requiresFp16,
|
|
717
|
+
offscreenCanvas: t.task === "image",
|
|
718
|
+
persistentCache: t.source !== "local" && n === "require"
|
|
719
|
+
}, o = [];
|
|
720
|
+
function s(e, t, n) {
|
|
721
|
+
e || o.push({
|
|
722
|
+
code: t,
|
|
723
|
+
message: n
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
return s(globalThis.isSecureContext, "SECURE_CONTEXT", "Use HTTPS or localhost."), s(typeof Worker == "function", "WORKERS", "This browser does not support dedicated workers."), s(typeof WebAssembly < "u", "WASM", "This browser does not support WebAssembly."), s(i.webgpu, "WEBGPU", "This browser does not have an available WebGPU adapter."), a.shaderFp16 && s(i.shaderFp16, "FP16", "This export requires WebGPU FP16 shaders."), a.offscreenCanvas && s(typeof OffscreenCanvas < "u", "OFFSCREEN_CANVAS", "Image generation needs OffscreenCanvas."), a.persistentCache && s(t.adapter === "litert-chat" ? r?.storage?.getDirectory && r?.locks : globalThis.caches !== void 0, "CACHE_UNAVAILABLE", "Required model cache storage is unavailable. Try cache: prefer or memory-only."), {
|
|
727
|
+
device: i,
|
|
728
|
+
requirements: a,
|
|
729
|
+
blockers: o
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
async function Q(e) {
|
|
733
|
+
try {
|
|
734
|
+
if (e.store === "opfs") return (await (await (await navigator.storage.getDirectory()).getFileHandle(ie(e.sha256))).getFile()).size === e.size ? "cached" : "missing";
|
|
735
|
+
if (!await caches.has(e.store)) return "missing";
|
|
736
|
+
let t = await caches.match(e.url, { cacheName: e.store });
|
|
737
|
+
if (!t) return "missing";
|
|
738
|
+
let n = t.headers.get("Content-Length");
|
|
739
|
+
return n === null ? "unknown" : Number(n) === e.size ? "cached" : "missing";
|
|
740
|
+
} catch (e) {
|
|
741
|
+
return e.name === "NotFoundError" ? "missing" : "unknown";
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
async function oe(e, { cache: n = "prefer", signal: i } = {}) {
|
|
745
|
+
let a = "preflightModel";
|
|
746
|
+
X(n, a), r(i, a);
|
|
747
|
+
let o = W(e);
|
|
748
|
+
if (!o && (e?.source === "local" || !w(e))) throw new t("INVALID_MODEL", "Pass a descriptor from listModels, inspectModel, or scanLocalModels.", { operation: a });
|
|
749
|
+
let s = o ? e : I(e), [c, l] = await Promise.all([Z(s, n), Promise.all(ae(s).map(async ({ path: e, size: t, ...r }) => ({
|
|
750
|
+
path: e,
|
|
751
|
+
size: t,
|
|
752
|
+
state: o ? "local" : n === "memory-only" ? "bypassed" : await Q({
|
|
753
|
+
...r,
|
|
754
|
+
size: t
|
|
755
|
+
})
|
|
756
|
+
})))]);
|
|
757
|
+
r(i, a, s.repo);
|
|
758
|
+
let u = l.reduce((e, t) => e + (t.state === "missing" || t.state === "bypassed" ? t.size : 0), 0);
|
|
759
|
+
return {
|
|
760
|
+
...c,
|
|
761
|
+
files: l,
|
|
762
|
+
totalBytes: l.reduce((e, t) => e + t.size, 0),
|
|
763
|
+
downloadBytes: l.some(({ state: e }) => e === "unknown") ? null : u,
|
|
764
|
+
knownDownloadBytes: u
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
// src/worker-factories.js
|
|
768
|
+
var $ = () => import("./image.worker-Bw4MnkKd.js"), se = {
|
|
769
|
+
"litert-chat": () => import("./inference.worker-ObNSBgG3.js"),
|
|
770
|
+
"onnx-chat": () => import("./onnx-chat.worker-BbP3C_6v.js"),
|
|
771
|
+
"laya-choice": () => import("./laya.worker-DgRSLTIF.js"),
|
|
772
|
+
"janus-image": $,
|
|
773
|
+
"sd-turbo": $
|
|
774
|
+
};
|
|
775
|
+
// src/worker-transport.js
|
|
776
|
+
function ce(e, r) {
|
|
777
|
+
let i, a;
|
|
778
|
+
function o(t) {
|
|
779
|
+
a || (a = t, e.terminate(), i?.reject(t));
|
|
780
|
+
}
|
|
781
|
+
function s(e, n) {
|
|
782
|
+
o(new t("WORKER_FAILED", e, {
|
|
783
|
+
operation: i?.operation,
|
|
784
|
+
repo: r,
|
|
785
|
+
cause: n
|
|
786
|
+
}));
|
|
787
|
+
}
|
|
788
|
+
return e.addEventListener("error", (e) => {
|
|
789
|
+
e.preventDefault(), s(e.message || "The browser could not run the model worker. Check worker CSP permissions.", e.error);
|
|
790
|
+
}), e.addEventListener("messageerror", () => s("The model worker sent an unreadable response.")), e.addEventListener("message", ({ data: e }) => {
|
|
791
|
+
let n = i;
|
|
792
|
+
if (e.type === "error" && !n) s(e.message);
|
|
793
|
+
else if (n) {
|
|
794
|
+
if (e.type === "error" || e.type === "generation-error") {
|
|
795
|
+
let i = new t(n.operation === "openModel" ? "LOAD_FAILED" : "INFERENCE_FAILED", e.message, {
|
|
796
|
+
operation: n.operation,
|
|
797
|
+
repo: r,
|
|
798
|
+
details: e.details,
|
|
799
|
+
cause: e.cause
|
|
800
|
+
});
|
|
801
|
+
n.operation === "openModel" || e.fatal ? o(i) : n.reject(i);
|
|
802
|
+
} else try {
|
|
803
|
+
n.receive(e, n.resolve);
|
|
804
|
+
} catch (e) {
|
|
805
|
+
o(new t("CALLBACK_FAILED", "A model callback threw an error.", {
|
|
806
|
+
operation: n.operation,
|
|
807
|
+
repo: r,
|
|
808
|
+
cause: e
|
|
809
|
+
}));
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}), {
|
|
813
|
+
run(s, c, l, u) {
|
|
814
|
+
return a ? Promise.reject(new t("DISPOSED", "This model is closed. Call openModel again.", {
|
|
815
|
+
operation: s,
|
|
816
|
+
repo: r,
|
|
817
|
+
cause: a
|
|
818
|
+
})) : l?.aborted ? Promise.reject(n(l, s, r)) : i ? Promise.reject(new t("BUSY", "Wait for the current model operation to finish.", {
|
|
819
|
+
operation: s,
|
|
820
|
+
repo: r
|
|
821
|
+
})) : new Promise((a, d) => {
|
|
822
|
+
let f = () => o(n(l, s, r));
|
|
823
|
+
function p(e, t) {
|
|
824
|
+
i === m && (l?.removeEventListener("abort", f), i = void 0, e(t));
|
|
825
|
+
}
|
|
826
|
+
let m = {
|
|
827
|
+
operation: s,
|
|
828
|
+
receive: u,
|
|
829
|
+
resolve: (e) => p(a, e),
|
|
830
|
+
reject: (e) => p(d, e)
|
|
831
|
+
};
|
|
832
|
+
i = m;
|
|
833
|
+
try {
|
|
834
|
+
l?.addEventListener("abort", f, { once: !0 }), e.postMessage(c);
|
|
835
|
+
} catch (e) {
|
|
836
|
+
o(new t("WORKER_FAILED", "Could not send a request to the model worker.", {
|
|
837
|
+
operation: s,
|
|
838
|
+
repo: r,
|
|
839
|
+
cause: e
|
|
840
|
+
}));
|
|
841
|
+
}
|
|
842
|
+
});
|
|
843
|
+
},
|
|
844
|
+
dispose() {
|
|
845
|
+
o(new t("DISPOSED", "The model was disposed.", {
|
|
846
|
+
operation: i?.operation,
|
|
847
|
+
repo: r
|
|
848
|
+
}));
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
// src/index.js
|
|
853
|
+
async function le(e, n, r) {
|
|
854
|
+
let i = "openModel";
|
|
855
|
+
if (typeof e == "string") {
|
|
856
|
+
let a = await z(e, {
|
|
857
|
+
signal: r,
|
|
858
|
+
findRelated: !1
|
|
859
|
+
}), o = a.models.find((e) => !n || e.task === n);
|
|
860
|
+
if (o) return o;
|
|
861
|
+
let s = a.status === "access-required" ? "ACCESS_REQUIRED" : "UNSUPPORTED_MODEL", c = n ? `Choose a compatible ${n} export.` : "Call inspectModel to find related browser exports.";
|
|
862
|
+
throw new t(s, [a.issues[0], c].filter(Boolean).join(" "), {
|
|
863
|
+
operation: i,
|
|
864
|
+
repo: a.repo
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
if (e?.source === "local") throw new t("INVALID_MODEL", "Pass the local model descriptor returned by scanLocalModels. Scan the folder again if the descriptor was copied or saved separately.", { operation: i });
|
|
868
|
+
if (!w(e)) throw new t("INVALID_MODEL", "Pass a model descriptor from listModels, inspectModel, or scanLocalModels, or a Hugging Face URL.", { operation: i });
|
|
869
|
+
return I(e);
|
|
870
|
+
}
|
|
871
|
+
async function ue(e, { task: n, signal: i, onProgress: a, cache: o = "prefer", maxOutputTokens: s } = {}) {
|
|
872
|
+
let c = "openModel";
|
|
873
|
+
X(o, c), r(i, c);
|
|
874
|
+
let l = W(e), u = l ? e : await le(e, n, i);
|
|
875
|
+
if (n && u.task !== n) throw new t("UNSUPPORTED_MODEL", `This export supports ${u.task}. Choose a ${n} export.`, {
|
|
876
|
+
operation: c,
|
|
877
|
+
repo: u.repo
|
|
878
|
+
});
|
|
879
|
+
if (s !== void 0 && (u.task !== "chat" || !Number.isSafeInteger(s) || s <= 0)) throw new t("INVALID_ARGUMENT", "maxOutputTokens must be a positive integer for a chat model.", {
|
|
880
|
+
operation: c,
|
|
881
|
+
repo: u.repo
|
|
882
|
+
});
|
|
883
|
+
let { blockers: d } = await Z(u, o);
|
|
884
|
+
if (r(i, c, u.repo), d.length) {
|
|
885
|
+
let { code: e, message: n } = d[0];
|
|
886
|
+
throw new t("DEVICE_UNSUPPORTED", n, {
|
|
887
|
+
operation: c,
|
|
888
|
+
repo: u.repo,
|
|
889
|
+
details: {
|
|
890
|
+
kind: e === "CACHE_UNAVAILABLE" ? "cache" : "device",
|
|
891
|
+
stage: "preflight",
|
|
892
|
+
retryable: !1
|
|
893
|
+
}
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
let f;
|
|
897
|
+
try {
|
|
898
|
+
let { default: e } = await se[u.adapter]();
|
|
899
|
+
r(i, c, u.repo), f = new e({ name: u.adapter });
|
|
900
|
+
} catch (e) {
|
|
901
|
+
throw r(i, c, u.repo), new t("WORKER_FAILED", "Could not start the model worker. Check that this site allows blob workers.", {
|
|
902
|
+
operation: c,
|
|
903
|
+
repo: u.repo,
|
|
904
|
+
cause: e
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
let p = ce(f, u.repo), m = 0;
|
|
908
|
+
try {
|
|
909
|
+
let e = {
|
|
910
|
+
type: "load",
|
|
911
|
+
registration: l?.registration ?? u,
|
|
912
|
+
localFiles: l?.files,
|
|
913
|
+
cache: o,
|
|
914
|
+
maxOutputTokens: s
|
|
915
|
+
};
|
|
916
|
+
return K(u, p, await p.run(c, e, i, (e, t) => {
|
|
917
|
+
(e.type === "load-progress" || e.type === "progress") && (Number.isFinite(e.loaded) && (m = Math.max(m, Math.min(e.loaded, u.bytes))), a?.({
|
|
918
|
+
stage: l ? "read" : "download",
|
|
919
|
+
loadedBytes: m,
|
|
920
|
+
totalBytes: u.bytes
|
|
921
|
+
})), (e.type === "initializing" || e.type === "preparing") && a?.({
|
|
922
|
+
stage: "initialize",
|
|
923
|
+
loadedBytes: u.bytes,
|
|
924
|
+
totalBytes: u.bytes
|
|
925
|
+
}), e.type === "ready" && (a?.({
|
|
926
|
+
stage: "ready",
|
|
927
|
+
loadedBytes: u.bytes,
|
|
928
|
+
totalBytes: u.bytes
|
|
929
|
+
}), t({
|
|
930
|
+
cache: e.cache,
|
|
931
|
+
chatSettings: e.chatSettings
|
|
932
|
+
}));
|
|
933
|
+
}));
|
|
934
|
+
} catch (e) {
|
|
935
|
+
throw p.dispose(), e;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
export { F as HUGGING_FACE_BROWSE_URL, t as ModelError, e as getDeviceInfo, z as inspectModel, L as listModels, ue as openModel, oe as preflightModel, re as scanLocalModels };
|