@p2arthur/webinference-sdk 0.0.0-stage → 0.1.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.
- package/README.md +120 -2
- package/dist/image.worker-DCCSYqzK.js +15 -0
- package/dist/index.js +653 -0
- package/dist/inference.worker-CuwWqHQs.js +15 -0
- package/dist/laya.worker-Dku9wD9_.js +15 -0
- package/dist/model-catalog-D6UCYXpI.js +3 -0
- package/dist/onnx-chat.worker-BkdwoJoF.js +15 -0
- package/index.d.ts +161 -0
- package/package.json +34 -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,653 @@
|
|
|
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 } = {}) {
|
|
16
|
+
super(t, { cause: i }), this.name = "ModelError", this.code = e, this.operation = n, this.repo = r;
|
|
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 = [
|
|
59
|
+
"config.json",
|
|
60
|
+
"tokenizer.json",
|
|
61
|
+
"tokenizer_config.json"
|
|
62
|
+
], m = /* @__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 h(e) {
|
|
87
|
+
return m.has(e?.model_type) && !e.is_encoder_decoder && (!Array.isArray(e.architectures) || e.architectures.some((e) => /(?:CausalLM|LMHeadModel)$/.test(e)));
|
|
88
|
+
}
|
|
89
|
+
function g(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 _(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 v(e) {
|
|
103
|
+
return typeof e == "string" && a.test(e) && e.split("/").every((e) => c.test(e));
|
|
104
|
+
}
|
|
105
|
+
function y(e) {
|
|
106
|
+
return typeof e == "string" && c.test(e);
|
|
107
|
+
}
|
|
108
|
+
function b(e, t, n) {
|
|
109
|
+
return `${i}/${e}/resolve/${t}/${n.split("/").map(encodeURIComponent).join("/")}`;
|
|
110
|
+
}
|
|
111
|
+
function x(e) {
|
|
112
|
+
if (!e || e.version !== 1 || !Object.hasOwn(l, e.adapter) || !v(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 && y(e.path) && Number.isSafeInteger(e.size) && e.size > 0 && (e.sha256 === void 0 || typeof e.sha256 == "string" && s.test(e.sha256)))) return !1;
|
|
113
|
+
let t = new Set(e.files.map(({ path: e }) => e));
|
|
114
|
+
if (t.size !== e.files.length) return !1;
|
|
115
|
+
switch (e.adapter) {
|
|
116
|
+
case "litert-chat": return e.files.length === 1 && /\.litertlm$/i.test(e.files[0].path) && s.test(e.files[0].sha256);
|
|
117
|
+
case "onnx-chat": {
|
|
118
|
+
let n = e.files[0].path;
|
|
119
|
+
return !!(g(n) && p.every((e) => t.has(e)) && _(n, [...t]));
|
|
120
|
+
}
|
|
121
|
+
case "laya-choice": return u.every((e) => t.has(e));
|
|
122
|
+
case "janus-image": return d.every((e) => t.has(e));
|
|
123
|
+
case "sd-turbo": return e.repo.toLowerCase() === "schmuell/sd-turbo-ort-web" && f.every((e) => t.has(e));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function S(e) {
|
|
127
|
+
let t = ["litert-chat", "onnx-chat"].includes(e.adapter) ? `/${e.files[0].path}` : "";
|
|
128
|
+
return `hub:${e.adapter}:${e.repo}@${e.revision}${t}`;
|
|
129
|
+
}
|
|
130
|
+
function C(e) {
|
|
131
|
+
return e.adapter === "onnx-chat" ? `${e.repo.split("/").at(-1)} · ${g(e.files[0].path)?.dtype.toUpperCase()}` : e.adapter === "litert-chat" ? e.files[0].path.split("/").at(-1).replace(/\.litertlm$/i, "") : e.repo;
|
|
132
|
+
}
|
|
133
|
+
function w(e) {
|
|
134
|
+
return e.files.reduce((e, t) => e + t.size, 0);
|
|
135
|
+
}
|
|
136
|
+
function T(e) {
|
|
137
|
+
let t = e?.laya;
|
|
138
|
+
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);
|
|
139
|
+
}
|
|
140
|
+
function E(e) {
|
|
141
|
+
return e?.model_type === "multi_modality" && Array.isArray(e.architectures) && e.architectures.includes("MultiModalityCausalLM");
|
|
142
|
+
}
|
|
143
|
+
// src/hub-inspector.js
|
|
144
|
+
function D(e) {
|
|
145
|
+
let t;
|
|
146
|
+
try {
|
|
147
|
+
t = new URL(e.trim());
|
|
148
|
+
} catch {
|
|
149
|
+
throw Error("Paste a Hugging Face model URL, such as https://huggingface.co/owner/model.");
|
|
150
|
+
}
|
|
151
|
+
if (t.origin !== "https://huggingface.co" || t.username || t.password) throw Error("Use a public model URL on huggingface.co.");
|
|
152
|
+
let n = t.pathname.replace(/^\/|\/$/g, "").split("/").map(decodeURIComponent), r = n.slice(0, 2).join("/");
|
|
153
|
+
if (!v(r) || [
|
|
154
|
+
"datasets",
|
|
155
|
+
"spaces",
|
|
156
|
+
"collections",
|
|
157
|
+
"api"
|
|
158
|
+
].includes(n[0])) throw Error("This link needs to point to a Hugging Face model repository or model file.");
|
|
159
|
+
if (n.length === 2) return { repo: r };
|
|
160
|
+
let [, , i, a, ...o] = n;
|
|
161
|
+
if (![
|
|
162
|
+
"tree",
|
|
163
|
+
"blob",
|
|
164
|
+
"resolve"
|
|
165
|
+
].includes(i) || !a || a.length > 200 || /[?#\\]/.test(a)) throw Error("Use a repository, revision, or model file link from Hugging Face.");
|
|
166
|
+
let s = o.join("/");
|
|
167
|
+
if (s && !y(s) || i !== "tree" && !s) throw Error("This model file link is incomplete.");
|
|
168
|
+
return i === "tree" ? {
|
|
169
|
+
repo: r,
|
|
170
|
+
revision: a,
|
|
171
|
+
folder: s
|
|
172
|
+
} : {
|
|
173
|
+
repo: r,
|
|
174
|
+
revision: a,
|
|
175
|
+
path: s
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function O(e, t) {
|
|
179
|
+
return fetch(e, {
|
|
180
|
+
signal: t,
|
|
181
|
+
credentials: "omit",
|
|
182
|
+
headers: { Accept: "application/json" }
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
async function k(e, t) {
|
|
186
|
+
let n = `https://huggingface.co/api/models/${e.repo}`, r = await O(`${e.revision ? `${n}/revision/${encodeURIComponent(e.revision)}` : n}?blobs=true`, t);
|
|
187
|
+
if ([
|
|
188
|
+
401,
|
|
189
|
+
403,
|
|
190
|
+
404
|
|
191
|
+
].includes(r.status)) throw Error("Hugging Face could not open this public repository or revision. Check the link and its access settings.");
|
|
192
|
+
if (r.status === 429) throw Error("Hugging Face rate-limited the request. Try again in a moment.");
|
|
193
|
+
if (!r.ok) throw Error(`Hugging Face returned HTTP ${r.status}. Try again.`);
|
|
194
|
+
let i = await r.json(), a = v(i.id) ? i.id : e.repo, o = i.sha;
|
|
195
|
+
if (!/^[a-f0-9]{40}$/.test(o)) throw Error("The Hub did not return a commit for this model.");
|
|
196
|
+
let s = Array.isArray(i.tags) ? i.tags : [], c = s.find((e) => typeof e == "string" && e.startsWith("base_model:quantized:"))?.slice(21), l = {
|
|
197
|
+
repo: a,
|
|
198
|
+
revision: o,
|
|
199
|
+
task: i.pipeline_tag,
|
|
200
|
+
files: 0,
|
|
201
|
+
candidates: [],
|
|
202
|
+
issues: [],
|
|
203
|
+
upstream: c
|
|
204
|
+
};
|
|
205
|
+
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;
|
|
206
|
+
let m = new Map((i.siblings ?? []).map((e) => [e.rfilename, e]));
|
|
207
|
+
if (l.files = m.size, e.path && !m.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;
|
|
208
|
+
function y(e, t) {
|
|
209
|
+
let n = {
|
|
210
|
+
version: 1,
|
|
211
|
+
adapter: e,
|
|
212
|
+
repo: a,
|
|
213
|
+
revision: o,
|
|
214
|
+
files: t.map((e) => {
|
|
215
|
+
let t = m.get(e);
|
|
216
|
+
return {
|
|
217
|
+
path: e,
|
|
218
|
+
size: t?.size,
|
|
219
|
+
...t?.lfs?.sha256 ? { sha256: t.lfs.sha256 } : {}
|
|
220
|
+
};
|
|
221
|
+
})
|
|
222
|
+
};
|
|
223
|
+
x(n) ? l.candidates.push(n) : l.issues.push(`Hugging Face did not provide the required size or checksum metadata for ${t[0]}.`);
|
|
224
|
+
}
|
|
225
|
+
function S(e) {
|
|
226
|
+
let t = e.filter((e) => !m.has(e));
|
|
227
|
+
return t.length && (l.verdict = "Files missing"), t;
|
|
228
|
+
}
|
|
229
|
+
let C = [...m.keys()], w = (t) => (!e.path || t === e.path) && (!e.folder || t.startsWith(`${e.folder}/`)), D = C.filter(w);
|
|
230
|
+
if (e.folder && !D.length) return l.issues.push("This folder has no files at the selected revision. Try the repository URL."), l;
|
|
231
|
+
let k = C.filter((e) => /-(web|gpu)\.litertlm$/i.test(e));
|
|
232
|
+
if (k.length === 0 && D.some((e) => /\.litertlm$/i.test(e))) {
|
|
233
|
+
let e = s.includes("webgpu") || s.includes("browser");
|
|
234
|
+
if (!e && a.startsWith("litert-community/")) {
|
|
235
|
+
let n = await O("https://huggingface.co/api/collections/litert-community/web-llm-models", t);
|
|
236
|
+
n.ok && (e = (await n.json()).items?.some((e) => e.repoType === "model" && e.id === a));
|
|
237
|
+
}
|
|
238
|
+
e && k.push(...D.filter((e) => /\.litertlm$/i.test(e) && !/(?:^|[-_])npu(?:[-_.]|$)/i.test(e)).sort((e, t) => m.get(e).size - m.get(t).size));
|
|
239
|
+
}
|
|
240
|
+
for (let e of k.filter(w).sort((e, t) => Number(!/-web\.litertlm$/i.test(e)) - Number(!/-web\.litertlm$/i.test(t)))) y("litert-chat", [e]);
|
|
241
|
+
let A = [
|
|
242
|
+
"q4",
|
|
243
|
+
"q4f16",
|
|
244
|
+
"q8",
|
|
245
|
+
"fp16",
|
|
246
|
+
"fp32"
|
|
247
|
+
], j = C.filter((t) => g(t) && (w(t) || e.path?.startsWith(`${t}_data`))).sort((e, t) => A.indexOf(g(e).dtype) - A.indexOf(g(t).dtype)), M = /laya/i.test(a) || s.includes("laya") || m.has("onnx/model_fp16.onnx_data"), N = /janus/i.test(a) || s.includes("multi_modality") || m.has("onnx/prepare_inputs_embeds_q4.onnx"), P = !e.path || e.path.endsWith(".onnx") || e.path.endsWith(".onnx_data"), F = (t) => !e.folder || t.some(w);
|
|
248
|
+
if (P && !m.has("config.json") && (M || N || j.length) && l.issues.push("The ONNX adapter needs a root config.json describing the model architecture."), P && (M || N || j.length) && m.has("config.json")) {
|
|
249
|
+
let n = m.get("config.json").size;
|
|
250
|
+
if (!Number.isSafeInteger(n) || n > 256e3) l.issues.push("The Hub config is missing size metadata or exceeds the inspection limit.");
|
|
251
|
+
else {
|
|
252
|
+
let n = await O(b(a, o, "config.json"), t), r = n.ok ? await n.json().catch(() => null) : null;
|
|
253
|
+
if (T(r)) {
|
|
254
|
+
let t = S(u);
|
|
255
|
+
t.length ? l.issues.push(`The Laya adapter needs these files: ${t.join(", ")}.`) : (!e.path || u.includes(e.path)) && F(u) && y("laya-choice", u);
|
|
256
|
+
} else if (E(r)) {
|
|
257
|
+
let t = S(d);
|
|
258
|
+
t.length ? l.issues.push(`The Janus adapter needs these files: ${t.join(", ")}.`) : (!e.path || d.includes(e.path)) && F(d) && y("janus-image", d);
|
|
259
|
+
} else if (j.length && h(r)) {
|
|
260
|
+
let e = S(p);
|
|
261
|
+
if (e.length) l.issues.push(`The ONNX chat adapter needs these files: ${e.join(", ")}.`);
|
|
262
|
+
else for (let e of j) {
|
|
263
|
+
let t = _(e, C);
|
|
264
|
+
if (!t) {
|
|
265
|
+
l.verdict = "Files missing", l.issues.push(`The external weight files for ${e} are incomplete.`);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
let n = r["transformers.js_config"]?.use_external_data_format, i = e.split("/").at(-1), a = typeof n == "object" && n ? n[i] ?? n[g(e).modelFile] : n, o = a === !0 ? 1 : Number(a) || 0;
|
|
269
|
+
if (t.length < o) {
|
|
270
|
+
l.verdict = "Files missing", l.issues.push(`${e} expects ${o} external weight files. The repository lists ${t.length}.`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
let s = ["generation_config.json", "chat_template.jinja"].filter((e) => m.has(e));
|
|
274
|
+
y("onnx-chat", [
|
|
275
|
+
e,
|
|
276
|
+
...p,
|
|
277
|
+
...t,
|
|
278
|
+
...s
|
|
279
|
+
]);
|
|
280
|
+
}
|
|
281
|
+
} else M && (/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.") : N && l.issues.push("The Janus adapter needs a MultiModalityCausalLM configuration and its matching ONNX pipeline.");
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (P && a.toLowerCase() === "schmuell/sd-turbo-ort-web" && (!e.path || f.includes(e.path)) && F(f)) {
|
|
285
|
+
let e = S(f);
|
|
286
|
+
e.length ? l.issues.push(`The SD-Turbo adapter needs these files: ${e.join(", ")}.`) : y("sd-turbo", f);
|
|
287
|
+
}
|
|
288
|
+
if (!l.candidates.length && !l.issues.length) {
|
|
289
|
+
if (D.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.");
|
|
290
|
+
else if (D.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.");
|
|
291
|
+
else if (D.some((e) => /\.(safetensors|gguf|bin)$/i.test(e))) {
|
|
292
|
+
let e = [
|
|
293
|
+
"SafeTensors",
|
|
294
|
+
"GGUF",
|
|
295
|
+
"BIN"
|
|
296
|
+
].filter((e) => D.some((t) => t.toLowerCase().endsWith(`.${e.toLowerCase()}`)));
|
|
297
|
+
l.issues.push(`Found ${e.join(" and ")} weights. This runtime needs a browser-compatible ONNX or LiteRT-LM export.`);
|
|
298
|
+
} else l.issues.push("No supported model files were found at this link. Try the model repository URL or a browser export.");
|
|
299
|
+
}
|
|
300
|
+
return l.canFindRelated = D.some((e) => /\.(onnx|litertlm|safetensors|gguf|bin)$/i.test(e)), l;
|
|
301
|
+
}
|
|
302
|
+
async function A(e, t, n) {
|
|
303
|
+
let r = t.path || t.folder ? await k({
|
|
304
|
+
repo: t.repo,
|
|
305
|
+
revision: t.revision
|
|
306
|
+
}, n) : null;
|
|
307
|
+
if (r?.candidates.length) return [r];
|
|
308
|
+
let i = v(e.upstream) ? e.upstream : e.repo, a = await Promise.allSettled(["transformers.js", "litert-lm"].map(async (t) => {
|
|
309
|
+
let r = new URLSearchParams({
|
|
310
|
+
limit: "4",
|
|
311
|
+
sort: "downloads",
|
|
312
|
+
direction: "-1"
|
|
313
|
+
});
|
|
314
|
+
r.append("filter", `base_model:quantized:${i}`), r.append("filter", t);
|
|
315
|
+
let a = await O(`https://huggingface.co/api/models?${r}`, n);
|
|
316
|
+
if (!a.ok) return [];
|
|
317
|
+
let o = await a.json();
|
|
318
|
+
return Array.isArray(o) ? o.filter((t) => v(t.id) && !t.gated && !t.private && t.id.toLowerCase() !== e.repo.toLowerCase() && t.tags?.includes(`base_model:quantized:${i}`)) : [];
|
|
319
|
+
})), o = [...new Set(a.flatMap((e) => e.status === "fulfilled" ? e.value.map((e) => e.id) : []))];
|
|
320
|
+
return (await Promise.allSettled(o.map((e) => k({ repo: e }, n)))).flatMap((e) => e.status === "fulfilled" && e.value.candidates.length ? [e.value] : []).slice(0, 3);
|
|
321
|
+
}
|
|
322
|
+
async function j(e, { signal: t, findRelated: n = !0 } = {}) {
|
|
323
|
+
let r = await k(e, t);
|
|
324
|
+
return n && !r.candidates.length && r.canFindRelated && (r.alternatives = await A(r, e, t).catch((e) => {
|
|
325
|
+
if (t?.aborted) throw e;
|
|
326
|
+
return [];
|
|
327
|
+
})), r;
|
|
328
|
+
}
|
|
329
|
+
// src/model-discovery.js
|
|
330
|
+
var M = "https://huggingface.co/models?library=transformers.js&pipeline_tag=text-generation&other=onnx&num_parameters=min:0,max:3B&sort=downloads";
|
|
331
|
+
function N({ version: e, adapter: t, repo: n, revision: r, files: i }) {
|
|
332
|
+
let a = {
|
|
333
|
+
version: e,
|
|
334
|
+
adapter: t,
|
|
335
|
+
repo: n,
|
|
336
|
+
revision: r,
|
|
337
|
+
files: i.map(({ path: e, size: t, sha256: n }) => Object.freeze({
|
|
338
|
+
path: e,
|
|
339
|
+
size: t,
|
|
340
|
+
...n ? { sha256: n } : {}
|
|
341
|
+
}))
|
|
342
|
+
}, o = t === "onnx-chat" ? g(i[0].path).dtype : void 0, s = l[t].task;
|
|
343
|
+
return Object.freeze({
|
|
344
|
+
...a,
|
|
345
|
+
files: Object.freeze(a.files),
|
|
346
|
+
id: S(a),
|
|
347
|
+
name: C(a),
|
|
348
|
+
bytes: w(a),
|
|
349
|
+
task: s,
|
|
350
|
+
variant: o,
|
|
351
|
+
requiresFp16: o === "q4f16" || o === "fp16" || s !== "chat"
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
async function P({ task: e, search: t, maxDownloadBytes: n = 1e400 } = {}) {
|
|
355
|
+
let { default: r } = await import("./model-catalog-D6UCYXpI.js"), i = t?.toLowerCase().trim();
|
|
356
|
+
return r.filter((t) => (!e || l[t.adapter].task === e) && (!i || t.repo.toLowerCase().includes(i)) && w(t) <= n).map(N);
|
|
357
|
+
}
|
|
358
|
+
function F(e) {
|
|
359
|
+
return {
|
|
360
|
+
repo: e.repo,
|
|
361
|
+
revision: e.revision,
|
|
362
|
+
status: e.candidates.length ? "ready" : e.verdict === "Access required" ? "access-required" : "unsupported",
|
|
363
|
+
models: e.candidates.map(N),
|
|
364
|
+
issues: e.issues.slice(),
|
|
365
|
+
alternatives: (e.alternatives ?? []).map(F)
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
async function I(e, { signal: n, findRelated: i = !0 } = {}) {
|
|
369
|
+
let a = "inspectModel";
|
|
370
|
+
r(n, a);
|
|
371
|
+
let o;
|
|
372
|
+
try {
|
|
373
|
+
if (o = typeof e == "string" ? D(e) : void 0, !o) throw Error("Use a public Hugging Face model URL.");
|
|
374
|
+
} catch (e) {
|
|
375
|
+
throw new t("INVALID_MODEL", e.message, {
|
|
376
|
+
operation: a,
|
|
377
|
+
cause: e
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
try {
|
|
381
|
+
return F(await j(o, {
|
|
382
|
+
signal: n,
|
|
383
|
+
findRelated: i
|
|
384
|
+
}));
|
|
385
|
+
} catch (e) {
|
|
386
|
+
r(n, a, o.repo);
|
|
387
|
+
let i = e instanceof TypeError ? "Check your internet connection and retry." : e.message;
|
|
388
|
+
throw new t("HUB_REQUEST_FAILED", `Could not inspect ${o.repo}. ${i}`, {
|
|
389
|
+
operation: a,
|
|
390
|
+
repo: o.repo,
|
|
391
|
+
cause: e
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
// src/model-session.js
|
|
396
|
+
function L(e, n, r, i) {
|
|
397
|
+
if (typeof e != "string" || !e.trim()) throw new t("INVALID_ARGUMENT", `${n} must be a non-empty string.`, {
|
|
398
|
+
operation: r,
|
|
399
|
+
repo: i
|
|
400
|
+
});
|
|
401
|
+
return e.trim();
|
|
402
|
+
}
|
|
403
|
+
function R(e, n) {
|
|
404
|
+
let { task: r, repo: i, adapter: a } = e, o = {
|
|
405
|
+
task: r,
|
|
406
|
+
model: e,
|
|
407
|
+
dispose: n.dispose
|
|
408
|
+
};
|
|
409
|
+
return r === "chat" ? {
|
|
410
|
+
...o,
|
|
411
|
+
async chat(e, { signal: t, onToken: r } = {}) {
|
|
412
|
+
let a = L(e, "Prompt", "chat", i), o = "";
|
|
413
|
+
return n.run("chat", {
|
|
414
|
+
type: "generate",
|
|
415
|
+
prompt: a
|
|
416
|
+
}, t, (e, t) => {
|
|
417
|
+
e.type === "delta" && (o += e.text, r?.(e.text)), e.type === "done" && t(o);
|
|
418
|
+
});
|
|
419
|
+
},
|
|
420
|
+
reset({ signal: e } = {}) {
|
|
421
|
+
return n.run("reset", { type: "reset" }, e, (e, t) => {
|
|
422
|
+
e.type === "reset" && t();
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
} : r === "image" ? {
|
|
426
|
+
...o,
|
|
427
|
+
async generateImage(e, { signal: r, seed: o, onProgress: s } = {}) {
|
|
428
|
+
let c = L(e, "Prompt", "generateImage", i);
|
|
429
|
+
if (o !== void 0 && (a !== "sd-turbo" || !Number.isInteger(o) || o < 0 || o > 0xffffffff)) throw new t("INVALID_ARGUMENT", "SD-Turbo accepts integer seeds from 0 to 4294967295. Janus chooses its own seed.", {
|
|
430
|
+
operation: "generateImage",
|
|
431
|
+
repo: i
|
|
432
|
+
});
|
|
433
|
+
let l = a === "sd-turbo" ? o ?? crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] : void 0;
|
|
434
|
+
return n.run("generateImage", {
|
|
435
|
+
type: "generate",
|
|
436
|
+
prompt: c,
|
|
437
|
+
seed: l
|
|
438
|
+
}, r, (e, t) => {
|
|
439
|
+
if (e.type === "generate-progress" && s?.({
|
|
440
|
+
fraction: e.fraction,
|
|
441
|
+
label: e.label
|
|
442
|
+
}), e.type === "result") {
|
|
443
|
+
let { blob: n, width: r, height: i } = e;
|
|
444
|
+
t({
|
|
445
|
+
blob: n,
|
|
446
|
+
width: r,
|
|
447
|
+
height: i,
|
|
448
|
+
...l === void 0 ? {} : { seed: l }
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
} : {
|
|
454
|
+
...o,
|
|
455
|
+
async classify(e, r, { signal: a, question: o = "Which category best matches this text?", onProgress: s } = {}) {
|
|
456
|
+
let c = "classify", l = Array.isArray(e) && Array.from(e);
|
|
457
|
+
if (!l || !l.every((e) => typeof e == "string" && e.trim())) throw new t("INVALID_ARGUMENT", "Texts must be an array of non-empty strings.", {
|
|
458
|
+
operation: c,
|
|
459
|
+
repo: i
|
|
460
|
+
});
|
|
461
|
+
if (!Array.isArray(r) || r.length < 3 || r.length > 5) throw new t("INVALID_ARGUMENT", "Provide three to five classification choices.", {
|
|
462
|
+
operation: c,
|
|
463
|
+
repo: i
|
|
464
|
+
});
|
|
465
|
+
let u = Array.from(r, (e) => typeof e == "string" ? { label: L(e, "Choice", c, i) } : {
|
|
466
|
+
label: L(e?.label, "Choice label", c, i),
|
|
467
|
+
description: e.description === void 0 ? void 0 : L(e.description, "Choice description", c, i)
|
|
468
|
+
}), d = u.map(({ label: e }) => e);
|
|
469
|
+
if (new Set(d).size !== d.length) throw new t("INVALID_ARGUMENT", "Give each classification choice a distinct label.", {
|
|
470
|
+
operation: c,
|
|
471
|
+
repo: i
|
|
472
|
+
});
|
|
473
|
+
let f = L(o, "Question", c, i), p = [], m = {
|
|
474
|
+
type: "run",
|
|
475
|
+
messages: l,
|
|
476
|
+
choices: u.map(({ label: e, description: t }) => t ? `${e}: ${t}` : e),
|
|
477
|
+
question: f
|
|
478
|
+
};
|
|
479
|
+
return n.run(c, m, a, (e, t) => {
|
|
480
|
+
if (e.type === "batch") {
|
|
481
|
+
for (let t of e.records) p.push({
|
|
482
|
+
index: t.route,
|
|
483
|
+
label: d[t.route],
|
|
484
|
+
scores: t.probabilities,
|
|
485
|
+
truncated: t.truncated
|
|
486
|
+
});
|
|
487
|
+
s?.({
|
|
488
|
+
completed: p.length,
|
|
489
|
+
total: l.length
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
e.type === "done" && t(p);
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
// src/worker-factories.js
|
|
498
|
+
var z = () => import("./image.worker-DCCSYqzK.js"), B = {
|
|
499
|
+
"litert-chat": () => import("./inference.worker-CuwWqHQs.js"),
|
|
500
|
+
"onnx-chat": () => import("./onnx-chat.worker-BkdwoJoF.js"),
|
|
501
|
+
"laya-choice": () => import("./laya.worker-Dku9wD9_.js"),
|
|
502
|
+
"janus-image": z,
|
|
503
|
+
"sd-turbo": z
|
|
504
|
+
};
|
|
505
|
+
// src/worker-transport.js
|
|
506
|
+
function V(e, r) {
|
|
507
|
+
let i, a;
|
|
508
|
+
function o(t) {
|
|
509
|
+
a || (a = t, e.terminate(), i?.reject(t));
|
|
510
|
+
}
|
|
511
|
+
function s(e, n) {
|
|
512
|
+
o(new t("WORKER_FAILED", e, {
|
|
513
|
+
operation: i?.operation,
|
|
514
|
+
repo: r,
|
|
515
|
+
cause: n
|
|
516
|
+
}));
|
|
517
|
+
}
|
|
518
|
+
return e.addEventListener("error", (e) => {
|
|
519
|
+
e.preventDefault(), s(e.message || "The browser could not run the model worker. Check worker CSP permissions.", e.error);
|
|
520
|
+
}), e.addEventListener("messageerror", () => s("The model worker sent an unreadable response.")), e.addEventListener("message", ({ data: e }) => {
|
|
521
|
+
let n = i;
|
|
522
|
+
if (e.type === "error" && !n) s(e.message);
|
|
523
|
+
else if (n) {
|
|
524
|
+
if (e.type === "error" || e.type === "generation-error") {
|
|
525
|
+
let i = new t(n.operation === "openModel" ? "LOAD_FAILED" : "INFERENCE_FAILED", e.message, {
|
|
526
|
+
operation: n.operation,
|
|
527
|
+
repo: r
|
|
528
|
+
});
|
|
529
|
+
n.operation === "openModel" || e.fatal ? o(i) : n.reject(i);
|
|
530
|
+
} else try {
|
|
531
|
+
n.receive(e, n.resolve);
|
|
532
|
+
} catch (e) {
|
|
533
|
+
o(new t("CALLBACK_FAILED", "A model callback threw an error.", {
|
|
534
|
+
operation: n.operation,
|
|
535
|
+
repo: r,
|
|
536
|
+
cause: e
|
|
537
|
+
}));
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}), {
|
|
541
|
+
run(s, c, l, u) {
|
|
542
|
+
return a ? Promise.reject(new t("DISPOSED", "This model is closed. Call openModel again.", {
|
|
543
|
+
operation: s,
|
|
544
|
+
repo: r,
|
|
545
|
+
cause: a
|
|
546
|
+
})) : l?.aborted ? Promise.reject(n(l, s, r)) : i ? Promise.reject(new t("BUSY", "Wait for the current model operation to finish.", {
|
|
547
|
+
operation: s,
|
|
548
|
+
repo: r
|
|
549
|
+
})) : new Promise((a, d) => {
|
|
550
|
+
let f = () => o(n(l, s, r));
|
|
551
|
+
function p(e, t) {
|
|
552
|
+
i === m && (l?.removeEventListener("abort", f), i = void 0, e(t));
|
|
553
|
+
}
|
|
554
|
+
let m = {
|
|
555
|
+
operation: s,
|
|
556
|
+
receive: u,
|
|
557
|
+
resolve: (e) => p(a, e),
|
|
558
|
+
reject: (e) => p(d, e)
|
|
559
|
+
};
|
|
560
|
+
i = m;
|
|
561
|
+
try {
|
|
562
|
+
l?.addEventListener("abort", f, { once: !0 }), e.postMessage(c);
|
|
563
|
+
} catch (e) {
|
|
564
|
+
o(new t("WORKER_FAILED", "Could not send a request to the model worker.", {
|
|
565
|
+
operation: s,
|
|
566
|
+
repo: r,
|
|
567
|
+
cause: e
|
|
568
|
+
}));
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
},
|
|
572
|
+
dispose() {
|
|
573
|
+
o(new t("DISPOSED", "The model was disposed.", {
|
|
574
|
+
operation: i?.operation,
|
|
575
|
+
repo: r
|
|
576
|
+
}));
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
// src/index.js
|
|
581
|
+
async function H(e, n, r) {
|
|
582
|
+
let i = "openModel";
|
|
583
|
+
if (typeof e == "string") {
|
|
584
|
+
let a = await I(e, {
|
|
585
|
+
signal: r,
|
|
586
|
+
findRelated: !1
|
|
587
|
+
}), o = a.models.find((e) => !n || e.task === n);
|
|
588
|
+
if (o) return o;
|
|
589
|
+
let s = a.status === "access-required" ? "ACCESS_REQUIRED" : "UNSUPPORTED_MODEL", c = n ? `Choose a compatible ${n} export.` : "Call inspectModel to find related browser exports.";
|
|
590
|
+
throw new t(s, [a.issues[0], c].filter(Boolean).join(" "), {
|
|
591
|
+
operation: i,
|
|
592
|
+
repo: a.repo
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
if (!x(e)) throw new t("INVALID_MODEL", "Pass a model descriptor from listModels or inspectModel, or a Hugging Face URL.", { operation: i });
|
|
596
|
+
let a = N(e);
|
|
597
|
+
if (n && a.task !== n) throw new t("UNSUPPORTED_MODEL", `This export supports ${a.task}. Choose a ${n} export.`, {
|
|
598
|
+
operation: i,
|
|
599
|
+
repo: a.repo
|
|
600
|
+
});
|
|
601
|
+
return a;
|
|
602
|
+
}
|
|
603
|
+
async function U(n) {
|
|
604
|
+
let r = globalThis.navigator, i = await e(), a = {
|
|
605
|
+
operation: "openModel",
|
|
606
|
+
repo: n.repo
|
|
607
|
+
};
|
|
608
|
+
if (!i.webgpu || typeof Worker != "function" || typeof WebAssembly > "u" || !globalThis.isSecureContext) throw new t("DEVICE_UNSUPPORTED", "Use a browser with WebGPU, WebAssembly, and workers over HTTPS or localhost.", a);
|
|
609
|
+
if (n.requiresFp16 && !i.shaderFp16) throw new t("DEVICE_UNSUPPORTED", "This export requires WebGPU FP16 shaders. Try a device with shader-f16 support.", a);
|
|
610
|
+
if (n.adapter === "litert-chat" && (!r.storage?.getDirectory || !r.locks)) throw new t("DEVICE_UNSUPPORTED", "LiteRT-LM needs the browser’s private file system and Web Locks APIs.", a);
|
|
611
|
+
if (n.task === "image" && typeof OffscreenCanvas > "u") throw new t("DEVICE_UNSUPPORTED", "Image generation needs OffscreenCanvas.", a);
|
|
612
|
+
}
|
|
613
|
+
async function W(e, { task: n, signal: i, onProgress: a } = {}) {
|
|
614
|
+
let o = "openModel";
|
|
615
|
+
r(i, o);
|
|
616
|
+
let s = await H(e, n, i);
|
|
617
|
+
await U(s), r(i, o, s.repo);
|
|
618
|
+
let c;
|
|
619
|
+
try {
|
|
620
|
+
let { default: e } = await B[s.adapter]();
|
|
621
|
+
r(i, o, s.repo), c = new e({ name: s.adapter });
|
|
622
|
+
} catch (e) {
|
|
623
|
+
throw r(i, o, s.repo), new t("WORKER_FAILED", "Could not start the model worker. Check that this site allows blob workers.", {
|
|
624
|
+
operation: o,
|
|
625
|
+
repo: s.repo,
|
|
626
|
+
cause: e
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
let l = V(c, s.repo), u = 0;
|
|
630
|
+
try {
|
|
631
|
+
return await l.run(o, {
|
|
632
|
+
type: "load",
|
|
633
|
+
registration: s
|
|
634
|
+
}, i, (e, t) => {
|
|
635
|
+
(e.type === "load-progress" || e.type === "progress") && (Number.isFinite(e.loaded) && (u = Math.max(u, Math.min(e.loaded, s.bytes))), a?.({
|
|
636
|
+
stage: "download",
|
|
637
|
+
loadedBytes: u,
|
|
638
|
+
totalBytes: s.bytes
|
|
639
|
+
})), (e.type === "initializing" || e.type === "preparing") && a?.({
|
|
640
|
+
stage: "initialize",
|
|
641
|
+
loadedBytes: s.bytes,
|
|
642
|
+
totalBytes: s.bytes
|
|
643
|
+
}), e.type === "ready" && (a?.({
|
|
644
|
+
stage: "ready",
|
|
645
|
+
loadedBytes: s.bytes,
|
|
646
|
+
totalBytes: s.bytes
|
|
647
|
+
}), t());
|
|
648
|
+
}), R(s, l);
|
|
649
|
+
} catch (e) {
|
|
650
|
+
throw l.dispose(), e;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
export { M as HUGGING_FACE_BROWSE_URL, t as ModelError, e as getDeviceInfo, I as inspectModel, P as listModels, W as openModel };
|