tempest-react-sdk 0.32.0 → 0.33.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/dist/tabular/compact.cjs +2 -0
- package/dist/tabular/compact.cjs.map +1 -0
- package/dist/tabular/compact.js +121 -0
- package/dist/tabular/compact.js.map +1 -0
- package/dist/tabular/exceptions.cjs +1 -1
- package/dist/tabular/exceptions.cjs.map +1 -1
- package/dist/tabular/exceptions.js +7 -3
- package/dist/tabular/exceptions.js.map +1 -1
- package/dist/tabular/manifest.cjs +1 -1
- package/dist/tabular/manifest.cjs.map +1 -1
- package/dist/tabular/manifest.js +29 -18
- package/dist/tabular/manifest.js.map +1 -1
- package/dist/tabular.cjs +1 -1
- package/dist/tabular.d.ts +629 -450
- package/dist/tabular.js +7 -6
- package/package.json +1 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./exceptions.cjs");var t=`TMC1`,n=1,r=class n{header;arrays;info;constructor(e,t,n){this.header=e,this.arrays=t,this.info=n}static async create(r,a){let o=await i(r,a),s=new Uint8Array(o);if(String.fromCharCode(...s.subarray(0,4))!==t)throw new e.CompactFormatError(`This is not a compact model file: it does not start with "${t}". A .onnx file goes through TabularPredictor instead.`);let c=new DataView(o).getUint32(4,!0),l=JSON.parse(new TextDecoder().decode(s.subarray(8,8+c)));if(l.schema_version>1)throw new e.CompactFormatError(`This file uses compact layout ${l.schema_version}, and this SDK understands 1. Upgrade tempest-react-sdk before serving it.`);let u={},d=8+c;for(let e of l.sections)u[e.name]=e.dtype===`float32`?new Float32Array(o,d,e.length):new Int32Array(o,d,e.length),d+=e.length*4;return new n(l,u,{kind:l.kind,classes:l.classes,numFeatures:l.n_features,featureNames:l.feature_names,numTrees:l.n_trees??0,isClassifier:l.task===`classification`,estimator:l.estimator})}async predict(e){let t=a(e,this.header.n_features),n=performance.now(),r=[];for(let n of e){let e=this.preprocess(n,t);r.push(this.header.kind===`linear`?this.linearScores(e):this.treeScores(e))}let{labels:i,probabilities:o}=this.finish(r);return{labels:i,probabilities:o,numRows:e.length,ms:performance.now()-n}}async dispose(){}preprocess(e,t){let n=this.header.preprocess;if(n===null)return e;let r=Array(t);for(let i=0;i<t;i+=1)r[i]=(e[i]-n.offset[i])/n.scale[i];return r}linearScores(e){let t=this.arrays.coef,n=this.arrays.intercept,r=this.header.n_features,i=this.header.n_outputs,a=Array(i);for(let o=0;o<i;o+=1){let i=n[o],s=o*r;for(let n=0;n<r;n+=1)i+=t[s+n]*e[n];a[o]=i}return a}treeScores(e){let t=this.arrays.node_feature,n=this.arrays.node_threshold,r=this.arrays.node_left,i=this.arrays.node_right,a=this.arrays.leaf_value,o=this.arrays.tree_offset,s=this.header.n_outputs,c=o.length-1,l=Array(s).fill(0);for(let u=0;u<c;u+=1){let c=o[u],d=t[c];for(;d>=0;)c=e[d]<=n[c]?r[c]:i[c],d=t[c];let f=(-1-d)*s;for(let e=0;e<s;e+=1)l[e]+=a[f+e]}for(let e=0;e<s;e+=1)l[e]=l[e]/c;return l}finish(e){let t=this.header.link,n=this.header.classes;if(t===`identity`)return{labels:e.map(e=>e[0]),probabilities:[]};let r=e.map(e=>{if(t===`sigmoid`){let t=1/(1+Math.exp(-e[0]));return[1-t,t]}if(t===`softmax`){let t=Math.max(...e),n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}let n=e.reduce((e,t)=>e+t,0);return n===0?[...e]:e.map(e=>e/n)}),i=this.header.class_type!==`str`;return{labels:r.map(e=>{let t=0;for(let n=1;n<e.length;n+=1)e[n]>e[t]&&(t=n);let r=n[t];return r===void 0?t:i?Number(r):r}),probabilities:r}}};async function i(t,n){if(typeof t==`string`){let r;try{r=await fetch(t,n)}catch(n){throw new e.ModelFetchError(`Could not download the model: ${t}`,{cause:n})}if(!r.ok)throw new e.ModelFetchError(`Could not download the model: ${r.status} ${r.statusText}`);return await r.arrayBuffer()}return t instanceof Uint8Array?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t}function a(t,n){if(!Array.isArray(t)||t.length===0)throw new e.FeatureShapeError(`predict() needs at least one row, shaped [[f1, f2, ...]].`);let r=t[0]?.length??0,i=t.findIndex(e=>e.length!==r);if(i!==-1)throw new e.FeatureShapeError(`All rows must have the same width; row ${i} has ${t[i]?.length} values, expected ${r}.`);if(r!==n)throw new e.FeatureShapeError(`The model expects ${n} features per row, got ${r}.`);return r}exports.CompactPredictor=r,exports.SUPPORTED_COMPACT_SCHEMA=n;
|
|
2
|
+
//# sourceMappingURL=compact.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compact.cjs","names":[],"sources":["../../src/tabular/compact.ts"],"sourcesContent":["/**\n * Running a model with no inference runtime at all.\n *\n * ONNX in the browser costs a **25.6 MB WebAssembly runtime** (6.0 MB\n * gzipped) before the first prediction, while the model itself is a few\n * hundred kilobytes. For an app whose only model is tabular, that runtime\n * *is* the download — so this reader replaces it with 1.49 KB of\n * arithmetic (measured, brotli).\n *\n * A linear model is a dot product. A tree is a chain of comparisons. That\n * is the whole implementation; there is nothing here that a WebAssembly\n * kernel would do better at this size.\n *\n * The file it reads (`.tmc`, magic `TMC1`) is written by\n * `tempest-fastapi-sdk`'s `export_sklearn_to_compact`, which verifies the\n * bytes against scikit-learn's own predictions and refuses to write a file\n * that disagrees. **It is data, not code**: no `eval`, no generated\n * JavaScript, nothing a strict CSP forbids.\n *\n * The trade against {@link TabularPredictor}: ONNX covers every estimator,\n * this covers linear models and tree ensembles. Pick by what your app\n * already ships — a page that loads ONNX for vision pays nothing extra for\n * tabular ONNX.\n */\n\nimport { CompactFormatError, FeatureShapeError, ModelFetchError } from \"./exceptions\";\nimport type { FeatureRow, PredictedLabel, TabularPrediction } from \"./types\";\n\n/** Magic bytes opening every compact file. */\nconst MAGIC = \"TMC1\";\n\n/** Layout version this reader understands. */\nexport const SUPPORTED_COMPACT_SCHEMA = 1;\n\n/** What the file holds. */\nexport type CompactKind = \"linear\" | \"tree_ensemble\";\n\n/** How raw scores become probabilities. */\ntype CompactLink = \"softmax\" | \"sigmoid\" | \"normalize\" | \"identity\";\n\n/** One array stored after the header. */\ninterface CompactSection {\n readonly name: string;\n readonly dtype: \"float32\" | \"int32\";\n readonly length: number;\n}\n\n/** The parsed header. */\ninterface CompactHeader {\n readonly schema_version: number;\n readonly kind: CompactKind;\n readonly task: \"classification\" | \"regression\";\n readonly link: CompactLink;\n readonly classes: readonly string[];\n /** How scikit-learn typed those labels: ``int``, ``float`` or ``str``. */\n readonly class_type?: \"int\" | \"float\" | \"str\";\n readonly n_features: number;\n readonly n_outputs: number;\n readonly n_trees?: number;\n readonly estimator: string;\n readonly feature_names: readonly string[];\n readonly preprocess: { readonly offset: number[]; readonly scale: number[] } | null;\n readonly sections: readonly CompactSection[];\n}\n\n/** What a loaded compact model is. */\nexport interface CompactPredictorInfo {\n /** Which reader path the file uses. */\n readonly kind: CompactKind;\n /** Class labels in score-column order; empty for a regressor. */\n readonly classes: readonly string[];\n /** Values expected per row. */\n readonly numFeatures: number;\n /** Column order recorded at training time, when the export had one. */\n readonly featureNames: readonly string[];\n /** Trees in the ensemble; `0` for a linear model. */\n readonly numTrees: number;\n /** Whether the model produces class scores. */\n readonly isClassifier: boolean;\n /** Class name of the exported estimator. */\n readonly estimator: string;\n}\n\n/**\n * A compact model, loaded and ready to answer.\n *\n * @example\n * ```ts\n * const predictor = await CompactPredictor.create(\"/models/risk.tmc\");\n * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);\n * ```\n */\nexport class CompactPredictor {\n private constructor(\n private readonly header: CompactHeader,\n private readonly arrays: Record<string, Float32Array | Int32Array>,\n /** What is loaded. */\n public readonly info: CompactPredictorInfo,\n ) {}\n\n /**\n * Load a `.tmc` file.\n *\n * @param source A URL, or the bytes when the app already has them.\n * @param requestInit `fetch` options, when `source` is a URL.\n * @returns The loaded predictor.\n * @throws {@link ModelFetchError} when a URL cannot be read.\n * @throws {@link CompactFormatError} when the bytes are not a compact\n * model, or use a layout newer than this reader.\n */\n static async create(\n source: string | ArrayBuffer | Uint8Array,\n requestInit?: RequestInit,\n ): Promise<CompactPredictor> {\n const buffer = await toBuffer(source, requestInit);\n const bytes = new Uint8Array(buffer);\n\n if (String.fromCharCode(...bytes.subarray(0, 4)) !== MAGIC) {\n throw new CompactFormatError(\n \"This is not a compact model file: it does not start with \" +\n `\"${MAGIC}\". A .onnx file goes through TabularPredictor instead.`,\n );\n }\n\n const view = new DataView(buffer);\n const headerLength = view.getUint32(4, true);\n const header = JSON.parse(\n new TextDecoder().decode(bytes.subarray(8, 8 + headerLength)),\n ) as CompactHeader;\n\n if (header.schema_version > SUPPORTED_COMPACT_SCHEMA) {\n throw new CompactFormatError(\n `This file uses compact layout ${header.schema_version}, and this ` +\n `SDK understands ${SUPPORTED_COMPACT_SCHEMA}. Upgrade ` +\n \"tempest-react-sdk before serving it.\",\n );\n }\n\n const arrays: Record<string, Float32Array | Int32Array> = {};\n let cursor = 8 + headerLength;\n for (const section of header.sections) {\n arrays[section.name] =\n section.dtype === \"float32\"\n ? new Float32Array(buffer, cursor, section.length)\n : new Int32Array(buffer, cursor, section.length);\n cursor += section.length * 4;\n }\n\n return new CompactPredictor(header, arrays, {\n kind: header.kind,\n classes: header.classes,\n numFeatures: header.n_features,\n featureNames: header.feature_names,\n numTrees: header.n_trees ?? 0,\n isClassifier: header.task === \"classification\",\n estimator: header.estimator,\n });\n }\n\n /**\n * Predict for a batch of rows.\n *\n * @param rows One array of feature values per row, in training column\n * order. A single row is still wrapped: `[[...]]`.\n * @returns Labels, class scores when the model is a classifier, and the\n * call's duration.\n * @throws {@link FeatureShapeError} when the batch is empty, ragged, or\n * the wrong width.\n */\n async predict(rows: readonly FeatureRow[]): Promise<TabularPrediction> {\n const width = validateRows(rows, this.header.n_features);\n const started = performance.now();\n\n const scores: number[][] = [];\n for (const row of rows) {\n const prepared = this.preprocess(row, width);\n scores.push(\n this.header.kind === \"linear\"\n ? this.linearScores(prepared)\n : this.treeScores(prepared),\n );\n }\n\n const { labels, probabilities } = this.finish(scores);\n return {\n labels,\n probabilities,\n numRows: rows.length,\n ms: performance.now() - started,\n };\n }\n\n /** Releasing nothing, so callers can swap predictors without branching. */\n async dispose(): Promise<void> {\n /* no runtime, nothing to release */\n }\n\n /**\n * Apply the folded scaler, when the export had one.\n *\n * @param row The raw feature values.\n * @param width How many there are.\n * @returns The values the model was trained on.\n */\n private preprocess(row: FeatureRow, width: number): number[] {\n const preprocess = this.header.preprocess;\n if (preprocess === null) return row as number[];\n const scaled = new Array<number>(width);\n for (let index = 0; index < width; index += 1) {\n scaled[index] =\n ((row[index] as number) - (preprocess.offset[index] as number)) /\n (preprocess.scale[index] as number);\n }\n return scaled;\n }\n\n /**\n * Score one row against the coefficient matrix.\n *\n * @param row The prepared feature values.\n * @returns One raw score per output.\n */\n private linearScores(row: readonly number[]): number[] {\n const coef = this.arrays.coef as Float32Array;\n const intercept = this.arrays.intercept as Float32Array;\n const features = this.header.n_features;\n const outputs = this.header.n_outputs;\n\n const scores = new Array<number>(outputs);\n for (let output = 0; output < outputs; output += 1) {\n let total = intercept[output] as number;\n const base = output * features;\n for (let index = 0; index < features; index += 1) {\n total += (coef[base + index] as number) * (row[index] as number);\n }\n scores[output] = total;\n }\n return scores;\n }\n\n /**\n * Walk every tree and average what the leaves hold.\n *\n * A leaf is marked by a negative `feature` entry, which also carries\n * its slot in the value array — so the walk needs no second lookup and\n * the file stores values only for leaves.\n *\n * @param row The prepared feature values.\n * @returns One averaged score per output.\n */\n private treeScores(row: readonly number[]): number[] {\n const feature = this.arrays.node_feature as Int32Array;\n const threshold = this.arrays.node_threshold as Float32Array;\n const left = this.arrays.node_left as Int32Array;\n const right = this.arrays.node_right as Int32Array;\n const leaf = this.arrays.leaf_value as Float32Array;\n const offsets = this.arrays.tree_offset as Int32Array;\n const outputs = this.header.n_outputs;\n const trees = offsets.length - 1;\n\n const totals = new Array<number>(outputs).fill(0);\n for (let tree = 0; tree < trees; tree += 1) {\n let node = offsets[tree] as number;\n let column = feature[node] as number;\n while (column >= 0) {\n node =\n (row[column] as number) <= (threshold[node] as number)\n ? (left[node] as number)\n : (right[node] as number);\n column = feature[node] as number;\n }\n const slot = (-1 - column) * outputs;\n for (let output = 0; output < outputs; output += 1) {\n totals[output] += leaf[slot + output] as number;\n }\n }\n for (let output = 0; output < outputs; output += 1) {\n totals[output] = (totals[output] as number) / trees;\n }\n return totals;\n }\n\n /**\n * Turn raw scores into labels and probabilities.\n *\n * @param scores One score array per row.\n * @returns Labels and probabilities in the shape the ONNX route uses,\n * so an app can swap runtimes without touching its own code. That\n * includes the label's **type**: an integer class comes back as a\n * number here exactly as ONNX returns it, because two routes over one\n * model that disagree on `0` versus `\"0\"` break the day someone\n * switches.\n */\n private finish(scores: readonly number[][]): {\n labels: PredictedLabel[];\n probabilities: number[][];\n } {\n const link = this.header.link;\n const classes = this.header.classes;\n\n if (link === \"identity\") {\n return { labels: scores.map((row) => row[0] as number), probabilities: [] };\n }\n\n const probabilities = scores.map((row) => {\n if (link === \"sigmoid\") {\n const positive = 1 / (1 + Math.exp(-(row[0] as number)));\n return [1 - positive, positive];\n }\n if (link === \"softmax\") {\n const highest = Math.max(...row);\n const exponentiated = row.map((value) => Math.exp(value - highest));\n const total = exponentiated.reduce((sum, value) => sum + value, 0);\n return exponentiated.map((value) => value / total);\n }\n const total = row.reduce((sum, value) => sum + value, 0);\n return total === 0 ? [...row] : row.map((value) => value / total);\n });\n\n const numeric = this.header.class_type !== \"str\";\n const labels = probabilities.map((row) => {\n let best = 0;\n for (let index = 1; index < row.length; index += 1) {\n if ((row[index] as number) > (row[best] as number)) best = index;\n }\n const label = classes[best];\n if (label === undefined) return best;\n return numeric ? Number(label) : label;\n });\n\n return { labels, probabilities };\n }\n}\n\n/**\n * Read a source into an `ArrayBuffer`.\n *\n * @param source A URL or the bytes.\n * @param requestInit `fetch` options.\n * @returns The bytes.\n * @throws {@link ModelFetchError} when the URL cannot be read.\n */\nasync function toBuffer(\n source: string | ArrayBuffer | Uint8Array,\n requestInit?: RequestInit,\n): Promise<ArrayBuffer> {\n if (typeof source === \"string\") {\n let response: Response;\n try {\n response = await fetch(source, requestInit);\n } catch (error) {\n throw new ModelFetchError(`Could not download the model: ${source}`, {\n cause: error,\n });\n }\n if (!response.ok) {\n throw new ModelFetchError(\n `Could not download the model: ${response.status} ${response.statusText}`,\n );\n }\n return await response.arrayBuffer();\n }\n if (source instanceof Uint8Array) {\n return source.buffer.slice(\n source.byteOffset,\n source.byteOffset + source.byteLength,\n ) as ArrayBuffer;\n }\n return source;\n}\n\n/**\n * Check a batch before predicting on it.\n *\n * @param rows The batch.\n * @param expected Features the model wants per row.\n * @returns The batch width.\n * @throws {@link FeatureShapeError} when the batch cannot be predicted on.\n */\nfunction validateRows(rows: readonly FeatureRow[], expected: number): number {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new FeatureShapeError(\"predict() needs at least one row, shaped [[f1, f2, ...]].\");\n }\n const width = rows[0]?.length ?? 0;\n const ragged = rows.findIndex((row) => row.length !== width);\n if (ragged !== -1) {\n throw new FeatureShapeError(\n `All rows must have the same width; row ${ragged} has ` +\n `${rows[ragged]?.length} values, expected ${width}.`,\n );\n }\n if (width !== expected) {\n throw new FeatureShapeError(\n `The model expects ${expected} features per row, got ${width}.`,\n );\n }\n return width;\n}\n"],"mappings":"oCA6BA,IAAM,EAAQ,OAGD,EAA2B,EA4D3B,EAAb,MAAa,CAAiB,CAEL,OACA,OAED,KAJpB,YACI,EACA,EAEA,EACF,CAJmB,KAAA,OAAA,EACA,KAAA,OAAA,EAED,KAAA,KAAA,CACjB,CAYH,aAAa,OACT,EACA,EACyB,CACzB,IAAM,EAAS,MAAM,EAAS,EAAQ,CAAW,EAC3C,EAAQ,IAAI,WAAW,CAAM,EAEnC,GAAI,OAAO,aAAa,GAAG,EAAM,SAAS,EAAG,CAAC,CAAC,IAAM,EACjD,MAAM,IAAI,EAAA,mBACN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CACA,GAAI,CAAC,EAAS,GACV,MAAM,IAAI,EAAA,gBACN,iCAAiC,EAAS,OAAO,GAAG,EAAS,YACjE,EAEJ,OAAO,MAAM,EAAS,YAAY,CACtC,CAOA,OANI,aAAkB,WACX,EAAO,OAAO,MACjB,EAAO,WACP,EAAO,WAAa,EAAO,UAC/B,EAEG,CACX,CAUA,SAAS,EAAa,EAA6B,EAA0B,CACzE,GAAI,CAAC,MAAM,QAAQ,CAAI,GAAK,EAAK,SAAW,EACxC,MAAM,IAAI,EAAA,kBAAkB,2DAA2D,EAE3F,IAAM,EAAQ,EAAK,EAAE,EAAE,QAAU,EAC3B,EAAS,EAAK,UAAW,GAAQ,EAAI,SAAW,CAAK,EAC3D,GAAI,IAAW,GACX,MAAM,IAAI,EAAA,kBACN,0CAA0C,EAAO,OAC1C,EAAK,EAAO,EAAE,OAAO,oBAAoB,EAAM,EAC1D,EAEJ,GAAI,IAAU,EACV,MAAM,IAAI,EAAA,kBACN,qBAAqB,EAAS,yBAAyB,EAAM,EACjE,EAEJ,OAAO,CACX"}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { CompactFormatError as e, FeatureShapeError as t, ModelFetchError as n } from "./exceptions.js";
|
|
2
|
+
//#region src/tabular/compact.ts
|
|
3
|
+
var r = "TMC1", i = 1, a = class t {
|
|
4
|
+
header;
|
|
5
|
+
arrays;
|
|
6
|
+
info;
|
|
7
|
+
constructor(e, t, n) {
|
|
8
|
+
this.header = e, this.arrays = t, this.info = n;
|
|
9
|
+
}
|
|
10
|
+
static async create(n, i) {
|
|
11
|
+
let a = await o(n, i), s = new Uint8Array(a);
|
|
12
|
+
if (String.fromCharCode(...s.subarray(0, 4)) !== r) throw new e(`This is not a compact model file: it does not start with "${r}". A .onnx file goes through TabularPredictor instead.`);
|
|
13
|
+
let c = new DataView(a).getUint32(4, !0), l = JSON.parse(new TextDecoder().decode(s.subarray(8, 8 + c)));
|
|
14
|
+
if (l.schema_version > 1) throw new e(`This file uses compact layout ${l.schema_version}, and this SDK understands 1. Upgrade tempest-react-sdk before serving it.`);
|
|
15
|
+
let u = {}, d = 8 + c;
|
|
16
|
+
for (let e of l.sections) u[e.name] = e.dtype === "float32" ? new Float32Array(a, d, e.length) : new Int32Array(a, d, e.length), d += e.length * 4;
|
|
17
|
+
return new t(l, u, {
|
|
18
|
+
kind: l.kind,
|
|
19
|
+
classes: l.classes,
|
|
20
|
+
numFeatures: l.n_features,
|
|
21
|
+
featureNames: l.feature_names,
|
|
22
|
+
numTrees: l.n_trees ?? 0,
|
|
23
|
+
isClassifier: l.task === "classification",
|
|
24
|
+
estimator: l.estimator
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
async predict(e) {
|
|
28
|
+
let t = s(e, this.header.n_features), n = performance.now(), r = [];
|
|
29
|
+
for (let n of e) {
|
|
30
|
+
let e = this.preprocess(n, t);
|
|
31
|
+
r.push(this.header.kind === "linear" ? this.linearScores(e) : this.treeScores(e));
|
|
32
|
+
}
|
|
33
|
+
let { labels: i, probabilities: a } = this.finish(r);
|
|
34
|
+
return {
|
|
35
|
+
labels: i,
|
|
36
|
+
probabilities: a,
|
|
37
|
+
numRows: e.length,
|
|
38
|
+
ms: performance.now() - n
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
async dispose() {}
|
|
42
|
+
preprocess(e, t) {
|
|
43
|
+
let n = this.header.preprocess;
|
|
44
|
+
if (n === null) return e;
|
|
45
|
+
let r = Array(t);
|
|
46
|
+
for (let i = 0; i < t; i += 1) r[i] = (e[i] - n.offset[i]) / n.scale[i];
|
|
47
|
+
return r;
|
|
48
|
+
}
|
|
49
|
+
linearScores(e) {
|
|
50
|
+
let t = this.arrays.coef, n = this.arrays.intercept, r = this.header.n_features, i = this.header.n_outputs, a = Array(i);
|
|
51
|
+
for (let o = 0; o < i; o += 1) {
|
|
52
|
+
let i = n[o], s = o * r;
|
|
53
|
+
for (let n = 0; n < r; n += 1) i += t[s + n] * e[n];
|
|
54
|
+
a[o] = i;
|
|
55
|
+
}
|
|
56
|
+
return a;
|
|
57
|
+
}
|
|
58
|
+
treeScores(e) {
|
|
59
|
+
let t = this.arrays.node_feature, n = this.arrays.node_threshold, r = this.arrays.node_left, i = this.arrays.node_right, a = this.arrays.leaf_value, o = this.arrays.tree_offset, s = this.header.n_outputs, c = o.length - 1, l = Array(s).fill(0);
|
|
60
|
+
for (let u = 0; u < c; u += 1) {
|
|
61
|
+
let c = o[u], d = t[c];
|
|
62
|
+
for (; d >= 0;) c = e[d] <= n[c] ? r[c] : i[c], d = t[c];
|
|
63
|
+
let f = (-1 - d) * s;
|
|
64
|
+
for (let e = 0; e < s; e += 1) l[e] += a[f + e];
|
|
65
|
+
}
|
|
66
|
+
for (let e = 0; e < s; e += 1) l[e] = l[e] / c;
|
|
67
|
+
return l;
|
|
68
|
+
}
|
|
69
|
+
finish(e) {
|
|
70
|
+
let t = this.header.link, n = this.header.classes;
|
|
71
|
+
if (t === "identity") return {
|
|
72
|
+
labels: e.map((e) => e[0]),
|
|
73
|
+
probabilities: []
|
|
74
|
+
};
|
|
75
|
+
let r = e.map((e) => {
|
|
76
|
+
if (t === "sigmoid") {
|
|
77
|
+
let t = 1 / (1 + Math.exp(-e[0]));
|
|
78
|
+
return [1 - t, t];
|
|
79
|
+
}
|
|
80
|
+
if (t === "softmax") {
|
|
81
|
+
let t = Math.max(...e), n = e.map((e) => Math.exp(e - t)), r = n.reduce((e, t) => e + t, 0);
|
|
82
|
+
return n.map((e) => e / r);
|
|
83
|
+
}
|
|
84
|
+
let n = e.reduce((e, t) => e + t, 0);
|
|
85
|
+
return n === 0 ? [...e] : e.map((e) => e / n);
|
|
86
|
+
}), i = this.header.class_type !== "str";
|
|
87
|
+
return {
|
|
88
|
+
labels: r.map((e) => {
|
|
89
|
+
let t = 0;
|
|
90
|
+
for (let n = 1; n < e.length; n += 1) e[n] > e[t] && (t = n);
|
|
91
|
+
let r = n[t];
|
|
92
|
+
return r === void 0 ? t : i ? Number(r) : r;
|
|
93
|
+
}),
|
|
94
|
+
probabilities: r
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
async function o(e, t) {
|
|
99
|
+
if (typeof e == "string") {
|
|
100
|
+
let r;
|
|
101
|
+
try {
|
|
102
|
+
r = await fetch(e, t);
|
|
103
|
+
} catch (t) {
|
|
104
|
+
throw new n(`Could not download the model: ${e}`, { cause: t });
|
|
105
|
+
}
|
|
106
|
+
if (!r.ok) throw new n(`Could not download the model: ${r.status} ${r.statusText}`);
|
|
107
|
+
return await r.arrayBuffer();
|
|
108
|
+
}
|
|
109
|
+
return e instanceof Uint8Array ? e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength) : e;
|
|
110
|
+
}
|
|
111
|
+
function s(e, n) {
|
|
112
|
+
if (!Array.isArray(e) || e.length === 0) throw new t("predict() needs at least one row, shaped [[f1, f2, ...]].");
|
|
113
|
+
let r = e[0]?.length ?? 0, i = e.findIndex((e) => e.length !== r);
|
|
114
|
+
if (i !== -1) throw new t(`All rows must have the same width; row ${i} has ${e[i]?.length} values, expected ${r}.`);
|
|
115
|
+
if (r !== n) throw new t(`The model expects ${n} features per row, got ${r}.`);
|
|
116
|
+
return r;
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
export { a as CompactPredictor, i as SUPPORTED_COMPACT_SCHEMA };
|
|
120
|
+
|
|
121
|
+
//# sourceMappingURL=compact.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compact.js","names":[],"sources":["../../src/tabular/compact.ts"],"sourcesContent":["/**\n * Running a model with no inference runtime at all.\n *\n * ONNX in the browser costs a **25.6 MB WebAssembly runtime** (6.0 MB\n * gzipped) before the first prediction, while the model itself is a few\n * hundred kilobytes. For an app whose only model is tabular, that runtime\n * *is* the download — so this reader replaces it with 1.49 KB of\n * arithmetic (measured, brotli).\n *\n * A linear model is a dot product. A tree is a chain of comparisons. That\n * is the whole implementation; there is nothing here that a WebAssembly\n * kernel would do better at this size.\n *\n * The file it reads (`.tmc`, magic `TMC1`) is written by\n * `tempest-fastapi-sdk`'s `export_sklearn_to_compact`, which verifies the\n * bytes against scikit-learn's own predictions and refuses to write a file\n * that disagrees. **It is data, not code**: no `eval`, no generated\n * JavaScript, nothing a strict CSP forbids.\n *\n * The trade against {@link TabularPredictor}: ONNX covers every estimator,\n * this covers linear models and tree ensembles. Pick by what your app\n * already ships — a page that loads ONNX for vision pays nothing extra for\n * tabular ONNX.\n */\n\nimport { CompactFormatError, FeatureShapeError, ModelFetchError } from \"./exceptions\";\nimport type { FeatureRow, PredictedLabel, TabularPrediction } from \"./types\";\n\n/** Magic bytes opening every compact file. */\nconst MAGIC = \"TMC1\";\n\n/** Layout version this reader understands. */\nexport const SUPPORTED_COMPACT_SCHEMA = 1;\n\n/** What the file holds. */\nexport type CompactKind = \"linear\" | \"tree_ensemble\";\n\n/** How raw scores become probabilities. */\ntype CompactLink = \"softmax\" | \"sigmoid\" | \"normalize\" | \"identity\";\n\n/** One array stored after the header. */\ninterface CompactSection {\n readonly name: string;\n readonly dtype: \"float32\" | \"int32\";\n readonly length: number;\n}\n\n/** The parsed header. */\ninterface CompactHeader {\n readonly schema_version: number;\n readonly kind: CompactKind;\n readonly task: \"classification\" | \"regression\";\n readonly link: CompactLink;\n readonly classes: readonly string[];\n /** How scikit-learn typed those labels: ``int``, ``float`` or ``str``. */\n readonly class_type?: \"int\" | \"float\" | \"str\";\n readonly n_features: number;\n readonly n_outputs: number;\n readonly n_trees?: number;\n readonly estimator: string;\n readonly feature_names: readonly string[];\n readonly preprocess: { readonly offset: number[]; readonly scale: number[] } | null;\n readonly sections: readonly CompactSection[];\n}\n\n/** What a loaded compact model is. */\nexport interface CompactPredictorInfo {\n /** Which reader path the file uses. */\n readonly kind: CompactKind;\n /** Class labels in score-column order; empty for a regressor. */\n readonly classes: readonly string[];\n /** Values expected per row. */\n readonly numFeatures: number;\n /** Column order recorded at training time, when the export had one. */\n readonly featureNames: readonly string[];\n /** Trees in the ensemble; `0` for a linear model. */\n readonly numTrees: number;\n /** Whether the model produces class scores. */\n readonly isClassifier: boolean;\n /** Class name of the exported estimator. */\n readonly estimator: string;\n}\n\n/**\n * A compact model, loaded and ready to answer.\n *\n * @example\n * ```ts\n * const predictor = await CompactPredictor.create(\"/models/risk.tmc\");\n * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);\n * ```\n */\nexport class CompactPredictor {\n private constructor(\n private readonly header: CompactHeader,\n private readonly arrays: Record<string, Float32Array | Int32Array>,\n /** What is loaded. */\n public readonly info: CompactPredictorInfo,\n ) {}\n\n /**\n * Load a `.tmc` file.\n *\n * @param source A URL, or the bytes when the app already has them.\n * @param requestInit `fetch` options, when `source` is a URL.\n * @returns The loaded predictor.\n * @throws {@link ModelFetchError} when a URL cannot be read.\n * @throws {@link CompactFormatError} when the bytes are not a compact\n * model, or use a layout newer than this reader.\n */\n static async create(\n source: string | ArrayBuffer | Uint8Array,\n requestInit?: RequestInit,\n ): Promise<CompactPredictor> {\n const buffer = await toBuffer(source, requestInit);\n const bytes = new Uint8Array(buffer);\n\n if (String.fromCharCode(...bytes.subarray(0, 4)) !== MAGIC) {\n throw new CompactFormatError(\n \"This is not a compact model file: it does not start with \" +\n `\"${MAGIC}\". A .onnx file goes through TabularPredictor instead.`,\n );\n }\n\n const view = new DataView(buffer);\n const headerLength = view.getUint32(4, true);\n const header = JSON.parse(\n new TextDecoder().decode(bytes.subarray(8, 8 + headerLength)),\n ) as CompactHeader;\n\n if (header.schema_version > SUPPORTED_COMPACT_SCHEMA) {\n throw new CompactFormatError(\n `This file uses compact layout ${header.schema_version}, and this ` +\n `SDK understands ${SUPPORTED_COMPACT_SCHEMA}. Upgrade ` +\n \"tempest-react-sdk before serving it.\",\n );\n }\n\n const arrays: Record<string, Float32Array | Int32Array> = {};\n let cursor = 8 + headerLength;\n for (const section of header.sections) {\n arrays[section.name] =\n section.dtype === \"float32\"\n ? new Float32Array(buffer, cursor, section.length)\n : new Int32Array(buffer, cursor, section.length);\n cursor += section.length * 4;\n }\n\n return new CompactPredictor(header, arrays, {\n kind: header.kind,\n classes: header.classes,\n numFeatures: header.n_features,\n featureNames: header.feature_names,\n numTrees: header.n_trees ?? 0,\n isClassifier: header.task === \"classification\",\n estimator: header.estimator,\n });\n }\n\n /**\n * Predict for a batch of rows.\n *\n * @param rows One array of feature values per row, in training column\n * order. A single row is still wrapped: `[[...]]`.\n * @returns Labels, class scores when the model is a classifier, and the\n * call's duration.\n * @throws {@link FeatureShapeError} when the batch is empty, ragged, or\n * the wrong width.\n */\n async predict(rows: readonly FeatureRow[]): Promise<TabularPrediction> {\n const width = validateRows(rows, this.header.n_features);\n const started = performance.now();\n\n const scores: number[][] = [];\n for (const row of rows) {\n const prepared = this.preprocess(row, width);\n scores.push(\n this.header.kind === \"linear\"\n ? this.linearScores(prepared)\n : this.treeScores(prepared),\n );\n }\n\n const { labels, probabilities } = this.finish(scores);\n return {\n labels,\n probabilities,\n numRows: rows.length,\n ms: performance.now() - started,\n };\n }\n\n /** Releasing nothing, so callers can swap predictors without branching. */\n async dispose(): Promise<void> {\n /* no runtime, nothing to release */\n }\n\n /**\n * Apply the folded scaler, when the export had one.\n *\n * @param row The raw feature values.\n * @param width How many there are.\n * @returns The values the model was trained on.\n */\n private preprocess(row: FeatureRow, width: number): number[] {\n const preprocess = this.header.preprocess;\n if (preprocess === null) return row as number[];\n const scaled = new Array<number>(width);\n for (let index = 0; index < width; index += 1) {\n scaled[index] =\n ((row[index] as number) - (preprocess.offset[index] as number)) /\n (preprocess.scale[index] as number);\n }\n return scaled;\n }\n\n /**\n * Score one row against the coefficient matrix.\n *\n * @param row The prepared feature values.\n * @returns One raw score per output.\n */\n private linearScores(row: readonly number[]): number[] {\n const coef = this.arrays.coef as Float32Array;\n const intercept = this.arrays.intercept as Float32Array;\n const features = this.header.n_features;\n const outputs = this.header.n_outputs;\n\n const scores = new Array<number>(outputs);\n for (let output = 0; output < outputs; output += 1) {\n let total = intercept[output] as number;\n const base = output * features;\n for (let index = 0; index < features; index += 1) {\n total += (coef[base + index] as number) * (row[index] as number);\n }\n scores[output] = total;\n }\n return scores;\n }\n\n /**\n * Walk every tree and average what the leaves hold.\n *\n * A leaf is marked by a negative `feature` entry, which also carries\n * its slot in the value array — so the walk needs no second lookup and\n * the file stores values only for leaves.\n *\n * @param row The prepared feature values.\n * @returns One averaged score per output.\n */\n private treeScores(row: readonly number[]): number[] {\n const feature = this.arrays.node_feature as Int32Array;\n const threshold = this.arrays.node_threshold as Float32Array;\n const left = this.arrays.node_left as Int32Array;\n const right = this.arrays.node_right as Int32Array;\n const leaf = this.arrays.leaf_value as Float32Array;\n const offsets = this.arrays.tree_offset as Int32Array;\n const outputs = this.header.n_outputs;\n const trees = offsets.length - 1;\n\n const totals = new Array<number>(outputs).fill(0);\n for (let tree = 0; tree < trees; tree += 1) {\n let node = offsets[tree] as number;\n let column = feature[node] as number;\n while (column >= 0) {\n node =\n (row[column] as number) <= (threshold[node] as number)\n ? (left[node] as number)\n : (right[node] as number);\n column = feature[node] as number;\n }\n const slot = (-1 - column) * outputs;\n for (let output = 0; output < outputs; output += 1) {\n totals[output] += leaf[slot + output] as number;\n }\n }\n for (let output = 0; output < outputs; output += 1) {\n totals[output] = (totals[output] as number) / trees;\n }\n return totals;\n }\n\n /**\n * Turn raw scores into labels and probabilities.\n *\n * @param scores One score array per row.\n * @returns Labels and probabilities in the shape the ONNX route uses,\n * so an app can swap runtimes without touching its own code. That\n * includes the label's **type**: an integer class comes back as a\n * number here exactly as ONNX returns it, because two routes over one\n * model that disagree on `0` versus `\"0\"` break the day someone\n * switches.\n */\n private finish(scores: readonly number[][]): {\n labels: PredictedLabel[];\n probabilities: number[][];\n } {\n const link = this.header.link;\n const classes = this.header.classes;\n\n if (link === \"identity\") {\n return { labels: scores.map((row) => row[0] as number), probabilities: [] };\n }\n\n const probabilities = scores.map((row) => {\n if (link === \"sigmoid\") {\n const positive = 1 / (1 + Math.exp(-(row[0] as number)));\n return [1 - positive, positive];\n }\n if (link === \"softmax\") {\n const highest = Math.max(...row);\n const exponentiated = row.map((value) => Math.exp(value - highest));\n const total = exponentiated.reduce((sum, value) => sum + value, 0);\n return exponentiated.map((value) => value / total);\n }\n const total = row.reduce((sum, value) => sum + value, 0);\n return total === 0 ? [...row] : row.map((value) => value / total);\n });\n\n const numeric = this.header.class_type !== \"str\";\n const labels = probabilities.map((row) => {\n let best = 0;\n for (let index = 1; index < row.length; index += 1) {\n if ((row[index] as number) > (row[best] as number)) best = index;\n }\n const label = classes[best];\n if (label === undefined) return best;\n return numeric ? Number(label) : label;\n });\n\n return { labels, probabilities };\n }\n}\n\n/**\n * Read a source into an `ArrayBuffer`.\n *\n * @param source A URL or the bytes.\n * @param requestInit `fetch` options.\n * @returns The bytes.\n * @throws {@link ModelFetchError} when the URL cannot be read.\n */\nasync function toBuffer(\n source: string | ArrayBuffer | Uint8Array,\n requestInit?: RequestInit,\n): Promise<ArrayBuffer> {\n if (typeof source === \"string\") {\n let response: Response;\n try {\n response = await fetch(source, requestInit);\n } catch (error) {\n throw new ModelFetchError(`Could not download the model: ${source}`, {\n cause: error,\n });\n }\n if (!response.ok) {\n throw new ModelFetchError(\n `Could not download the model: ${response.status} ${response.statusText}`,\n );\n }\n return await response.arrayBuffer();\n }\n if (source instanceof Uint8Array) {\n return source.buffer.slice(\n source.byteOffset,\n source.byteOffset + source.byteLength,\n ) as ArrayBuffer;\n }\n return source;\n}\n\n/**\n * Check a batch before predicting on it.\n *\n * @param rows The batch.\n * @param expected Features the model wants per row.\n * @returns The batch width.\n * @throws {@link FeatureShapeError} when the batch cannot be predicted on.\n */\nfunction validateRows(rows: readonly FeatureRow[], expected: number): number {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new FeatureShapeError(\"predict() needs at least one row, shaped [[f1, f2, ...]].\");\n }\n const width = rows[0]?.length ?? 0;\n const ragged = rows.findIndex((row) => row.length !== width);\n if (ragged !== -1) {\n throw new FeatureShapeError(\n `All rows must have the same width; row ${ragged} has ` +\n `${rows[ragged]?.length} values, expected ${width}.`,\n );\n }\n if (width !== expected) {\n throw new FeatureShapeError(\n `The model expects ${expected} features per row, got ${width}.`,\n );\n }\n return width;\n}\n"],"mappings":";;AA6BA,IAAM,IAAQ,QAGD,IAA2B,GA4D3B,IAAb,MAAa,EAAiB;CAEL;CACA;CAED;CAJpB,YACI,GACA,GAEA,GACF;EADkB,AAHC,KAAA,SAAA,GACA,KAAA,SAAA,GAED,KAAA,OAAA;CACjB;CAYH,aAAa,OACT,GACA,GACyB;EACzB,IAAM,IAAS,MAAM,EAAS,GAAQ,CAAW,GAC3C,IAAQ,IAAI,WAAW,CAAM;EAEnC,IAAI,OAAO,aAAa,GAAG,EAAM,SAAS,GAAG,CAAC,CAAC,MAAM,GACjD,MAAM,IAAI,EACN,6DACQ,EAAM,uDAClB;EAIJ,IAAM,IAAe,IADJ,SAAS,CACL,CAAA,CAAK,UAAU,GAAG,EAAI,GACrC,IAAS,KAAK,MAChB,IAAI,YAAY,CAAC,CAAC,OAAO,EAAM,SAAS,GAAG,IAAI,CAAY,CAAC,CAChE;EAEA,IAAI,EAAO,iBAAA,GACP,MAAM,IAAI,EACN,iCAAiC,EAAO,eAAe,2EAG3D;EAGJ,IAAM,IAAoD,CAAC,GACvD,IAAS,IAAI;EACjB,KAAK,IAAM,KAAW,EAAO,UAKzB,AAJA,EAAO,EAAQ,QACX,EAAQ,UAAU,YACZ,IAAI,aAAa,GAAQ,GAAQ,EAAQ,MAAM,IAC/C,IAAI,WAAW,GAAQ,GAAQ,EAAQ,MAAM,GACvD,KAAU,EAAQ,SAAS;EAG/B,OAAO,IAAI,EAAiB,GAAQ,GAAQ;GACxC,MAAM,EAAO;GACb,SAAS,EAAO;GAChB,aAAa,EAAO;GACpB,cAAc,EAAO;GACrB,UAAU,EAAO,WAAW;GAC5B,cAAc,EAAO,SAAS;GAC9B,WAAW,EAAO;EACtB,CAAC;CACL;CAYA,MAAM,QAAQ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Error`}},t=class extends e{constructor(e,t){super(e,t),this.name=`ModelLoadError`}},n=class extends e{constructor(e,t){super(e,t),this.name=`UnsupportedGraphError`}},r=class extends e{constructor(e,t){super(e,t),this.name=`
|
|
1
|
+
var e=class extends Error{constructor(e,t){super(e,t),this.name=`TabularError`}},t=class extends e{constructor(e,t){super(e,t),this.name=`ModelLoadError`}},n=class extends e{constructor(e,t){super(e,t),this.name=`UnsupportedGraphError`}},r=class extends e{constructor(e,t){super(e,t),this.name=`CompactFormatError`}},i=class extends e{constructor(e,t){super(e,t),this.name=`FeatureShapeError`}},a=class extends e{constructor(e,t){super(e,t),this.name=`InferenceError`}},o=class extends e{constructor(e,t){super(e,t),this.name=`ModelFetchError`}};exports.CompactFormatError=r,exports.FeatureShapeError=i,exports.InferenceError=a,exports.ModelFetchError=o,exports.ModelLoadError=t,exports.TabularError=e,exports.UnsupportedGraphError=n;
|
|
2
2
|
//# sourceMappingURL=exceptions.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exceptions.cjs","names":[],"sources":["../../src/tabular/exceptions.ts"],"sourcesContent":["/**\n * Errors thrown by the tabular inference module.\n *\n * Each one exists because the underlying failure is unreadable on its own:\n * ONNX Runtime reports a missing operator registration, and the actual cause\n * is an import path chosen three files away.\n *\n * Every subclass sets `name` to a **literal** string rather than to\n * `new.target.name`. Measured in a real build: the minifier renames the\n * class, so the derived form ships as `error.name === \"t\"` — useless in a\n * log and in any consumer that branches on the name.\n */\n\n/** Base class for every error this module throws. */\nexport class TabularError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"TabularError\";\n }\n}\n\n/** The model bytes could not be loaded into a session. */\nexport class ModelLoadError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelLoadError\";\n }\n}\n\n/**\n * The runtime has no kernels for this graph's operators.\n *\n * Measured, and the reason this class exists: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly build without the\n * `ai.onnx.ml` domain, so creating a session over any scikit-learn export\n * fails with `No Op registered for TreeEnsembleClassifier`. The message\n * names the fix, because the raw error points at the model instead of at\n * the import.\n */\nexport class UnsupportedGraphError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"UnsupportedGraphError\";\n }\n}\n\n/** The rows do not match what the model expects. */\nexport class FeatureShapeError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"FeatureShapeError\";\n }\n}\n\n/** The session ran but its outputs could not be read. */\nexport class InferenceError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"InferenceError\";\n }\n}\n\n/**\n * The model bytes could not be fetched or read from the cache.\n *\n * Distinct from {@link ModelLoadError}: this one means the app is offline\n * and nothing was cached, which is a deployment problem, not a model\n * problem.\n */\nexport class ModelFetchError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelFetchError\";\n }\n}\n"],"mappings":"AAcA,IAAa,EAAb,cAAkC,KAAM,CACpC,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,cAChB,CACJ,EAGa,EAAb,cAAoC,CAAa,CAC7C,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,gBAChB,CACJ,EAYa,EAAb,cAA2C,CAAa,CACpD,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,uBAChB,CACJ,EAGa,EAAb,cAAuC,CAAa,CAChD,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,mBAChB,CACJ,EAGa,EAAb,cAAoC,CAAa,CAC7C,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,gBAChB,CACJ,EASa,EAAb,cAAqC,CAAa,CAC9C,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,iBAChB,CACJ"}
|
|
1
|
+
{"version":3,"file":"exceptions.cjs","names":[],"sources":["../../src/tabular/exceptions.ts"],"sourcesContent":["/**\n * Errors thrown by the tabular inference module.\n *\n * Each one exists because the underlying failure is unreadable on its own:\n * ONNX Runtime reports a missing operator registration, and the actual cause\n * is an import path chosen three files away.\n *\n * Every subclass sets `name` to a **literal** string rather than to\n * `new.target.name`. Measured in a real build: the minifier renames the\n * class, so the derived form ships as `error.name === \"t\"` — useless in a\n * log and in any consumer that branches on the name.\n */\n\n/** Base class for every error this module throws. */\nexport class TabularError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"TabularError\";\n }\n}\n\n/** The model bytes could not be loaded into a session. */\nexport class ModelLoadError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelLoadError\";\n }\n}\n\n/**\n * The runtime has no kernels for this graph's operators.\n *\n * Measured, and the reason this class exists: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly build without the\n * `ai.onnx.ml` domain, so creating a session over any scikit-learn export\n * fails with `No Op registered for TreeEnsembleClassifier`. The message\n * names the fix, because the raw error points at the model instead of at\n * the import.\n */\nexport class UnsupportedGraphError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"UnsupportedGraphError\";\n }\n}\n\n/**\n * The bytes are not a compact model, or use a newer layout.\n *\n * Separate from {@link ModelLoadError} because the fix is different: a\n * `.onnx` file handed to the compact reader is a wiring mistake, not a\n * broken model.\n */\nexport class CompactFormatError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CompactFormatError\";\n }\n}\n\n/** The rows do not match what the model expects. */\nexport class FeatureShapeError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"FeatureShapeError\";\n }\n}\n\n/** The session ran but its outputs could not be read. */\nexport class InferenceError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"InferenceError\";\n }\n}\n\n/**\n * The model bytes could not be fetched or read from the cache.\n *\n * Distinct from {@link ModelLoadError}: this one means the app is offline\n * and nothing was cached, which is a deployment problem, not a model\n * problem.\n */\nexport class ModelFetchError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelFetchError\";\n }\n}\n"],"mappings":"AAcA,IAAa,EAAb,cAAkC,KAAM,CACpC,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,cAChB,CACJ,EAGa,EAAb,cAAoC,CAAa,CAC7C,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,gBAChB,CACJ,EAYa,EAAb,cAA2C,CAAa,CACpD,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,uBAChB,CACJ,EASa,EAAb,cAAwC,CAAa,CACjD,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,oBAChB,CACJ,EAGa,EAAb,cAAuC,CAAa,CAChD,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,mBAChB,CACJ,EAGa,EAAb,cAAoC,CAAa,CAC7C,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,gBAChB,CACJ,EASa,EAAb,cAAqC,CAAa,CAC9C,YAAY,EAAiB,EAAwB,CACjD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,iBAChB,CACJ"}
|
|
@@ -13,18 +13,22 @@ var e = class extends Error {
|
|
|
13
13
|
}
|
|
14
14
|
}, r = class extends e {
|
|
15
15
|
constructor(e, t) {
|
|
16
|
-
super(e, t), this.name = "
|
|
16
|
+
super(e, t), this.name = "CompactFormatError";
|
|
17
17
|
}
|
|
18
18
|
}, i = class extends e {
|
|
19
19
|
constructor(e, t) {
|
|
20
|
-
super(e, t), this.name = "
|
|
20
|
+
super(e, t), this.name = "FeatureShapeError";
|
|
21
21
|
}
|
|
22
22
|
}, a = class extends e {
|
|
23
|
+
constructor(e, t) {
|
|
24
|
+
super(e, t), this.name = "InferenceError";
|
|
25
|
+
}
|
|
26
|
+
}, o = class extends e {
|
|
23
27
|
constructor(e, t) {
|
|
24
28
|
super(e, t), this.name = "ModelFetchError";
|
|
25
29
|
}
|
|
26
30
|
};
|
|
27
31
|
//#endregion
|
|
28
|
-
export { r as
|
|
32
|
+
export { r as CompactFormatError, i as FeatureShapeError, a as InferenceError, o as ModelFetchError, t as ModelLoadError, e as TabularError, n as UnsupportedGraphError };
|
|
29
33
|
|
|
30
34
|
//# sourceMappingURL=exceptions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exceptions.js","names":[],"sources":["../../src/tabular/exceptions.ts"],"sourcesContent":["/**\n * Errors thrown by the tabular inference module.\n *\n * Each one exists because the underlying failure is unreadable on its own:\n * ONNX Runtime reports a missing operator registration, and the actual cause\n * is an import path chosen three files away.\n *\n * Every subclass sets `name` to a **literal** string rather than to\n * `new.target.name`. Measured in a real build: the minifier renames the\n * class, so the derived form ships as `error.name === \"t\"` — useless in a\n * log and in any consumer that branches on the name.\n */\n\n/** Base class for every error this module throws. */\nexport class TabularError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"TabularError\";\n }\n}\n\n/** The model bytes could not be loaded into a session. */\nexport class ModelLoadError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelLoadError\";\n }\n}\n\n/**\n * The runtime has no kernels for this graph's operators.\n *\n * Measured, and the reason this class exists: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly build without the\n * `ai.onnx.ml` domain, so creating a session over any scikit-learn export\n * fails with `No Op registered for TreeEnsembleClassifier`. The message\n * names the fix, because the raw error points at the model instead of at\n * the import.\n */\nexport class UnsupportedGraphError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"UnsupportedGraphError\";\n }\n}\n\n/** The rows do not match what the model expects. */\nexport class FeatureShapeError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"FeatureShapeError\";\n }\n}\n\n/** The session ran but its outputs could not be read. */\nexport class InferenceError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"InferenceError\";\n }\n}\n\n/**\n * The model bytes could not be fetched or read from the cache.\n *\n * Distinct from {@link ModelLoadError}: this one means the app is offline\n * and nothing was cached, which is a deployment problem, not a model\n * problem.\n */\nexport class ModelFetchError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelFetchError\";\n }\n}\n"],"mappings":";AAcA,IAAa,IAAb,cAAkC,MAAM;CACpC,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAGa,IAAb,cAAoC,EAAa;CAC7C,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAYa,IAAb,cAA2C,EAAa;CACpD,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAGa,IAAb,cAAuC,EAAa;CAChD,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAGa,IAAb,cAAoC,EAAa;CAC7C,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GASa,IAAb,cAAqC,EAAa;CAC9C,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ"}
|
|
1
|
+
{"version":3,"file":"exceptions.js","names":[],"sources":["../../src/tabular/exceptions.ts"],"sourcesContent":["/**\n * Errors thrown by the tabular inference module.\n *\n * Each one exists because the underlying failure is unreadable on its own:\n * ONNX Runtime reports a missing operator registration, and the actual cause\n * is an import path chosen three files away.\n *\n * Every subclass sets `name` to a **literal** string rather than to\n * `new.target.name`. Measured in a real build: the minifier renames the\n * class, so the derived form ships as `error.name === \"t\"` — useless in a\n * log and in any consumer that branches on the name.\n */\n\n/** Base class for every error this module throws. */\nexport class TabularError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"TabularError\";\n }\n}\n\n/** The model bytes could not be loaded into a session. */\nexport class ModelLoadError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelLoadError\";\n }\n}\n\n/**\n * The runtime has no kernels for this graph's operators.\n *\n * Measured, and the reason this class exists: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly build without the\n * `ai.onnx.ml` domain, so creating a session over any scikit-learn export\n * fails with `No Op registered for TreeEnsembleClassifier`. The message\n * names the fix, because the raw error points at the model instead of at\n * the import.\n */\nexport class UnsupportedGraphError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"UnsupportedGraphError\";\n }\n}\n\n/**\n * The bytes are not a compact model, or use a newer layout.\n *\n * Separate from {@link ModelLoadError} because the fix is different: a\n * `.onnx` file handed to the compact reader is a wiring mistake, not a\n * broken model.\n */\nexport class CompactFormatError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CompactFormatError\";\n }\n}\n\n/** The rows do not match what the model expects. */\nexport class FeatureShapeError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"FeatureShapeError\";\n }\n}\n\n/** The session ran but its outputs could not be read. */\nexport class InferenceError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"InferenceError\";\n }\n}\n\n/**\n * The model bytes could not be fetched or read from the cache.\n *\n * Distinct from {@link ModelLoadError}: this one means the app is offline\n * and nothing was cached, which is a deployment problem, not a model\n * problem.\n */\nexport class ModelFetchError extends TabularError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ModelFetchError\";\n }\n}\n"],"mappings":";AAcA,IAAa,IAAb,cAAkC,MAAM;CACpC,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAGa,IAAb,cAAoC,EAAa;CAC7C,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAYa,IAAb,cAA2C,EAAa;CACpD,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GASa,IAAb,cAAwC,EAAa;CACjD,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAGa,IAAb,cAAuC,EAAa;CAChD,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GAGa,IAAb,cAAoC,EAAa;CAC7C,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ,GASa,IAAb,cAAqC,EAAa;CAC9C,YAAY,GAAiB,GAAwB;EAEjD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,OAAO;CAChB;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./exceptions.cjs"),t=require("./cache.cjs"),n=require("./predictor.cjs");var
|
|
1
|
+
const e=require("./exceptions.cjs"),t=require("./cache.cjs"),n=require("./compact.cjs"),r=require("./predictor.cjs");var i=1,a=`manifest.json`;async function o(t,n){let r=u(t),i;try{i=await fetch(r,n)}catch(t){throw new e.ModelFetchError(`Could not read the manifest at ${r}`,{cause:t})}if(!i.ok)throw new e.ModelFetchError(`Could not read the manifest at ${r}: ${i.status} ${i.statusText}`);let a=await i.json();if(typeof a?.schema_version!=`number`)throw new e.ModelFetchError(`${r} is not an edge package manifest (no schema_version).`);if(a.schema_version>1)throw new e.ModelFetchError(`The manifest at ${r} uses schema_version ${a.schema_version}, and this SDK understands 1. Upgrade tempest-react-sdk before serving this package.`);return a}async function s(e,i={}){let a=await o(e),s=e.endsWith(`/`)?e:`${e}/`,u=c(a,i.runtime??`auto`),d=`${s}${l(a,u)}`,f=i.cache??!0,p=f===!1?d:await t.fetchModelBytes(d,typeof f==`object`?f:{}),m=u===`compact`?await n.CompactPredictor.create(p):await r.TabularPredictor.create(p,{providers:i.providers,warmup:i.warmup,sessionOptions:i.sessionOptions}),h=a.output.classes;return{manifest:a,predictor:m,runtime:u,featureNames:a.input.feature_names,classes:h,explain:e=>e.map((e,t)=>({name:h[t]??String(t),score:e})).sort((e,t)=>t.score-e.score)}}function c(t,n){let r=t.runtimes??[],i=r.some(e=>e.kind===`compact`);if(n===`auto`)return i?`compact`:`onnx`;if(n===`compact`&&!i)throw new e.ModelFetchError(`This package carries no compact model (${t.name} lists ${r.map(e=>e.kind).join(`, `)||`onnx`}). Re-export it with edge_pipeline(compact=True), or load it as ONNX.`);return n}function l(e,t){return(e.runtimes??[]).find(e=>e.kind===t)?.file??e.model.file}function u(e){return e.endsWith(`.json`)?e:e.endsWith(`/`)?`${e}${a}`:`${e}/${a}`}exports.MANIFEST_FILENAME=a,exports.SUPPORTED_MANIFEST_SCHEMA=i,exports.fetchEdgeManifest=o,exports.loadEdgePackage=s;
|
|
2
2
|
//# sourceMappingURL=manifest.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.cjs","names":[],"sources":["../../src/tabular/manifest.ts"],"sourcesContent":["/**\n * Reading an edge package published by `tempest-fastapi-sdk`.\n *\n * `edge_pipeline` writes a directory — the graph, a gzipped copy, a drift\n * baseline and a `manifest.json` — and the browser is one of its two\n * intended consumers. The manifest is what turns a `.onnx` URL into\n * something a UI can use: the **column order** the model was trained on,\n * the class names behind `probabilities[2]`, and a version to compare\n * against what is already cached.\n *\n * That column order is the field worth loading a manifest for. A model fed\n * the right features in the wrong order answers confidently and wrongly,\n * and no runtime check catches it.\n *\n * The contract is pinned by `schema_version`. Unknown fields are ignored\n * rather than rejected, so a package written by a newer SDK still loads.\n */\n\nimport { fetchModelBytes, type ModelCacheOptions } from \"./cache\";\nimport { ModelFetchError } from \"./exceptions\";\nimport { TabularPredictor } from \"./predictor\";\nimport type { TabularPredictorOptions } from \"./types\";\n\n/** Manifest schema version this reader was written against. */\nexport const SUPPORTED_MANIFEST_SCHEMA = 1;\n\n/** Fixed filename inside a package directory. */\nexport const MANIFEST_FILENAME = \"manifest.json\";\n\n/** The graph file and how to check you got it whole. */\nexport interface ManifestModelFile {\n readonly file: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly gzip_file: string | null;\n readonly gzip_bytes: number | null;\n readonly opset: number;\n readonly dtype: string;\n}\n\n/** What the graph expects per row. */\nexport interface ManifestInput {\n readonly name: string;\n readonly features: number;\n /** Column order used at training time. */\n readonly feature_names: readonly string[];\n}\n\n/** What the graph answers. */\nexport interface ManifestOutput {\n readonly is_classifier: boolean;\n readonly label_output: string;\n readonly probability_output: string | null;\n /** Class labels in score-column order. */\n readonly classes: readonly string[];\n}\n\n/** The package manifest, as written by `edge_pipeline`. */\nexport interface EdgeManifest {\n readonly schema_version: number;\n readonly name: string;\n readonly version: string;\n readonly created_at: string;\n readonly sdk_version: string;\n readonly estimator: string;\n readonly model: ManifestModelFile;\n readonly input: ManifestInput;\n readonly output: ManifestOutput;\n readonly verified: boolean | null;\n readonly baseline_file: string | null;\n readonly baseline_samples: number;\n}\n\n/** A package loaded and ready to answer. */\nexport interface LoadedEdgePackage {\n /** What was published. */\n readonly manifest: EdgeManifest;\n /** The running model. */\n readonly predictor: TabularPredictor;\n /** Column order the rows must follow. */\n readonly featureNames: readonly string[];\n /** Class names behind each probability column. */\n readonly classes: readonly string[];\n /**\n * Map a prediction's scores onto class names.\n *\n * @param probabilities One row of scores.\n * @returns Name/score pairs, highest first.\n */\n readonly explain: (probabilities: readonly number[]) => { name: string; score: number }[];\n}\n\n/** Options for {@link loadEdgePackage}. */\nexport interface LoadEdgePackageOptions extends TabularPredictorOptions {\n /** Cache the model bytes for offline use. `true` by default. */\n readonly cache?: boolean | ModelCacheOptions;\n}\n\n/**\n * Read a package's manifest.\n *\n * Cheap: it is a few hundred bytes, so an app can check for a new version\n * without downloading a model it may already have.\n *\n * @example\n * ```ts\n * const manifest = await fetchEdgeManifest(\"/models/risk/\");\n * if (manifest.version !== localStorage.getItem(\"risk-version\")) {\n * // a new model was published\n * }\n * ```\n *\n * @param directoryUrl URL of the package directory, with or without a\n * trailing slash. A full URL to the manifest file also works.\n * @param requestInit `fetch` options.\n * @returns The parsed manifest.\n * @throws {@link ModelFetchError} when the manifest cannot be read, or when\n * its `schema_version` is newer than this reader understands — loading it\n * anyway would risk misreading the field that defines column order.\n */\nexport async function fetchEdgeManifest(\n directoryUrl: string,\n requestInit?: RequestInit,\n): Promise<EdgeManifest> {\n const url = manifestUrl(directoryUrl);\n let response: Response;\n try {\n response = await fetch(url, requestInit);\n } catch (error) {\n throw new ModelFetchError(`Could not read the manifest at ${url}`, {\n cause: error,\n });\n }\n if (!response.ok) {\n throw new ModelFetchError(\n `Could not read the manifest at ${url}: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as EdgeManifest;\n if (typeof manifest?.schema_version !== \"number\") {\n throw new ModelFetchError(`${url} is not an edge package manifest (no schema_version).`);\n }\n if (manifest.schema_version > SUPPORTED_MANIFEST_SCHEMA) {\n throw new ModelFetchError(\n `The manifest at ${url} uses schema_version ${manifest.schema_version}, ` +\n `and this SDK understands ${SUPPORTED_MANIFEST_SCHEMA}. Upgrade ` +\n \"tempest-react-sdk before serving this package.\",\n );\n }\n return manifest;\n}\n\n/**\n * Load a whole edge package: manifest, model, and the names to read it by.\n *\n * @example\n * ```ts\n * const pkg = await loadEdgePackage(\"/models/risk/\");\n *\n * console.log(pkg.featureNames); // [\"age\", \"income\", \"tenure\", \"score\", \"visits\"]\n *\n * const { probabilities } = await pkg.predictor.predict([[41, 5200, 3, 0.82, 12]]);\n * console.log(pkg.explain(probabilities[0]!)); // [{ name: \"approved\", score: 0.91 }, ...]\n * ```\n *\n * @param directoryUrl URL of the package directory.\n * @param options Predictor options plus caching.\n * @returns The loaded package.\n * @throws {@link ModelFetchError} when the manifest or model cannot be read.\n */\nexport async function loadEdgePackage(\n directoryUrl: string,\n options: LoadEdgePackageOptions = {},\n): Promise<LoadedEdgePackage> {\n const manifest = await fetchEdgeManifest(directoryUrl);\n const base = directoryUrl.endsWith(\"/\") ? directoryUrl : `${directoryUrl}/`;\n const modelUrl = `${base}${manifest.model.file}`;\n\n const cache = options.cache ?? true;\n const source =\n cache === false\n ? modelUrl\n : await fetchModelBytes(modelUrl, typeof cache === \"object\" ? cache : {});\n\n const predictor = await TabularPredictor.create(source, {\n providers: options.providers,\n warmup: options.warmup,\n sessionOptions: options.sessionOptions,\n });\n\n const classes = manifest.output.classes;\n return {\n manifest,\n predictor,\n featureNames: manifest.input.feature_names,\n classes,\n explain: (probabilities: readonly number[]) =>\n probabilities\n .map((score, index) => ({\n name: classes[index] ?? String(index),\n score,\n }))\n .sort((a, b) => b.score - a.score),\n };\n}\n\n/**\n * Resolve a directory URL to its manifest file.\n *\n * @param directoryUrl The package directory, or the manifest itself.\n * @returns The manifest URL.\n */\nfunction manifestUrl(directoryUrl: string): string {\n if (directoryUrl.endsWith(\".json\")) return directoryUrl;\n return directoryUrl.endsWith(\"/\")\n ? `${directoryUrl}${MANIFEST_FILENAME}`\n : `${directoryUrl}/${MANIFEST_FILENAME}`;\n}\n"],"mappings":"0FAwBA,IAAa,EAA4B,EAG5B,EAAoB,gBA6FjC,eAAsB,EAClB,EACA,EACqB,CACrB,IAAM,EAAM,EAAY,CAAY,EAChC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B,GAAG,EAAa,GAAG,GAC7B"}
|
|
1
|
+
{"version":3,"file":"manifest.cjs","names":[],"sources":["../../src/tabular/manifest.ts"],"sourcesContent":["/**\n * Reading an edge package published by `tempest-fastapi-sdk`.\n *\n * `edge_pipeline` writes a directory — the graph, a gzipped copy, a drift\n * baseline and a `manifest.json` — and the browser is one of its two\n * intended consumers. The manifest is what turns a `.onnx` URL into\n * something a UI can use: the **column order** the model was trained on,\n * the class names behind `probabilities[2]`, and a version to compare\n * against what is already cached.\n *\n * That column order is the field worth loading a manifest for. A model fed\n * the right features in the wrong order answers confidently and wrongly,\n * and no runtime check catches it.\n *\n * The contract is pinned by `schema_version`. Unknown fields are ignored\n * rather than rejected, so a package written by a newer SDK still loads.\n */\n\nimport { fetchModelBytes, type ModelCacheOptions } from \"./cache\";\nimport { CompactPredictor } from \"./compact\";\nimport { ModelFetchError } from \"./exceptions\";\nimport { TabularPredictor } from \"./predictor\";\nimport type { FeatureRow, TabularPrediction, TabularPredictorOptions } from \"./types\";\n\n/** Manifest schema version this reader was written against. */\nexport const SUPPORTED_MANIFEST_SCHEMA = 1;\n\n/** Fixed filename inside a package directory. */\nexport const MANIFEST_FILENAME = \"manifest.json\";\n\n/** The graph file and how to check you got it whole. */\nexport interface ManifestModelFile {\n readonly file: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly gzip_file: string | null;\n readonly gzip_bytes: number | null;\n readonly opset: number;\n readonly dtype: string;\n}\n\n/** What the graph expects per row. */\nexport interface ManifestInput {\n readonly name: string;\n readonly features: number;\n /** Column order used at training time. */\n readonly feature_names: readonly string[];\n}\n\n/** What the graph answers. */\nexport interface ManifestOutput {\n readonly is_classifier: boolean;\n readonly label_output: string;\n readonly probability_output: string | null;\n /** Class labels in score-column order. */\n readonly classes: readonly string[];\n}\n\n/**\n * Where the packaged model came from, when it came from an existing\n * artifact.\n *\n * Present when the package was built with `edge_pipeline_from_pickle`: the\n * `.pkl` never reaches the browser (a pickle is a Python program, not\n * data), but its name and digest travel in the manifest, so a model\n * answering in a tab can be traced back to the file that produced it.\n */\nexport interface ManifestSource {\n readonly file: string;\n readonly kind: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly sklearn_version: string;\n readonly warnings: readonly string[];\n}\n\n/**\n * One file in the package a runtime can load.\n *\n * A package may carry the same model twice — as ONNX, which any runtime\n * reads at the cost of a 25.6 MB WebAssembly download, and as the compact\n * format, which needs no runtime. The list is what lets the browser pick\n * by what it already ships.\n */\nexport interface ManifestRuntime {\n readonly kind: \"onnx\" | \"compact\" | string;\n readonly file: string;\n readonly bytes: number;\n readonly gzip_file: string | null;\n readonly gzip_bytes: number | null;\n readonly sha256: string;\n}\n\n/** The package manifest, as written by `edge_pipeline`. */\nexport interface EdgeManifest {\n readonly schema_version: number;\n readonly name: string;\n readonly version: string;\n readonly created_at: string;\n readonly sdk_version: string;\n readonly estimator: string;\n readonly model: ManifestModelFile;\n readonly input: ManifestInput;\n readonly output: ManifestOutput;\n readonly verified: boolean | null;\n /** Every file a runtime can load. Absent on packages written before v0.194. */\n readonly runtimes?: readonly ManifestRuntime[];\n /** Absent on packages built straight from a fitted estimator. */\n readonly source?: ManifestSource;\n readonly baseline_file: string | null;\n readonly baseline_samples: number;\n}\n\n/** Which reader served the package. */\nexport type TabularRuntime = \"onnx\" | \"compact\";\n\n/** A package loaded and ready to answer. */\nexport interface LoadedEdgePackage {\n /** What was published. */\n readonly manifest: EdgeManifest;\n /** The running model, whichever runtime read it. */\n readonly predictor: PredictorLike;\n /** Which reader was used. */\n readonly runtime: TabularRuntime;\n /** Column order the rows must follow. */\n readonly featureNames: readonly string[];\n /** Class names behind each probability column. */\n readonly classes: readonly string[];\n /**\n * Map a prediction's scores onto class names.\n *\n * @param probabilities One row of scores.\n * @returns Name/score pairs, highest first.\n */\n readonly explain: (probabilities: readonly number[]) => { name: string; score: number }[];\n}\n\n/**\n * The shape both readers share.\n *\n * `TabularPredictor` (ONNX) and `CompactPredictor` (runtime-free) answer\n * with the same object, so an app can switch routes without touching a\n * line of its own code.\n */\nexport interface PredictorLike {\n predict(rows: readonly FeatureRow[]): Promise<TabularPrediction>;\n dispose(): Promise<void>;\n}\n\n/** Options for {@link loadEdgePackage}. */\nexport interface LoadEdgePackageOptions extends TabularPredictorOptions {\n /** Cache the model bytes for offline use. `true` by default. */\n readonly cache?: boolean | ModelCacheOptions;\n /**\n * Which reader to use.\n *\n * `\"auto\"` (the default) takes the compact form when the package has\n * one, because it answers without downloading a WebAssembly runtime.\n * Force `\"onnx\"` when the app already ships ONNX for something else —\n * then the runtime is already paid for and ONNX covers more estimators.\n */\n readonly runtime?: TabularRuntime | \"auto\";\n}\n\n/**\n * Read a package's manifest.\n *\n * Cheap: it is a few hundred bytes, so an app can check for a new version\n * without downloading a model it may already have.\n *\n * @example\n * ```ts\n * const manifest = await fetchEdgeManifest(\"/models/risk/\");\n * if (manifest.version !== localStorage.getItem(\"risk-version\")) {\n * // a new model was published\n * }\n * ```\n *\n * @param directoryUrl URL of the package directory, with or without a\n * trailing slash. A full URL to the manifest file also works.\n * @param requestInit `fetch` options.\n * @returns The parsed manifest.\n * @throws {@link ModelFetchError} when the manifest cannot be read, or when\n * its `schema_version` is newer than this reader understands — loading it\n * anyway would risk misreading the field that defines column order.\n */\nexport async function fetchEdgeManifest(\n directoryUrl: string,\n requestInit?: RequestInit,\n): Promise<EdgeManifest> {\n const url = manifestUrl(directoryUrl);\n let response: Response;\n try {\n response = await fetch(url, requestInit);\n } catch (error) {\n throw new ModelFetchError(`Could not read the manifest at ${url}`, {\n cause: error,\n });\n }\n if (!response.ok) {\n throw new ModelFetchError(\n `Could not read the manifest at ${url}: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as EdgeManifest;\n if (typeof manifest?.schema_version !== \"number\") {\n throw new ModelFetchError(`${url} is not an edge package manifest (no schema_version).`);\n }\n if (manifest.schema_version > SUPPORTED_MANIFEST_SCHEMA) {\n throw new ModelFetchError(\n `The manifest at ${url} uses schema_version ${manifest.schema_version}, ` +\n `and this SDK understands ${SUPPORTED_MANIFEST_SCHEMA}. Upgrade ` +\n \"tempest-react-sdk before serving this package.\",\n );\n }\n return manifest;\n}\n\n/**\n * Load a whole edge package: manifest, model, and the names to read it by.\n *\n * @example\n * ```ts\n * const pkg = await loadEdgePackage(\"/models/risk/\");\n *\n * console.log(pkg.featureNames); // [\"age\", \"income\", \"tenure\", \"score\", \"visits\"]\n *\n * const { probabilities } = await pkg.predictor.predict([[41, 5200, 3, 0.82, 12]]);\n * console.log(pkg.explain(probabilities[0]!)); // [{ name: \"approved\", score: 0.91 }, ...]\n * ```\n *\n * @param directoryUrl URL of the package directory.\n * @param options Predictor options plus caching.\n * @returns The loaded package.\n * @throws {@link ModelFetchError} when the manifest or model cannot be read.\n */\nexport async function loadEdgePackage(\n directoryUrl: string,\n options: LoadEdgePackageOptions = {},\n): Promise<LoadedEdgePackage> {\n const manifest = await fetchEdgeManifest(directoryUrl);\n const base = directoryUrl.endsWith(\"/\") ? directoryUrl : `${directoryUrl}/`;\n const runtime = chooseRuntime(manifest, options.runtime ?? \"auto\");\n const file = fileFor(manifest, runtime);\n const modelUrl = `${base}${file}`;\n\n const cache = options.cache ?? true;\n const source =\n cache === false\n ? modelUrl\n : await fetchModelBytes(modelUrl, typeof cache === \"object\" ? cache : {});\n\n const predictor: PredictorLike =\n runtime === \"compact\"\n ? await CompactPredictor.create(source)\n : await TabularPredictor.create(source, {\n providers: options.providers,\n warmup: options.warmup,\n sessionOptions: options.sessionOptions,\n });\n\n const classes = manifest.output.classes;\n return {\n manifest,\n predictor,\n runtime,\n featureNames: manifest.input.feature_names,\n classes,\n explain: (probabilities: readonly number[]) =>\n probabilities\n .map((score, index) => ({\n name: classes[index] ?? String(index),\n score,\n }))\n .sort((a, b) => b.score - a.score),\n };\n}\n\n/**\n * Decide which reader serves this package.\n *\n * @param manifest The package manifest.\n * @param requested What the caller asked for.\n * @returns The runtime to use.\n * @throws {@link ModelFetchError} when the package does not carry the\n * requested form — asking for a compact model that was never written\n * should say so, not silently download 25 MB of WebAssembly instead.\n */\nfunction chooseRuntime(manifest: EdgeManifest, requested: TabularRuntime | \"auto\"): TabularRuntime {\n const available = manifest.runtimes ?? [];\n const hasCompact = available.some((entry) => entry.kind === \"compact\");\n\n if (requested === \"auto\") return hasCompact ? \"compact\" : \"onnx\";\n if (requested === \"compact\" && !hasCompact) {\n throw new ModelFetchError(\n `This package carries no compact model (${manifest.name} lists ` +\n `${available.map((entry) => entry.kind).join(\", \") || \"onnx\"}). ` +\n \"Re-export it with edge_pipeline(compact=True), or load it as ONNX.\",\n );\n }\n return requested;\n}\n\n/**\n * Find the file a runtime reads.\n *\n * @param manifest The package manifest.\n * @param runtime The chosen runtime.\n * @returns The filename inside the package directory.\n */\nfunction fileFor(manifest: EdgeManifest, runtime: TabularRuntime): string {\n const entry = (manifest.runtimes ?? []).find((item) => item.kind === runtime);\n return entry?.file ?? manifest.model.file;\n}\n\n/**\n * Resolve a directory URL to its manifest file.\n *\n * @param directoryUrl The package directory, or the manifest itself.\n * @returns The manifest URL.\n */\nfunction manifestUrl(directoryUrl: string): string {\n if (directoryUrl.endsWith(\".json\")) return directoryUrl;\n return directoryUrl.endsWith(\"/\")\n ? `${directoryUrl}${MANIFEST_FILENAME}`\n : `${directoryUrl}/${MANIFEST_FILENAME}`;\n}\n"],"mappings":"qHAyBA,IAAa,EAA4B,EAG5B,EAAoB,gBA8JjC,eAAsB,EAClB,EACA,EACqB,CACrB,IAAM,EAAM,EAAY,CAAY,EAChC,EACJ,GAAI,CACA,EAAW,MAAM,MAAM,EAAK,CAAW,CAC3C,OAAS,EAAO,CACZ,MAAM,IAAI,EAAA,gBAAgB,kCAAkC,IAAO,CAC/D,MAAO,CACX,CAAC,CACL,CACA,GAAI,CAAC,EAAS,GACV,MAAM,IAAI,EAAA,gBACN,kCAAkC,EAAI,IAAI,EAAS,OAAO,GAAG,EAAS,YAC1E,EAGJ,IAAM,EAAY,MAAM,EAAS,KAAK,EACtC,GAA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AC,KAAK,IAAI,GAAK,OAAO,sEAErE,EAEJ,OAAO,CACX,CASA,SAAS,EAAQ,EAAwB,EAAiC,CAEtE,OADe,EAAS,UAAY,CAAC,EAAA,CAAG,KAAM,GAAS,EAAK,OAAS,CAC9D,CAAA,EAAO,MAAQ,EAAS,MAAM,IACzC,CAQA,SAAS,EAAY,EAA8B,CAE/C,OADI,EAAa,SAAS,OAAO,EAAU,EACpC,EAAa,SAAS,GAAG,EAC1B,GAAG,IAAe,IAClB,GAAG,EAAa,GAAG,GAC7B"}
|
package/dist/tabular/manifest.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { ModelFetchError as e } from "./exceptions.js";
|
|
2
2
|
import { fetchModelBytes as t } from "./cache.js";
|
|
3
|
-
import {
|
|
3
|
+
import { CompactPredictor as n } from "./compact.js";
|
|
4
|
+
import { TabularPredictor as r } from "./predictor.js";
|
|
4
5
|
//#region src/tabular/manifest.ts
|
|
5
|
-
var
|
|
6
|
-
async function
|
|
7
|
-
let r =
|
|
6
|
+
var i = 1, a = "manifest.json";
|
|
7
|
+
async function o(t, n) {
|
|
8
|
+
let r = u(t), i;
|
|
8
9
|
try {
|
|
9
10
|
i = await fetch(r, n);
|
|
10
11
|
} catch (t) {
|
|
@@ -16,27 +17,37 @@ async function a(t, n) {
|
|
|
16
17
|
if (a.schema_version > 1) throw new e(`The manifest at ${r} uses schema_version ${a.schema_version}, and this SDK understands 1. Upgrade tempest-react-sdk before serving this package.`);
|
|
17
18
|
return a;
|
|
18
19
|
}
|
|
19
|
-
async function
|
|
20
|
-
let
|
|
21
|
-
providers:
|
|
22
|
-
warmup:
|
|
23
|
-
sessionOptions:
|
|
24
|
-
}),
|
|
20
|
+
async function s(e, i = {}) {
|
|
21
|
+
let a = await o(e), s = e.endsWith("/") ? e : `${e}/`, u = c(a, i.runtime ?? "auto"), d = `${s}${l(a, u)}`, f = i.cache ?? !0, p = f === !1 ? d : await t(d, typeof f == "object" ? f : {}), m = u === "compact" ? await n.create(p) : await r.create(p, {
|
|
22
|
+
providers: i.providers,
|
|
23
|
+
warmup: i.warmup,
|
|
24
|
+
sessionOptions: i.sessionOptions
|
|
25
|
+
}), h = a.output.classes;
|
|
25
26
|
return {
|
|
26
|
-
manifest:
|
|
27
|
-
predictor:
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
manifest: a,
|
|
28
|
+
predictor: m,
|
|
29
|
+
runtime: u,
|
|
30
|
+
featureNames: a.input.feature_names,
|
|
31
|
+
classes: h,
|
|
30
32
|
explain: (e) => e.map((e, t) => ({
|
|
31
|
-
name:
|
|
33
|
+
name: h[t] ?? String(t),
|
|
32
34
|
score: e
|
|
33
35
|
})).sort((e, t) => t.score - e.score)
|
|
34
36
|
};
|
|
35
37
|
}
|
|
36
|
-
function
|
|
37
|
-
|
|
38
|
+
function c(t, n) {
|
|
39
|
+
let r = t.runtimes ?? [], i = r.some((e) => e.kind === "compact");
|
|
40
|
+
if (n === "auto") return i ? "compact" : "onnx";
|
|
41
|
+
if (n === "compact" && !i) throw new e(`This package carries no compact model (${t.name} lists ${r.map((e) => e.kind).join(", ") || "onnx"}). Re-export it with edge_pipeline(compact=True), or load it as ONNX.`);
|
|
42
|
+
return n;
|
|
43
|
+
}
|
|
44
|
+
function l(e, t) {
|
|
45
|
+
return (e.runtimes ?? []).find((e) => e.kind === t)?.file ?? e.model.file;
|
|
46
|
+
}
|
|
47
|
+
function u(e) {
|
|
48
|
+
return e.endsWith(".json") ? e : e.endsWith("/") ? `${e}${a}` : `${e}/${a}`;
|
|
38
49
|
}
|
|
39
50
|
//#endregion
|
|
40
|
-
export {
|
|
51
|
+
export { a as MANIFEST_FILENAME, i as SUPPORTED_MANIFEST_SCHEMA, o as fetchEdgeManifest, s as loadEdgePackage };
|
|
41
52
|
|
|
42
53
|
//# sourceMappingURL=manifest.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","names":[],"sources":["../../src/tabular/manifest.ts"],"sourcesContent":["/**\n * Reading an edge package published by `tempest-fastapi-sdk`.\n *\n * `edge_pipeline` writes a directory — the graph, a gzipped copy, a drift\n * baseline and a `manifest.json` — and the browser is one of its two\n * intended consumers. The manifest is what turns a `.onnx` URL into\n * something a UI can use: the **column order** the model was trained on,\n * the class names behind `probabilities[2]`, and a version to compare\n * against what is already cached.\n *\n * That column order is the field worth loading a manifest for. A model fed\n * the right features in the wrong order answers confidently and wrongly,\n * and no runtime check catches it.\n *\n * The contract is pinned by `schema_version`. Unknown fields are ignored\n * rather than rejected, so a package written by a newer SDK still loads.\n */\n\nimport { fetchModelBytes, type ModelCacheOptions } from \"./cache\";\nimport { ModelFetchError } from \"./exceptions\";\nimport { TabularPredictor } from \"./predictor\";\nimport type { TabularPredictorOptions } from \"./types\";\n\n/** Manifest schema version this reader was written against. */\nexport const SUPPORTED_MANIFEST_SCHEMA = 1;\n\n/** Fixed filename inside a package directory. */\nexport const MANIFEST_FILENAME = \"manifest.json\";\n\n/** The graph file and how to check you got it whole. */\nexport interface ManifestModelFile {\n readonly file: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly gzip_file: string | null;\n readonly gzip_bytes: number | null;\n readonly opset: number;\n readonly dtype: string;\n}\n\n/** What the graph expects per row. */\nexport interface ManifestInput {\n readonly name: string;\n readonly features: number;\n /** Column order used at training time. */\n readonly feature_names: readonly string[];\n}\n\n/** What the graph answers. */\nexport interface ManifestOutput {\n readonly is_classifier: boolean;\n readonly label_output: string;\n readonly probability_output: string | null;\n /** Class labels in score-column order. */\n readonly classes: readonly string[];\n}\n\n/** The package manifest, as written by `edge_pipeline`. */\nexport interface EdgeManifest {\n readonly schema_version: number;\n readonly name: string;\n readonly version: string;\n readonly created_at: string;\n readonly sdk_version: string;\n readonly estimator: string;\n readonly model: ManifestModelFile;\n readonly input: ManifestInput;\n readonly output: ManifestOutput;\n readonly verified: boolean | null;\n readonly baseline_file: string | null;\n readonly baseline_samples: number;\n}\n\n/** A package loaded and ready to answer. */\nexport interface LoadedEdgePackage {\n /** What was published. */\n readonly manifest: EdgeManifest;\n /** The running model. */\n readonly predictor: TabularPredictor;\n /** Column order the rows must follow. */\n readonly featureNames: readonly string[];\n /** Class names behind each probability column. */\n readonly classes: readonly string[];\n /**\n * Map a prediction's scores onto class names.\n *\n * @param probabilities One row of scores.\n * @returns Name/score pairs, highest first.\n */\n readonly explain: (probabilities: readonly number[]) => { name: string; score: number }[];\n}\n\n/** Options for {@link loadEdgePackage}. */\nexport interface LoadEdgePackageOptions extends TabularPredictorOptions {\n /** Cache the model bytes for offline use. `true` by default. */\n readonly cache?: boolean | ModelCacheOptions;\n}\n\n/**\n * Read a package's manifest.\n *\n * Cheap: it is a few hundred bytes, so an app can check for a new version\n * without downloading a model it may already have.\n *\n * @example\n * ```ts\n * const manifest = await fetchEdgeManifest(\"/models/risk/\");\n * if (manifest.version !== localStorage.getItem(\"risk-version\")) {\n * // a new model was published\n * }\n * ```\n *\n * @param directoryUrl URL of the package directory, with or without a\n * trailing slash. A full URL to the manifest file also works.\n * @param requestInit `fetch` options.\n * @returns The parsed manifest.\n * @throws {@link ModelFetchError} when the manifest cannot be read, or when\n * its `schema_version` is newer than this reader understands — loading it\n * anyway would risk misreading the field that defines column order.\n */\nexport async function fetchEdgeManifest(\n directoryUrl: string,\n requestInit?: RequestInit,\n): Promise<EdgeManifest> {\n const url = manifestUrl(directoryUrl);\n let response: Response;\n try {\n response = await fetch(url, requestInit);\n } catch (error) {\n throw new ModelFetchError(`Could not read the manifest at ${url}`, {\n cause: error,\n });\n }\n if (!response.ok) {\n throw new ModelFetchError(\n `Could not read the manifest at ${url}: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as EdgeManifest;\n if (typeof manifest?.schema_version !== \"number\") {\n throw new ModelFetchError(`${url} is not an edge package manifest (no schema_version).`);\n }\n if (manifest.schema_version > SUPPORTED_MANIFEST_SCHEMA) {\n throw new ModelFetchError(\n `The manifest at ${url} uses schema_version ${manifest.schema_version}, ` +\n `and this SDK understands ${SUPPORTED_MANIFEST_SCHEMA}. Upgrade ` +\n \"tempest-react-sdk before serving this package.\",\n );\n }\n return manifest;\n}\n\n/**\n * Load a whole edge package: manifest, model, and the names to read it by.\n *\n * @example\n * ```ts\n * const pkg = await loadEdgePackage(\"/models/risk/\");\n *\n * console.log(pkg.featureNames); // [\"age\", \"income\", \"tenure\", \"score\", \"visits\"]\n *\n * const { probabilities } = await pkg.predictor.predict([[41, 5200, 3, 0.82, 12]]);\n * console.log(pkg.explain(probabilities[0]!)); // [{ name: \"approved\", score: 0.91 }, ...]\n * ```\n *\n * @param directoryUrl URL of the package directory.\n * @param options Predictor options plus caching.\n * @returns The loaded package.\n * @throws {@link ModelFetchError} when the manifest or model cannot be read.\n */\nexport async function loadEdgePackage(\n directoryUrl: string,\n options: LoadEdgePackageOptions = {},\n): Promise<LoadedEdgePackage> {\n const manifest = await fetchEdgeManifest(directoryUrl);\n const base = directoryUrl.endsWith(\"/\") ? directoryUrl : `${directoryUrl}/`;\n const modelUrl = `${base}${manifest.model.file}`;\n\n const cache = options.cache ?? true;\n const source =\n cache === false\n ? modelUrl\n : await fetchModelBytes(modelUrl, typeof cache === \"object\" ? cache : {});\n\n const predictor = await TabularPredictor.create(source, {\n providers: options.providers,\n warmup: options.warmup,\n sessionOptions: options.sessionOptions,\n });\n\n const classes = manifest.output.classes;\n return {\n manifest,\n predictor,\n featureNames: manifest.input.feature_names,\n classes,\n explain: (probabilities: readonly number[]) =>\n probabilities\n .map((score, index) => ({\n name: classes[index] ?? String(index),\n score,\n }))\n .sort((a, b) => b.score - a.score),\n };\n}\n\n/**\n * Resolve a directory URL to its manifest file.\n *\n * @param directoryUrl The package directory, or the manifest itself.\n * @returns The manifest URL.\n */\nfunction manifestUrl(directoryUrl: string): string {\n if (directoryUrl.endsWith(\".json\")) return directoryUrl;\n return directoryUrl.endsWith(\"/\")\n ? `${directoryUrl}${MANIFEST_FILENAME}`\n : `${directoryUrl}/${MANIFEST_FILENAME}`;\n}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,OADI,EAAa,SAAS,OAAO,IAAU,IACpC,EAAa,SAAS,GAAG,IAC1B,GAAG,IAAe,MAClB,GAAG,EAAa,GAAG;AAC7B"}
|
|
1
|
+
{"version":3,"file":"manifest.js","names":[],"sources":["../../src/tabular/manifest.ts"],"sourcesContent":["/**\n * Reading an edge package published by `tempest-fastapi-sdk`.\n *\n * `edge_pipeline` writes a directory — the graph, a gzipped copy, a drift\n * baseline and a `manifest.json` — and the browser is one of its two\n * intended consumers. The manifest is what turns a `.onnx` URL into\n * something a UI can use: the **column order** the model was trained on,\n * the class names behind `probabilities[2]`, and a version to compare\n * against what is already cached.\n *\n * That column order is the field worth loading a manifest for. A model fed\n * the right features in the wrong order answers confidently and wrongly,\n * and no runtime check catches it.\n *\n * The contract is pinned by `schema_version`. Unknown fields are ignored\n * rather than rejected, so a package written by a newer SDK still loads.\n */\n\nimport { fetchModelBytes, type ModelCacheOptions } from \"./cache\";\nimport { CompactPredictor } from \"./compact\";\nimport { ModelFetchError } from \"./exceptions\";\nimport { TabularPredictor } from \"./predictor\";\nimport type { FeatureRow, TabularPrediction, TabularPredictorOptions } from \"./types\";\n\n/** Manifest schema version this reader was written against. */\nexport const SUPPORTED_MANIFEST_SCHEMA = 1;\n\n/** Fixed filename inside a package directory. */\nexport const MANIFEST_FILENAME = \"manifest.json\";\n\n/** The graph file and how to check you got it whole. */\nexport interface ManifestModelFile {\n readonly file: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly gzip_file: string | null;\n readonly gzip_bytes: number | null;\n readonly opset: number;\n readonly dtype: string;\n}\n\n/** What the graph expects per row. */\nexport interface ManifestInput {\n readonly name: string;\n readonly features: number;\n /** Column order used at training time. */\n readonly feature_names: readonly string[];\n}\n\n/** What the graph answers. */\nexport interface ManifestOutput {\n readonly is_classifier: boolean;\n readonly label_output: string;\n readonly probability_output: string | null;\n /** Class labels in score-column order. */\n readonly classes: readonly string[];\n}\n\n/**\n * Where the packaged model came from, when it came from an existing\n * artifact.\n *\n * Present when the package was built with `edge_pipeline_from_pickle`: the\n * `.pkl` never reaches the browser (a pickle is a Python program, not\n * data), but its name and digest travel in the manifest, so a model\n * answering in a tab can be traced back to the file that produced it.\n */\nexport interface ManifestSource {\n readonly file: string;\n readonly kind: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly sklearn_version: string;\n readonly warnings: readonly string[];\n}\n\n/**\n * One file in the package a runtime can load.\n *\n * A package may carry the same model twice — as ONNX, which any runtime\n * reads at the cost of a 25.6 MB WebAssembly download, and as the compact\n * format, which needs no runtime. The list is what lets the browser pick\n * by what it already ships.\n */\nexport interface ManifestRuntime {\n readonly kind: \"onnx\" | \"compact\" | string;\n readonly file: string;\n readonly bytes: number;\n readonly gzip_file: string | null;\n readonly gzip_bytes: number | null;\n readonly sha256: string;\n}\n\n/** The package manifest, as written by `edge_pipeline`. */\nexport interface EdgeManifest {\n readonly schema_version: number;\n readonly name: string;\n readonly version: string;\n readonly created_at: string;\n readonly sdk_version: string;\n readonly estimator: string;\n readonly model: ManifestModelFile;\n readonly input: ManifestInput;\n readonly output: ManifestOutput;\n readonly verified: boolean | null;\n /** Every file a runtime can load. Absent on packages written before v0.194. */\n readonly runtimes?: readonly ManifestRuntime[];\n /** Absent on packages built straight from a fitted estimator. */\n readonly source?: ManifestSource;\n readonly baseline_file: string | null;\n readonly baseline_samples: number;\n}\n\n/** Which reader served the package. */\nexport type TabularRuntime = \"onnx\" | \"compact\";\n\n/** A package loaded and ready to answer. */\nexport interface LoadedEdgePackage {\n /** What was published. */\n readonly manifest: EdgeManifest;\n /** The running model, whichever runtime read it. */\n readonly predictor: PredictorLike;\n /** Which reader was used. */\n readonly runtime: TabularRuntime;\n /** Column order the rows must follow. */\n readonly featureNames: readonly string[];\n /** Class names behind each probability column. */\n readonly classes: readonly string[];\n /**\n * Map a prediction's scores onto class names.\n *\n * @param probabilities One row of scores.\n * @returns Name/score pairs, highest first.\n */\n readonly explain: (probabilities: readonly number[]) => { name: string; score: number }[];\n}\n\n/**\n * The shape both readers share.\n *\n * `TabularPredictor` (ONNX) and `CompactPredictor` (runtime-free) answer\n * with the same object, so an app can switch routes without touching a\n * line of its own code.\n */\nexport interface PredictorLike {\n predict(rows: readonly FeatureRow[]): Promise<TabularPrediction>;\n dispose(): Promise<void>;\n}\n\n/** Options for {@link loadEdgePackage}. */\nexport interface LoadEdgePackageOptions extends TabularPredictorOptions {\n /** Cache the model bytes for offline use. `true` by default. */\n readonly cache?: boolean | ModelCacheOptions;\n /**\n * Which reader to use.\n *\n * `\"auto\"` (the default) takes the compact form when the package has\n * one, because it answers without downloading a WebAssembly runtime.\n * Force `\"onnx\"` when the app already ships ONNX for something else —\n * then the runtime is already paid for and ONNX covers more estimators.\n */\n readonly runtime?: TabularRuntime | \"auto\";\n}\n\n/**\n * Read a package's manifest.\n *\n * Cheap: it is a few hundred bytes, so an app can check for a new version\n * without downloading a model it may already have.\n *\n * @example\n * ```ts\n * const manifest = await fetchEdgeManifest(\"/models/risk/\");\n * if (manifest.version !== localStorage.getItem(\"risk-version\")) {\n * // a new model was published\n * }\n * ```\n *\n * @param directoryUrl URL of the package directory, with or without a\n * trailing slash. A full URL to the manifest file also works.\n * @param requestInit `fetch` options.\n * @returns The parsed manifest.\n * @throws {@link ModelFetchError} when the manifest cannot be read, or when\n * its `schema_version` is newer than this reader understands — loading it\n * anyway would risk misreading the field that defines column order.\n */\nexport async function fetchEdgeManifest(\n directoryUrl: string,\n requestInit?: RequestInit,\n): Promise<EdgeManifest> {\n const url = manifestUrl(directoryUrl);\n let response: Response;\n try {\n response = await fetch(url, requestInit);\n } catch (error) {\n throw new ModelFetchError(`Could not read the manifest at ${url}`, {\n cause: error,\n });\n }\n if (!response.ok) {\n throw new ModelFetchError(\n `Could not read the manifest at ${url}: ${response.status} ${response.statusText}`,\n );\n }\n\n const manifest = (await response.json()) as EdgeManifest;\n if (typeof manifest?.schema_version !== \"number\") {\n throw new ModelFetchError(`${url} is not an edge package manifest (no schema_version).`);\n }\n if (manifest.schema_version > SUPPORTED_MANIFEST_SCHEMA) {\n throw new ModelFetchError(\n `The manifest at ${url} uses schema_version ${manifest.schema_version}, ` +\n `and this SDK understands ${SUPPORTED_MANIFEST_SCHEMA}. Upgrade ` +\n \"tempest-react-sdk before serving this package.\",\n );\n }\n return manifest;\n}\n\n/**\n * Load a whole edge package: manifest, model, and the names to read it by.\n *\n * @example\n * ```ts\n * const pkg = await loadEdgePackage(\"/models/risk/\");\n *\n * console.log(pkg.featureNames); // [\"age\", \"income\", \"tenure\", \"score\", \"visits\"]\n *\n * const { probabilities } = await pkg.predictor.predict([[41, 5200, 3, 0.82, 12]]);\n * console.log(pkg.explain(probabilities[0]!)); // [{ name: \"approved\", score: 0.91 }, ...]\n * ```\n *\n * @param directoryUrl URL of the package directory.\n * @param options Predictor options plus caching.\n * @returns The loaded package.\n * @throws {@link ModelFetchError} when the manifest or model cannot be read.\n */\nexport async function loadEdgePackage(\n directoryUrl: string,\n options: LoadEdgePackageOptions = {},\n): Promise<LoadedEdgePackage> {\n const manifest = await fetchEdgeManifest(directoryUrl);\n const base = directoryUrl.endsWith(\"/\") ? directoryUrl : `${directoryUrl}/`;\n const runtime = chooseRuntime(manifest, options.runtime ?? \"auto\");\n const file = fileFor(manifest, runtime);\n const modelUrl = `${base}${file}`;\n\n const cache = options.cache ?? true;\n const source =\n cache === false\n ? modelUrl\n : await fetchModelBytes(modelUrl, typeof cache === \"object\" ? cache : {});\n\n const predictor: PredictorLike =\n runtime === \"compact\"\n ? await CompactPredictor.create(source)\n : await TabularPredictor.create(source, {\n providers: options.providers,\n warmup: options.warmup,\n sessionOptions: options.sessionOptions,\n });\n\n const classes = manifest.output.classes;\n return {\n manifest,\n predictor,\n runtime,\n featureNames: manifest.input.feature_names,\n classes,\n explain: (probabilities: readonly number[]) =>\n probabilities\n .map((score, index) => ({\n name: classes[index] ?? String(index),\n score,\n }))\n .sort((a, b) => b.score - a.score),\n };\n}\n\n/**\n * Decide which reader serves this package.\n *\n * @param manifest The package manifest.\n * @param requested What the caller asked for.\n * @returns The runtime to use.\n * @throws {@link ModelFetchError} when the package does not carry the\n * requested form — asking for a compact model that was never written\n * should say so, not silently download 25 MB of WebAssembly instead.\n */\nfunction chooseRuntime(manifest: EdgeManifest, requested: TabularRuntime | \"auto\"): TabularRuntime {\n const available = manifest.runtimes ?? [];\n const hasCompact = available.some((entry) => entry.kind === \"compact\");\n\n if (requested === \"auto\") return hasCompact ? \"compact\" : \"onnx\";\n if (requested === \"compact\" && !hasCompact) {\n throw new ModelFetchError(\n `This package carries no compact model (${manifest.name} lists ` +\n `${available.map((entry) => entry.kind).join(\", \") || \"onnx\"}). ` +\n \"Re-export it with edge_pipeline(compact=True), or load it as ONNX.\",\n );\n }\n return requested;\n}\n\n/**\n * Find the file a runtime reads.\n *\n * @param manifest The package manifest.\n * @param runtime The chosen runtime.\n * @returns The filename inside the package directory.\n */\nfunction fileFor(manifest: EdgeManifest, runtime: TabularRuntime): string {\n const entry = (manifest.runtimes ?? []).find((item) => item.kind === runtime);\n return entry?.file ?? manifest.model.file;\n}\n\n/**\n * Resolve a directory URL to its manifest file.\n *\n * @param directoryUrl The package directory, or the manifest itself.\n * @returns The manifest URL.\n */\nfunction manifestUrl(directoryUrl: string): string {\n if (directoryUrl.endsWith(\".json\")) return directoryUrl;\n return directoryUrl.endsWith(\"/\")\n ? `${directoryUrl}${MANIFEST_FILENAME}`\n : `${directoryUrl}/${MANIFEST_FILENAME}`;\n}\n"],"mappings":";;;;;AAyBA,IAAa,IAA4B,GAG5B,IAAoB;AA8JjC,eAAsB,EAClB,GACA,GACqB;CACrB,IAAM,IAAM,EAAY,CAAY,GAChC;CACJ,IAAI;EACA,IAAW,MAAM,MAAM,GAAK,CAAW;CAC3C,SAAS,GAAO;EACZ,MAAM,IAAI,EAAgB,kCAAkC,KAAO,EAC/D,OAAO,EACX,CAAC;CACL;CACA,IAAI,CAAC,EAAS,IACV,MAAM,IAAI,EACN,kCAAkC,EAAI,IAAI,EAAS,OAAO,GAA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,EAAM,IAAI,CAAC,CAAC,KAAK,IAAI,KAAK,OAAO,sEAErE;CAEJ,OAAO;AACX;AASA,SAAS,EAAQ,GAAwB,GAAiC;CAEtE,QADe,EAAS,YAAY,CAAC,EAAA,CAAG,MAAM,MAAS,EAAK,SAAS,CAC9D,CAAA,EAAO,QAAQ,EAAS,MAAM;AACzC;AAQA,SAAS,EAAY,GAA8B;CAE/C,OADI,EAAa,SAAS,OAAO,IAAU,IACpC,EAAa,SAAS,GAAG,IAC1B,GAAG,IAAe,MAClB,GAAG,EAAa,GAAG;AAC7B"}
|
package/dist/tabular.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./tabular/assets.cjs"),t=require("./tabular/exceptions.cjs"),n=require("./tabular/cache.cjs"),r=require("./tabular/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./tabular/assets.cjs"),t=require("./tabular/exceptions.cjs"),n=require("./tabular/cache.cjs"),r=require("./tabular/compact.cjs"),i=require("./tabular/predictor.cjs"),a=require("./tabular/manifest.cjs"),o=require("./tabular/use-tabular-predictor.cjs");exports.CompactFormatError=t.CompactFormatError,exports.CompactPredictor=r.CompactPredictor,exports.DEFAULT_MODEL_CACHE=n.DEFAULT_MODEL_CACHE,exports.DEFAULT_TABULAR_PROVIDERS=i.DEFAULT_TABULAR_PROVIDERS,exports.FeatureShapeError=t.FeatureShapeError,exports.InferenceError=t.InferenceError,exports.MANIFEST_FILENAME=a.MANIFEST_FILENAME,exports.ModelFetchError=t.ModelFetchError,exports.ModelLoadError=t.ModelLoadError,exports.ORT_WASM_ASSETS=e.ORT_WASM_ASSETS,exports.SUPPORTED_COMPACT_SCHEMA=r.SUPPORTED_COMPACT_SCHEMA,exports.SUPPORTED_MANIFEST_SCHEMA=a.SUPPORTED_MANIFEST_SCHEMA,exports.TabularError=t.TabularError,exports.TabularPredictor=i.TabularPredictor,exports.UnsupportedGraphError=t.UnsupportedGraphError,exports.cacheModelBytes=n.cacheModelBytes,exports.clearModelCache=n.clearModelCache,exports.configureOrtAssets=e.configureOrtAssets,exports.fetchEdgeManifest=a.fetchEdgeManifest,exports.fetchModelBytes=n.fetchModelBytes,exports.isModelCached=n.isModelCached,exports.loadEdgePackage=a.loadEdgePackage,exports.ortAssetUrls=e.ortAssetUrls,exports.useTabularPredictor=o.useTabularPredictor;
|