tempest-react-sdk 0.32.1 → 0.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./exceptions.cjs");let n=require("onnxruntime-web");n=e.__toESM(n,1);var r=[`wasm`],i=[`label`,`class`,`variable`,`output`],a=[`probabilit`,`score`],o=1e6;function s(e,t){for(let n of t){let t=e.find(e=>e.toLowerCase().includes(n));if(t!==void 0)return t}return null}function c(e){let t=e.inputMetadata?.[0];if(t===void 0||t.isTensor!==!0)return null;let n=t.shape[1];return typeof n!=`number`||!Number.isInteger(n)||n<=0||n>o?null:n}function l(e){return typeof e==`bigint`?Number(e):typeof e==`number`?e:String(e)}function u(e){let n=e instanceof Error?e.message:String(e);return n.includes(`No Op registered`)?new t.UnsupportedGraphError(`This runtime build has no kernels for the model's operators. scikit-learn exports use the ai.onnx.ml domain, which is missing from the WebGPU build: import "onnxruntime-web", not "onnxruntime-web/webgpu". Original error: `+n,{cause:e}):new t.ModelLoadError(`Failed to load the model: ${n}`,{cause:e})}function d(e){let n=e instanceof Error?e.message:String(e);return n.includes(`non-tensor typed value`)||n.includes(`Can't access output tensor data`)?new t.InferenceError(`The model has a non-tensor output, which ONNX Runtime Web cannot read. A scikit-learn export made with ZipMap enabled returns a sequence of maps per row — re-export with export_sklearn_to_onnx, which disables it. Original error: ${n}`,{cause:e}):new t.InferenceError(`Inference failed: ${n}`,{cause:e})}var f=class e{session;info;constructor(e,t){this.session=e,this.info=t}static async create(t,i={}){let o=i.providers??r,l;try{l=await n.InferenceSession.create(t,{...i.sessionOptions??{},executionProviders:o})}catch(e){throw u(e)}let d=[...l.outputNames],f=s(d,a),m=d.find(e=>e!==f&&p(e))??d.find(e=>e!==f)??d[0],h=new e(l,{inputName:l.inputNames[0],numFeatures:c(l),outputNames:d,labelOutput:m,probabilityOutput:f,isClassifier:f!==null,providers:o});return i.warmup!==!1&&await h.warmUp(),h}async warmUp(){let e=this.info.numFeatures;if(e!==null)try{await this.predict([Array(e).fill(0)])}catch{}}async predict(e){if(!Array.isArray(e)||e.length===0)throw new t.FeatureShapeError(`predict() needs at least one row, shaped [[f1, f2, ...]].`);let r=e[0]?.length??0;if(r===0)throw new t.FeatureShapeError(`The first row has no feature values.`);let i=e.findIndex(e=>e.length!==r);if(i!==-1)throw new t.FeatureShapeError(`All rows must have the same width; row ${i} has ${e[i]?.length} values, expected ${r}.`);let a=this.info.numFeatures;if(a!==null&&r!==a)throw new t.FeatureShapeError(`The model expects ${a} features per row, got ${r}.`);let o=new Float32Array(e.length*r);for(let t=0;t<e.length;t+=1)o.set(e[t],t*r);let s=new n.Tensor(`float32`,o,[e.length,r]),c=performance.now(),u;try{u=await this.session.run({[this.info.inputName]:s})}catch(e){throw d(e)}let f=performance.now()-c,p=u[this.info.labelOutput];if(p?.data===void 0)throw new t.InferenceError(`The model produced no readable "${this.info.labelOutput}" output.`);let m=Array.from(p.data,l),h=[];if(this.info.probabilityOutput!==null){let t=u[this.info.probabilityOutput];if(t?.data!==void 0){let n=Array.from(t.data,Number),r=n.length/e.length;for(let t=0;t<e.length;t+=1)h.push(n.slice(t*r,(t+1)*r))}}return{labels:m,probabilities:h,numRows:e.length,ms:f}}async dispose(){await this.session.release?.()}};function p(e){let t=e.toLowerCase();return i.some(e=>t.includes(e))}exports.DEFAULT_TABULAR_PROVIDERS=r,exports.TabularPredictor=f;
1
+ const e=require("./assets.cjs"),t=require("./exceptions.cjs");async function n(){try{return await import(`onnxruntime-web`)}catch(e){throw new t.ModelLoadError(`The ONNX route needs the optional peer dependency: npm install onnxruntime-web. For a model with no runtime at all, export it with edge_pipeline(compact=True) and load it through CompactPredictor.`,{cause:e})}}var r=[`wasm`],i=[`label`,`class`,`variable`,`output`],a=[`probabilit`,`score`],o=1e6;function s(e,t){for(let n of t){let t=e.find(e=>e.toLowerCase().includes(n));if(t!==void 0)return t}return null}function c(e){let t=e.inputMetadata?.[0];if(t===void 0||t.isTensor!==!0)return null;let n=t.shape[1];return typeof n!=`number`||!Number.isInteger(n)||n<=0||n>o?null:n}function l(e){return typeof e==`bigint`?Number(e):typeof e==`number`?e:String(e)}function u(e){let n=e instanceof Error?e.message:String(e);return n.includes(`No Op registered`)?new t.UnsupportedGraphError(`This runtime build has no kernels for the model's operators. scikit-learn exports use the ai.onnx.ml domain, which is missing from the WebGPU build: import "onnxruntime-web", not "onnxruntime-web/webgpu". Original error: `+n,{cause:e}):new t.ModelLoadError(`Failed to load the model: ${n}`,{cause:e})}function d(e){let n=e instanceof Error?e.message:String(e);return n.includes(`non-tensor typed value`)||n.includes(`Can't access output tensor data`)?new t.InferenceError(`The model has a non-tensor output, which ONNX Runtime Web cannot read. A scikit-learn export made with ZipMap enabled returns a sequence of maps per row — re-export with export_sklearn_to_onnx, which disables it. Original error: ${n}`,{cause:e}):new t.InferenceError(`Inference failed: ${n}`,{cause:e})}var f=class i{runtime;session;info;constructor(e,t,n){this.runtime=e,this.session=t,this.info=n}static async create(t,o={}){let l=o.providers??r,d=await n(),f=e.configuredOrtAssetPath();f!==void 0&&(d.env.wasm.wasmPaths=f);let m;try{m=await d.InferenceSession.create(t,{...o.sessionOptions??{},executionProviders:l})}catch(e){throw u(e)}let h=[...m.outputNames],g=s(h,a),_=h.find(e=>e!==g&&p(e))??h.find(e=>e!==g)??h[0],v=new i(d,m,{inputName:m.inputNames[0],numFeatures:c(m),outputNames:h,labelOutput:_,probabilityOutput:g,isClassifier:g!==null,providers:l});return o.warmup!==!1&&await v.warmUp(),v}async warmUp(){let e=this.info.numFeatures;if(e!==null)try{await this.predict([Array(e).fill(0)])}catch{}}async predict(e){if(!Array.isArray(e)||e.length===0)throw new t.FeatureShapeError(`predict() needs at least one row, shaped [[f1, f2, ...]].`);let n=e[0]?.length??0;if(n===0)throw new t.FeatureShapeError(`The first row has no feature values.`);let r=e.findIndex(e=>e.length!==n);if(r!==-1)throw new t.FeatureShapeError(`All rows must have the same width; row ${r} has ${e[r]?.length} values, expected ${n}.`);let i=this.info.numFeatures;if(i!==null&&n!==i)throw new t.FeatureShapeError(`The model expects ${i} features per row, got ${n}.`);let a=new Float32Array(e.length*n);for(let t=0;t<e.length;t+=1)a.set(e[t],t*n);let o=new this.runtime.Tensor(`float32`,a,[e.length,n]),s=performance.now(),c;try{c=await this.session.run({[this.info.inputName]:o})}catch(e){throw d(e)}let u=performance.now()-s,f=c[this.info.labelOutput];if(f?.data===void 0)throw new t.InferenceError(`The model produced no readable "${this.info.labelOutput}" output.`);let p=Array.from(f.data,l),m=[];if(this.info.probabilityOutput!==null){let t=c[this.info.probabilityOutput];if(t?.data!==void 0){let n=Array.from(t.data,Number),r=n.length/e.length;for(let t=0;t<e.length;t+=1)m.push(n.slice(t*r,(t+1)*r))}}return{labels:p,probabilities:m,numRows:e.length,ms:u}}async dispose(){await this.session.release?.()}};function p(e){let t=e.toLowerCase();return i.some(e=>t.includes(e))}exports.DEFAULT_TABULAR_PROVIDERS=r,exports.TabularPredictor=f;
2
2
  //# sourceMappingURL=predictor.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"predictor.cjs","names":[],"sources":["../../src/tabular/predictor.ts"],"sourcesContent":["/**\n * Running a scikit-learn model in the browser, offline.\n *\n * The model file is produced by `tempest-fastapi-sdk`'s\n * `export_sklearn_to_onnx`. This is everything between that file and an\n * answer — the same glue the Python `OnnxPredictor` provides on a device,\n * with the browser's own traps handled:\n *\n * - **int64 labels arrive as `bigint`.** ONNX Runtime Web surfaces the\n * label tensor as a `BigInt64Array`, so a caller comparing `label === 1`\n * silently gets `false` and `JSON.stringify` throws. Labels are converted.\n * - **`ai.onnx.ml` needs the right build.** Measured: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly binary without those\n * operators, and session creation fails with `No Op registered for\n * TreeEnsembleClassifier`. That failure is translated into an error that\n * names the import.\n * - **Which output is which.** A classifier returns `label` and\n * `probabilities`; a regressor returns a single `variable`. Indexing by\n * position works until the day you deploy the other kind.\n */\n\nimport * as ort from \"onnxruntime-web\";\n\nimport {\n FeatureShapeError,\n InferenceError,\n ModelLoadError,\n UnsupportedGraphError,\n} from \"./exceptions\";\nimport type {\n FeatureRow,\n PredictedLabel,\n TabularModelSource,\n TabularPrediction,\n TabularPredictorInfo,\n TabularPredictorOptions,\n} from \"./types\";\n\n/**\n * Execution providers used when the caller does not choose.\n *\n * WebAssembly only, and deliberately: scikit-learn graphs are `ai.onnx.ml`\n * operators, which the WebGPU backend does not implement. There is no\n * speed left on the table here — a 10-tree forest predicts a row in about\n * 0.05 ms in Chromium.\n */\nexport const DEFAULT_TABULAR_PROVIDERS: readonly string[] = [\"wasm\"];\n\n/** Output names that indicate predicted classes rather than scores. */\nconst LABEL_HINTS = [\"label\", \"class\", \"variable\", \"output\"] as const;\n\n/** Output names that indicate class scores. */\nconst PROBABILITY_HINTS = [\"probabilit\", \"score\"] as const;\n\n/** Largest plausible feature count; anything above is a dynamic-dim sentinel. */\nconst MAX_DECLARED_FEATURES = 1_000_000;\n\n/**\n * Pick the first output whose name contains one of `hints`.\n *\n * @param names Graph output names.\n * @param hints Lowercase substrings to look for.\n * @returns The matching name, or `null`.\n */\nfunction matchOutput(names: readonly string[], hints: readonly string[]): string | null {\n for (const hint of hints) {\n const found = names.find((name) => name.toLowerCase().includes(hint));\n if (found !== undefined) return found;\n }\n return null;\n}\n\n/**\n * Read the declared feature count from the input metadata.\n *\n * A dynamic batch dimension is reported as a symbolic string or as an\n * out-of-range number (`4294967295` — an unsigned `-1`), so only a sane\n * positive integer in the second position is trusted.\n *\n * @param session The loaded session.\n * @returns The feature count, or `null` when the graph does not declare one.\n */\nfunction declaredFeatures(session: ort.InferenceSession): number | null {\n const metadata = session.inputMetadata?.[0];\n if (metadata === undefined || metadata.isTensor !== true) return null;\n const dimension = metadata.shape[1];\n if (typeof dimension !== \"number\") return null;\n if (!Number.isInteger(dimension) || dimension <= 0) return null;\n return dimension > MAX_DECLARED_FEATURES ? null : dimension;\n}\n\n/**\n * Convert one raw label value into a JS-friendly label.\n *\n * @param value A tensor element: `bigint` for int64, `number` for float,\n * `string` for a string-labelled classifier.\n * @returns The label as a number or string.\n */\nfunction toLabel(value: unknown): PredictedLabel {\n if (typeof value === \"bigint\") return Number(value);\n if (typeof value === \"number\") return value;\n return String(value);\n}\n\n/**\n * Translate a session-creation failure into an error naming its cause.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asLoadError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes(\"No Op registered\")) {\n return new UnsupportedGraphError(\n \"This runtime build has no kernels for the model's operators. \" +\n \"scikit-learn exports use the ai.onnx.ml domain, which is missing \" +\n 'from the WebGPU build: import \"onnxruntime-web\", not ' +\n '\"onnxruntime-web/webgpu\". Original error: ' +\n message,\n { cause: error },\n );\n }\n return new ModelLoadError(`Failed to load the model: ${message}`, { cause: error });\n}\n\n/**\n * Translate a run failure into an error naming its cause.\n *\n * Measured: an export made with skl2onnx's default (ZipMap enabled) has a\n * probability output that is a sequence of maps, and ONNX Runtime Web\n * refuses to read non-tensor values — `Reading data from non-tensor typed\n * value is not supported`. That message describes the runtime's limitation,\n * not the fix, so it is replaced by one that names the export flag.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asRunError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (\n message.includes(\"non-tensor typed value\") ||\n message.includes(\"Can't access output tensor data\")\n ) {\n return new InferenceError(\n \"The model has a non-tensor output, which ONNX Runtime Web cannot \" +\n \"read. A scikit-learn export made with ZipMap enabled returns a \" +\n \"sequence of maps per row — re-export with export_sklearn_to_onnx, \" +\n `which disables it. Original error: ${message}`,\n { cause: error },\n );\n }\n return new InferenceError(`Inference failed: ${message}`, { cause: error });\n}\n\n/**\n * A loaded tabular model, ready to answer.\n *\n * @example\n * ```ts\n * const predictor = await TabularPredictor.create(\"/models/classifier.onnx\");\n * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);\n * ```\n */\nexport class TabularPredictor {\n private constructor(\n private readonly session: ort.InferenceSession,\n /** What is loaded and how it is configured. */\n public readonly info: TabularPredictorInfo,\n ) {}\n\n /**\n * Load a model and describe its graph.\n *\n * @param source A URL string, or the model bytes (which is what an\n * offline app passes, having read them from the cache).\n * @param options Providers, warm-up and pass-through session options.\n * @throws {@link UnsupportedGraphError} when the runtime build lacks the\n * `ai.onnx.ml` operators — the WebGPU entry point does.\n * @throws {@link ModelLoadError} for any other load failure.\n */\n static async create(\n source: TabularModelSource,\n options: TabularPredictorOptions = {},\n ): Promise<TabularPredictor> {\n const providers = options.providers ?? DEFAULT_TABULAR_PROVIDERS;\n let session: ort.InferenceSession;\n try {\n session = await ort.InferenceSession.create(source as never, {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n });\n } catch (error) {\n throw asLoadError(error);\n }\n\n const outputNames = [...session.outputNames];\n const probabilityOutput = matchOutput(outputNames, PROBABILITY_HINTS);\n const labelOutput =\n outputNames.find((name) => name !== probabilityOutput && isLabelName(name)) ??\n outputNames.find((name) => name !== probabilityOutput) ??\n (outputNames[0] as string);\n\n const predictor = new TabularPredictor(session, {\n inputName: session.inputNames[0] as string,\n numFeatures: declaredFeatures(session),\n outputNames,\n labelOutput,\n probabilityOutput,\n isClassifier: probabilityOutput !== null,\n providers,\n });\n\n if (options.warmup !== false) await predictor.warmUp();\n return predictor;\n }\n\n /**\n * Run one throwaway inference so the first real call is not the slow one.\n *\n * Skipped when the graph does not declare a feature count, since there\n * is no shape to synthesise. Failures are swallowed: a warm-up that\n * cannot run is not a reason to refuse to serve.\n */\n async warmUp(): Promise<void> {\n const features = this.info.numFeatures;\n if (features === null) return;\n try {\n await this.predict([new Array<number>(features).fill(0)]);\n } catch {\n /* a failed warm-up must not prevent serving */\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 produces them, and the\n * call's duration.\n * @throws {@link FeatureShapeError} when the batch is empty, ragged, or\n * the wrong width — checked here so the failure names the mismatch\n * instead of surfacing as an opaque runtime error.\n * @throws {@link InferenceError} when the session runs but its outputs\n * cannot be read.\n */\n async predict(rows: readonly FeatureRow[]): Promise<TabularPrediction> {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new FeatureShapeError(\n \"predict() needs at least one row, shaped [[f1, f2, ...]].\",\n );\n }\n const width = rows[0]?.length ?? 0;\n if (width === 0) {\n throw new FeatureShapeError(\"The first row has no feature values.\");\n }\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 const expected = this.info.numFeatures;\n if (expected !== null && width !== expected) {\n throw new FeatureShapeError(\n `The model expects ${expected} features per row, got ${width}.`,\n );\n }\n\n const flat = new Float32Array(rows.length * width);\n for (let index = 0; index < rows.length; index += 1) {\n flat.set(rows[index] as number[], index * width);\n }\n const tensor = new ort.Tensor(\"float32\", flat, [rows.length, width]);\n\n const started = performance.now();\n let outputs: ort.InferenceSession.OnnxValueMapType;\n try {\n outputs = await this.session.run({ [this.info.inputName]: tensor });\n } catch (error) {\n throw asRunError(error);\n }\n const ms = performance.now() - started;\n\n const labelTensor = outputs[this.info.labelOutput];\n if (labelTensor?.data === undefined) {\n throw new InferenceError(\n `The model produced no readable \"${this.info.labelOutput}\" output.`,\n );\n }\n\n const labels: PredictedLabel[] = Array.from(\n labelTensor.data as ArrayLike<unknown>,\n toLabel,\n );\n\n const probabilities: number[][] = [];\n if (this.info.probabilityOutput !== null) {\n const scores = outputs[this.info.probabilityOutput];\n if (scores?.data !== undefined) {\n const values = Array.from(scores.data as ArrayLike<number>, Number);\n const classes = values.length / rows.length;\n for (let index = 0; index < rows.length; index += 1) {\n probabilities.push(values.slice(index * classes, (index + 1) * classes));\n }\n }\n }\n\n return { labels, probabilities, numRows: rows.length, ms };\n }\n\n /**\n * Release the session's memory.\n *\n * Worth calling on a route that swaps models: the WebAssembly heap does\n * not shrink on garbage collection alone.\n */\n async dispose(): Promise<void> {\n await this.session.release?.();\n }\n}\n\n/**\n * Whether an output name looks like a label rather than a score.\n *\n * @param name The graph output name.\n * @returns `true` when the name matches a known label convention.\n */\nfunction isLabelName(name: string): boolean {\n const lowered = name.toLowerCase();\n return LABEL_HINTS.some((hint) => lowered.includes(hint));\n}\n"],"mappings":"qIA8CA,IAAa,EAA+C,CAAC,MAAM,EAG7D,EAAc,CAAC,QAAS,QAAS,WAAY,QAAQ,EAGrD,EAAoB,CAAC,aAAc,OAAO,EAG1C,EAAwB,IAS9B,SAAS,EAAY,EAA0B,EAAyC,CACpF,IAAK,IAAM,KAAQ,EAAO,CACtB,IAAM,EAAQ,EAAM,KAAM,GAAS,EAAK,YAAY,CAAC,CAAC,SAAS,CAAI,CAAC,EACpE,GAAI,IAAU,IAAA,GAAW,OAAO,CACpC,CACA,OAAO,IACX,CAYA,SAAS,EAAiB,EAA8C,CACpE,IAAM,EAAW,EAAQ,gBAAgB,GACzC,GAAI,IAAa,IAAA,IAAa,EAAS,WAAa,GAAM,OAAO,KACjE,IAAM,EAAY,EAAS,MAAM,GAGjC,OAFI,OAAO,GAAc,UACrB,CAAC,OAAO,UAAU,CAAS,GAAK,GAAa,GAC1C,EAAY,EADwC,KACT,CACtD,CASA,SAAS,EAAQ,EAAgC,CAG7C,OAFI,OAAO,GAAU,SAAiB,OAAO,CAAK,EAC9C,OAAO,GAAU,SAAiB,EAC/B,OAAO,CAAK,CACvB,CAQA,SAAS,EAAY,EAAuB,CACxC,IAAM,EAAU,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAWrE,OAVI,EAAQ,SAAS,kBAAkB,EAC5B,IAAI,EAAA,sBACP,gOAII,EACJ,CAAE,MAAO,CAAM,CACnB,EAEG,I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KAAK,KAAK,mBACjC,GAAI,GAAQ,OAAS,IAAA,GAAW,CAC5B,IAAM,EAAS,MAAM,KAAK,EAAO,KAA2B,MAAM,EAC5D,EAAU,EAAO,OAAS,EAAK,OACrC,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAK,OAAQ,GAAS,EAC9C,EAAc,KAAK,EAAO,MAAM,EAAQ,GAAU,EAAQ,GAAK,CAAO,CAAC,CAE/E,CACJ,CAEA,MAAO,CAAE,SAAQ,gBAAe,QAAS,EAAK,OAAQ,IAAG,CAC7D,CAQA,MAAM,SAAyB,CAC3B,MAAM,KAAK,QAAQ,UAAU,CACjC,CACJ,EAQA,SAAS,EAAY,EAAuB,CACxC,IAAM,EAAU,EAAK,YAAY,EACjC,OAAO,EAAY,KAAM,GAAS,EAAQ,SAAS,CAAI,CAAC,CAC5D"}
1
+ {"version":3,"file":"predictor.cjs","names":[],"sources":["../../src/tabular/predictor.ts"],"sourcesContent":["/**\n * Running a scikit-learn model in the browser, offline.\n *\n * The model file is produced by `tempest-fastapi-sdk`'s\n * `export_sklearn_to_onnx`. This is everything between that file and an\n * answer — the same glue the Python `OnnxPredictor` provides on a device,\n * with the browser's own traps handled:\n *\n * - **int64 labels arrive as `bigint`.** ONNX Runtime Web surfaces the\n * label tensor as a `BigInt64Array`, so a caller comparing `label === 1`\n * silently gets `false` and `JSON.stringify` throws. Labels are converted.\n * - **`ai.onnx.ml` needs the right build.** Measured: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly binary without those\n * operators, and session creation fails with `No Op registered for\n * TreeEnsembleClassifier`. That failure is translated into an error that\n * names the import.\n * - **Which output is which.** A classifier returns `label` and\n * `probabilities`; a regressor returns a single `variable`. Indexing by\n * position works until the day you deploy the other kind.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { configuredOrtAssetPath } from \"./assets\";\nimport {\n FeatureShapeError,\n InferenceError,\n ModelLoadError,\n UnsupportedGraphError,\n} from \"./exceptions\";\nimport type {\n FeatureRow,\n PredictedLabel,\n TabularModelSource,\n TabularPrediction,\n TabularPredictorInfo,\n TabularPredictorOptions,\n} from \"./types\";\n\n/**\n * Import ONNX Runtime Web, only when a model is actually being loaded.\n *\n * Static import would make every consumer of this subpath install the peer,\n * including apps that only ever touch `CompactPredictor` — whose whole\n * point is not needing a runtime. Found by installing the published\n * package into an empty project, which is the only place the difference\n * shows.\n *\n * @returns The runtime module.\n * @throws {@link ModelLoadError} when the peer is not installed, naming it.\n */\nasync function loadRuntime(): Promise<typeof ort> {\n try {\n return (await import(\"onnxruntime-web\")) as typeof ort;\n } catch (error) {\n throw new ModelLoadError(\n \"The ONNX route needs the optional peer dependency: \" +\n \"npm install onnxruntime-web. For a model with no runtime at \" +\n \"all, export it with edge_pipeline(compact=True) and load it \" +\n \"through CompactPredictor.\",\n { cause: error },\n );\n }\n}\n\n/**\n * Execution providers used when the caller does not choose.\n *\n * WebAssembly only, and deliberately: scikit-learn graphs are `ai.onnx.ml`\n * operators, which the WebGPU backend does not implement. There is no\n * speed left on the table here — a 10-tree forest predicts a row in about\n * 0.05 ms in Chromium.\n */\nexport const DEFAULT_TABULAR_PROVIDERS: readonly string[] = [\"wasm\"];\n\n/** Output names that indicate predicted classes rather than scores. */\nconst LABEL_HINTS = [\"label\", \"class\", \"variable\", \"output\"] as const;\n\n/** Output names that indicate class scores. */\nconst PROBABILITY_HINTS = [\"probabilit\", \"score\"] as const;\n\n/** Largest plausible feature count; anything above is a dynamic-dim sentinel. */\nconst MAX_DECLARED_FEATURES = 1_000_000;\n\n/**\n * Pick the first output whose name contains one of `hints`.\n *\n * @param names Graph output names.\n * @param hints Lowercase substrings to look for.\n * @returns The matching name, or `null`.\n */\nfunction matchOutput(names: readonly string[], hints: readonly string[]): string | null {\n for (const hint of hints) {\n const found = names.find((name) => name.toLowerCase().includes(hint));\n if (found !== undefined) return found;\n }\n return null;\n}\n\n/**\n * Read the declared feature count from the input metadata.\n *\n * A dynamic batch dimension is reported as a symbolic string or as an\n * out-of-range number (`4294967295` — an unsigned `-1`), so only a sane\n * positive integer in the second position is trusted.\n *\n * @param session The loaded session.\n * @returns The feature count, or `null` when the graph does not declare one.\n */\nfunction declaredFeatures(session: ort.InferenceSession): number | null {\n const metadata = session.inputMetadata?.[0];\n if (metadata === undefined || metadata.isTensor !== true) return null;\n const dimension = metadata.shape[1];\n if (typeof dimension !== \"number\") return null;\n if (!Number.isInteger(dimension) || dimension <= 0) return null;\n return dimension > MAX_DECLARED_FEATURES ? null : dimension;\n}\n\n/**\n * Convert one raw label value into a JS-friendly label.\n *\n * @param value A tensor element: `bigint` for int64, `number` for float,\n * `string` for a string-labelled classifier.\n * @returns The label as a number or string.\n */\nfunction toLabel(value: unknown): PredictedLabel {\n if (typeof value === \"bigint\") return Number(value);\n if (typeof value === \"number\") return value;\n return String(value);\n}\n\n/**\n * Translate a session-creation failure into an error naming its cause.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asLoadError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes(\"No Op registered\")) {\n return new UnsupportedGraphError(\n \"This runtime build has no kernels for the model's operators. \" +\n \"scikit-learn exports use the ai.onnx.ml domain, which is missing \" +\n 'from the WebGPU build: import \"onnxruntime-web\", not ' +\n '\"onnxruntime-web/webgpu\". Original error: ' +\n message,\n { cause: error },\n );\n }\n return new ModelLoadError(`Failed to load the model: ${message}`, { cause: error });\n}\n\n/**\n * Translate a run failure into an error naming its cause.\n *\n * Measured: an export made with skl2onnx's default (ZipMap enabled) has a\n * probability output that is a sequence of maps, and ONNX Runtime Web\n * refuses to read non-tensor values — `Reading data from non-tensor typed\n * value is not supported`. That message describes the runtime's limitation,\n * not the fix, so it is replaced by one that names the export flag.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asRunError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (\n message.includes(\"non-tensor typed value\") ||\n message.includes(\"Can't access output tensor data\")\n ) {\n return new InferenceError(\n \"The model has a non-tensor output, which ONNX Runtime Web cannot \" +\n \"read. A scikit-learn export made with ZipMap enabled returns a \" +\n \"sequence of maps per row — re-export with export_sklearn_to_onnx, \" +\n `which disables it. Original error: ${message}`,\n { cause: error },\n );\n }\n return new InferenceError(`Inference failed: ${message}`, { cause: error });\n}\n\n/**\n * A loaded tabular model, ready to answer.\n *\n * @example\n * ```ts\n * const predictor = await TabularPredictor.create(\"/models/classifier.onnx\");\n * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);\n * ```\n */\nexport class TabularPredictor {\n private constructor(\n private readonly runtime: typeof ort,\n private readonly session: ort.InferenceSession,\n /** What is loaded and how it is configured. */\n public readonly info: TabularPredictorInfo,\n ) {}\n\n /**\n * Load a model and describe its graph.\n *\n * @param source A URL string, or the model bytes (which is what an\n * offline app passes, having read them from the cache).\n * @param options Providers, warm-up and pass-through session options.\n * @throws {@link UnsupportedGraphError} when the runtime build lacks the\n * `ai.onnx.ml` operators — the WebGPU entry point does.\n * @throws {@link ModelLoadError} for any other load failure.\n */\n static async create(\n source: TabularModelSource,\n options: TabularPredictorOptions = {},\n ): Promise<TabularPredictor> {\n const providers = options.providers ?? DEFAULT_TABULAR_PROVIDERS;\n const runtime = await loadRuntime();\n const assets = configuredOrtAssetPath();\n if (assets !== undefined) runtime.env.wasm.wasmPaths = assets;\n\n let session: ort.InferenceSession;\n try {\n session = await runtime.InferenceSession.create(source as never, {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n });\n } catch (error) {\n throw asLoadError(error);\n }\n\n const outputNames = [...session.outputNames];\n const probabilityOutput = matchOutput(outputNames, PROBABILITY_HINTS);\n const labelOutput =\n outputNames.find((name) => name !== probabilityOutput && isLabelName(name)) ??\n outputNames.find((name) => name !== probabilityOutput) ??\n (outputNames[0] as string);\n\n const predictor = new TabularPredictor(runtime, session, {\n inputName: session.inputNames[0] as string,\n numFeatures: declaredFeatures(session),\n outputNames,\n labelOutput,\n probabilityOutput,\n isClassifier: probabilityOutput !== null,\n providers,\n });\n\n if (options.warmup !== false) await predictor.warmUp();\n return predictor;\n }\n\n /**\n * Run one throwaway inference so the first real call is not the slow one.\n *\n * Skipped when the graph does not declare a feature count, since there\n * is no shape to synthesise. Failures are swallowed: a warm-up that\n * cannot run is not a reason to refuse to serve.\n */\n async warmUp(): Promise<void> {\n const features = this.info.numFeatures;\n if (features === null) return;\n try {\n await this.predict([new Array<number>(features).fill(0)]);\n } catch {\n /* a failed warm-up must not prevent serving */\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 produces them, and the\n * call's duration.\n * @throws {@link FeatureShapeError} when the batch is empty, ragged, or\n * the wrong width — checked here so the failure names the mismatch\n * instead of surfacing as an opaque runtime error.\n * @throws {@link InferenceError} when the session runs but its outputs\n * cannot be read.\n */\n async predict(rows: readonly FeatureRow[]): Promise<TabularPrediction> {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new FeatureShapeError(\n \"predict() needs at least one row, shaped [[f1, f2, ...]].\",\n );\n }\n const width = rows[0]?.length ?? 0;\n if (width === 0) {\n throw new FeatureShapeError(\"The first row has no feature values.\");\n }\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 const expected = this.info.numFeatures;\n if (expected !== null && width !== expected) {\n throw new FeatureShapeError(\n `The model expects ${expected} features per row, got ${width}.`,\n );\n }\n\n const flat = new Float32Array(rows.length * width);\n for (let index = 0; index < rows.length; index += 1) {\n flat.set(rows[index] as number[], index * width);\n }\n const tensor = new this.runtime.Tensor(\"float32\", flat, [rows.length, width]);\n\n const started = performance.now();\n let outputs: ort.InferenceSession.OnnxValueMapType;\n try {\n outputs = await this.session.run({ [this.info.inputName]: tensor });\n } catch (error) {\n throw asRunError(error);\n }\n const ms = performance.now() - started;\n\n const labelTensor = outputs[this.info.labelOutput];\n if (labelTensor?.data === undefined) {\n throw new InferenceError(\n `The model produced no readable \"${this.info.labelOutput}\" output.`,\n );\n }\n\n const labels: PredictedLabel[] = Array.from(\n labelTensor.data as ArrayLike<unknown>,\n toLabel,\n );\n\n const probabilities: number[][] = [];\n if (this.info.probabilityOutput !== null) {\n const scores = outputs[this.info.probabilityOutput];\n if (scores?.data !== undefined) {\n const values = Array.from(scores.data as ArrayLike<number>, Number);\n const classes = values.length / rows.length;\n for (let index = 0; index < rows.length; index += 1) {\n probabilities.push(values.slice(index * classes, (index + 1) * classes));\n }\n }\n }\n\n return { labels, probabilities, numRows: rows.length, ms };\n }\n\n /**\n * Release the session's memory.\n *\n * Worth calling on a route that swaps models: the WebAssembly heap does\n * not shrink on garbage collection alone.\n */\n async dispose(): Promise<void> {\n await this.session.release?.();\n }\n}\n\n/**\n * Whether an output name looks like a label rather than a score.\n *\n * @param name The graph output name.\n * @returns `true` when the name matches a known label convention.\n */\nfunction isLabelName(name: string): boolean {\n const lowered = name.toLowerCase();\n return LABEL_HINTS.some((hint) => lowered.includes(hint));\n}\n"],"mappings":"8DAmDA,eAAe,GAAmC,CAC9C,GAAI,CACA,OAAQ,MAAM,OAAO,kBACzB,OAAS,EAAO,CACZ,MAAM,IAAI,EAAA,eACN,uMAIA,CAAE,MAAO,CAAM,CACnB,CACJ,CACJ,CAUA,IAAa,EAA+C,CAAC,MAAM,EAG7D,EAAc,CAAC,QAAS,QAAS,WAAY,QAAQ,EAGrD,EAAoB,CAAC,aAAc,OAAO,EAG1C,EAAwB,IAS9B,SAAS,EAAY,EAA0B,EAAyC,CACpF,IAAK,IAAM,KAAQ,EAAO,CACtB,IAAM,EAAQ,EAAM,KAAM,GAAS,EAAK,YAAY,CAAC,CAAC,SAAS,CAAI,CAAC,EACpE,GAAI,IAAU,IAAA,GAAW,OAAO,CACpC,CAC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
@@ -1,62 +1,72 @@
1
- import { FeatureShapeError as e, InferenceError as t, ModelLoadError as n, UnsupportedGraphError as r } from "./exceptions.js";
2
- import * as i from "onnxruntime-web";
1
+ import { configuredOrtAssetPath as e } from "./assets.js";
2
+ import { FeatureShapeError as t, InferenceError as n, ModelLoadError as r, UnsupportedGraphError as i } from "./exceptions.js";
3
3
  //#region src/tabular/predictor.ts
4
- var a = ["wasm"], o = [
4
+ async function a() {
5
+ try {
6
+ return await import("onnxruntime-web");
7
+ } catch (e) {
8
+ throw new r("The ONNX route needs the optional peer dependency: npm install onnxruntime-web. For a model with no runtime at all, export it with edge_pipeline(compact=True) and load it through CompactPredictor.", { cause: e });
9
+ }
10
+ }
11
+ var o = ["wasm"], s = [
5
12
  "label",
6
13
  "class",
7
14
  "variable",
8
15
  "output"
9
- ], s = ["probabilit", "score"], c = 1e6;
10
- function l(e, t) {
16
+ ], c = ["probabilit", "score"], l = 1e6;
17
+ function u(e, t) {
11
18
  for (let n of t) {
12
19
  let t = e.find((e) => e.toLowerCase().includes(n));
13
20
  if (t !== void 0) return t;
14
21
  }
15
22
  return null;
16
23
  }
17
- function u(e) {
24
+ function d(e) {
18
25
  let t = e.inputMetadata?.[0];
19
26
  if (t === void 0 || t.isTensor !== !0) return null;
20
27
  let n = t.shape[1];
21
- return typeof n != "number" || !Number.isInteger(n) || n <= 0 || n > c ? null : n;
28
+ return typeof n != "number" || !Number.isInteger(n) || n <= 0 || n > l ? null : n;
22
29
  }
23
- function d(e) {
30
+ function f(e) {
24
31
  return typeof e == "bigint" ? Number(e) : typeof e == "number" ? e : String(e);
25
32
  }
26
- function f(e) {
33
+ function p(e) {
27
34
  let t = e instanceof Error ? e.message : String(e);
28
- return t.includes("No Op registered") ? new r("This runtime build has no kernels for the model's operators. scikit-learn exports use the ai.onnx.ml domain, which is missing from the WebGPU build: import \"onnxruntime-web\", not \"onnxruntime-web/webgpu\". Original error: " + t, { cause: e }) : new n(`Failed to load the model: ${t}`, { cause: e });
35
+ return t.includes("No Op registered") ? new i("This runtime build has no kernels for the model's operators. scikit-learn exports use the ai.onnx.ml domain, which is missing from the WebGPU build: import \"onnxruntime-web\", not \"onnxruntime-web/webgpu\". Original error: " + t, { cause: e }) : new r(`Failed to load the model: ${t}`, { cause: e });
29
36
  }
30
- function p(e) {
31
- let n = e instanceof Error ? e.message : String(e);
32
- return n.includes("non-tensor typed value") || n.includes("Can't access output tensor data") ? new t(`The model has a non-tensor output, which ONNX Runtime Web cannot read. A scikit-learn export made with ZipMap enabled returns a sequence of maps per row — re-export with export_sklearn_to_onnx, which disables it. Original error: ${n}`, { cause: e }) : new t(`Inference failed: ${n}`, { cause: e });
37
+ function m(e) {
38
+ let t = e instanceof Error ? e.message : String(e);
39
+ return t.includes("non-tensor typed value") || t.includes("Can't access output tensor data") ? new n(`The model has a non-tensor output, which ONNX Runtime Web cannot read. A scikit-learn export made with ZipMap enabled returns a sequence of maps per row — re-export with export_sklearn_to_onnx, which disables it. Original error: ${t}`, { cause: e }) : new n(`Inference failed: ${t}`, { cause: e });
33
40
  }
34
- var m = class n {
41
+ var h = class r {
42
+ runtime;
35
43
  session;
36
44
  info;
37
- constructor(e, t) {
38
- this.session = e, this.info = t;
45
+ constructor(e, t, n) {
46
+ this.runtime = e, this.session = t, this.info = n;
39
47
  }
40
- static async create(e, t = {}) {
41
- let r = t.providers ?? a, o;
48
+ static async create(t, n = {}) {
49
+ let i = n.providers ?? o, s = await a(), l = e();
50
+ l !== void 0 && (s.env.wasm.wasmPaths = l);
51
+ let f;
42
52
  try {
43
- o = await i.InferenceSession.create(e, {
44
- ...t.sessionOptions ?? {},
45
- executionProviders: r
53
+ f = await s.InferenceSession.create(t, {
54
+ ...n.sessionOptions ?? {},
55
+ executionProviders: i
46
56
  });
47
57
  } catch (e) {
48
- throw f(e);
58
+ throw p(e);
49
59
  }
50
- let c = [...o.outputNames], d = l(c, s), p = c.find((e) => e !== d && h(e)) ?? c.find((e) => e !== d) ?? c[0], m = new n(o, {
51
- inputName: o.inputNames[0],
52
- numFeatures: u(o),
53
- outputNames: c,
54
- labelOutput: p,
55
- probabilityOutput: d,
56
- isClassifier: d !== null,
57
- providers: r
60
+ let m = [...f.outputNames], h = u(m, c), _ = m.find((e) => e !== h && g(e)) ?? m.find((e) => e !== h) ?? m[0], v = new r(s, f, {
61
+ inputName: f.inputNames[0],
62
+ numFeatures: d(f),
63
+ outputNames: m,
64
+ labelOutput: _,
65
+ probabilityOutput: h,
66
+ isClassifier: h !== null,
67
+ providers: i
58
68
  });
59
- return t.warmup !== !1 && await m.warmUp(), m;
69
+ return n.warmup !== !1 && await v.warmUp(), v;
60
70
  }
61
71
  async warmUp() {
62
72
  let e = this.info.numFeatures;
@@ -64,48 +74,48 @@ var m = class n {
64
74
  await this.predict([Array(e).fill(0)]);
65
75
  } catch {}
66
76
  }
67
- async predict(n) {
68
- if (!Array.isArray(n) || n.length === 0) throw new e("predict() needs at least one row, shaped [[f1, f2, ...]].");
69
- let r = n[0]?.length ?? 0;
70
- if (r === 0) throw new e("The first row has no feature values.");
71
- let a = n.findIndex((e) => e.length !== r);
72
- if (a !== -1) throw new e(`All rows must have the same width; row ${a} has ${n[a]?.length} values, expected ${r}.`);
73
- let o = this.info.numFeatures;
74
- if (o !== null && r !== o) throw new e(`The model expects ${o} features per row, got ${r}.`);
75
- let s = new Float32Array(n.length * r);
76
- for (let e = 0; e < n.length; e += 1) s.set(n[e], e * r);
77
- let c = new i.Tensor("float32", s, [n.length, r]), l = performance.now(), u;
77
+ async predict(e) {
78
+ if (!Array.isArray(e) || e.length === 0) throw new t("predict() needs at least one row, shaped [[f1, f2, ...]].");
79
+ let r = e[0]?.length ?? 0;
80
+ if (r === 0) throw new t("The first row has no feature values.");
81
+ let i = e.findIndex((e) => e.length !== r);
82
+ if (i !== -1) throw new t(`All rows must have the same width; row ${i} has ${e[i]?.length} values, expected ${r}.`);
83
+ let a = this.info.numFeatures;
84
+ if (a !== null && r !== a) throw new t(`The model expects ${a} features per row, got ${r}.`);
85
+ let o = new Float32Array(e.length * r);
86
+ for (let t = 0; t < e.length; t += 1) o.set(e[t], t * r);
87
+ let s = new this.runtime.Tensor("float32", o, [e.length, r]), c = performance.now(), l;
78
88
  try {
79
- u = await this.session.run({ [this.info.inputName]: c });
89
+ l = await this.session.run({ [this.info.inputName]: s });
80
90
  } catch (e) {
81
- throw p(e);
91
+ throw m(e);
82
92
  }
83
- let f = performance.now() - l, m = u[this.info.labelOutput];
84
- if (m?.data === void 0) throw new t(`The model produced no readable "${this.info.labelOutput}" output.`);
85
- let h = Array.from(m.data, d), g = [];
93
+ let u = performance.now() - c, d = l[this.info.labelOutput];
94
+ if (d?.data === void 0) throw new n(`The model produced no readable "${this.info.labelOutput}" output.`);
95
+ let p = Array.from(d.data, f), h = [];
86
96
  if (this.info.probabilityOutput !== null) {
87
- let e = u[this.info.probabilityOutput];
88
- if (e?.data !== void 0) {
89
- let t = Array.from(e.data, Number), r = t.length / n.length;
90
- for (let e = 0; e < n.length; e += 1) g.push(t.slice(e * r, (e + 1) * r));
97
+ let t = l[this.info.probabilityOutput];
98
+ if (t?.data !== void 0) {
99
+ let n = Array.from(t.data, Number), r = n.length / e.length;
100
+ for (let t = 0; t < e.length; t += 1) h.push(n.slice(t * r, (t + 1) * r));
91
101
  }
92
102
  }
93
103
  return {
94
- labels: h,
95
- probabilities: g,
96
- numRows: n.length,
97
- ms: f
104
+ labels: p,
105
+ probabilities: h,
106
+ numRows: e.length,
107
+ ms: u
98
108
  };
99
109
  }
100
110
  async dispose() {
101
111
  await this.session.release?.();
102
112
  }
103
113
  };
104
- function h(e) {
114
+ function g(e) {
105
115
  let t = e.toLowerCase();
106
- return o.some((e) => t.includes(e));
116
+ return s.some((e) => t.includes(e));
107
117
  }
108
118
  //#endregion
109
- export { a as DEFAULT_TABULAR_PROVIDERS, m as TabularPredictor };
119
+ export { o as DEFAULT_TABULAR_PROVIDERS, h as TabularPredictor };
110
120
 
111
121
  //# sourceMappingURL=predictor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"predictor.js","names":[],"sources":["../../src/tabular/predictor.ts"],"sourcesContent":["/**\n * Running a scikit-learn model in the browser, offline.\n *\n * The model file is produced by `tempest-fastapi-sdk`'s\n * `export_sklearn_to_onnx`. This is everything between that file and an\n * answer — the same glue the Python `OnnxPredictor` provides on a device,\n * with the browser's own traps handled:\n *\n * - **int64 labels arrive as `bigint`.** ONNX Runtime Web surfaces the\n * label tensor as a `BigInt64Array`, so a caller comparing `label === 1`\n * silently gets `false` and `JSON.stringify` throws. Labels are converted.\n * - **`ai.onnx.ml` needs the right build.** Measured: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly binary without those\n * operators, and session creation fails with `No Op registered for\n * TreeEnsembleClassifier`. That failure is translated into an error that\n * names the import.\n * - **Which output is which.** A classifier returns `label` and\n * `probabilities`; a regressor returns a single `variable`. Indexing by\n * position works until the day you deploy the other kind.\n */\n\nimport * as ort from \"onnxruntime-web\";\n\nimport {\n FeatureShapeError,\n InferenceError,\n ModelLoadError,\n UnsupportedGraphError,\n} from \"./exceptions\";\nimport type {\n FeatureRow,\n PredictedLabel,\n TabularModelSource,\n TabularPrediction,\n TabularPredictorInfo,\n TabularPredictorOptions,\n} from \"./types\";\n\n/**\n * Execution providers used when the caller does not choose.\n *\n * WebAssembly only, and deliberately: scikit-learn graphs are `ai.onnx.ml`\n * operators, which the WebGPU backend does not implement. There is no\n * speed left on the table here — a 10-tree forest predicts a row in about\n * 0.05 ms in Chromium.\n */\nexport const DEFAULT_TABULAR_PROVIDERS: readonly string[] = [\"wasm\"];\n\n/** Output names that indicate predicted classes rather than scores. */\nconst LABEL_HINTS = [\"label\", \"class\", \"variable\", \"output\"] as const;\n\n/** Output names that indicate class scores. */\nconst PROBABILITY_HINTS = [\"probabilit\", \"score\"] as const;\n\n/** Largest plausible feature count; anything above is a dynamic-dim sentinel. */\nconst MAX_DECLARED_FEATURES = 1_000_000;\n\n/**\n * Pick the first output whose name contains one of `hints`.\n *\n * @param names Graph output names.\n * @param hints Lowercase substrings to look for.\n * @returns The matching name, or `null`.\n */\nfunction matchOutput(names: readonly string[], hints: readonly string[]): string | null {\n for (const hint of hints) {\n const found = names.find((name) => name.toLowerCase().includes(hint));\n if (found !== undefined) return found;\n }\n return null;\n}\n\n/**\n * Read the declared feature count from the input metadata.\n *\n * A dynamic batch dimension is reported as a symbolic string or as an\n * out-of-range number (`4294967295` — an unsigned `-1`), so only a sane\n * positive integer in the second position is trusted.\n *\n * @param session The loaded session.\n * @returns The feature count, or `null` when the graph does not declare one.\n */\nfunction declaredFeatures(session: ort.InferenceSession): number | null {\n const metadata = session.inputMetadata?.[0];\n if (metadata === undefined || metadata.isTensor !== true) return null;\n const dimension = metadata.shape[1];\n if (typeof dimension !== \"number\") return null;\n if (!Number.isInteger(dimension) || dimension <= 0) return null;\n return dimension > MAX_DECLARED_FEATURES ? null : dimension;\n}\n\n/**\n * Convert one raw label value into a JS-friendly label.\n *\n * @param value A tensor element: `bigint` for int64, `number` for float,\n * `string` for a string-labelled classifier.\n * @returns The label as a number or string.\n */\nfunction toLabel(value: unknown): PredictedLabel {\n if (typeof value === \"bigint\") return Number(value);\n if (typeof value === \"number\") return value;\n return String(value);\n}\n\n/**\n * Translate a session-creation failure into an error naming its cause.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asLoadError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes(\"No Op registered\")) {\n return new UnsupportedGraphError(\n \"This runtime build has no kernels for the model's operators. \" +\n \"scikit-learn exports use the ai.onnx.ml domain, which is missing \" +\n 'from the WebGPU build: import \"onnxruntime-web\", not ' +\n '\"onnxruntime-web/webgpu\". Original error: ' +\n message,\n { cause: error },\n );\n }\n return new ModelLoadError(`Failed to load the model: ${message}`, { cause: error });\n}\n\n/**\n * Translate a run failure into an error naming its cause.\n *\n * Measured: an export made with skl2onnx's default (ZipMap enabled) has a\n * probability output that is a sequence of maps, and ONNX Runtime Web\n * refuses to read non-tensor values — `Reading data from non-tensor typed\n * value is not supported`. That message describes the runtime's limitation,\n * not the fix, so it is replaced by one that names the export flag.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asRunError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (\n message.includes(\"non-tensor typed value\") ||\n message.includes(\"Can't access output tensor data\")\n ) {\n return new InferenceError(\n \"The model has a non-tensor output, which ONNX Runtime Web cannot \" +\n \"read. A scikit-learn export made with ZipMap enabled returns a \" +\n \"sequence of maps per row — re-export with export_sklearn_to_onnx, \" +\n `which disables it. Original error: ${message}`,\n { cause: error },\n );\n }\n return new InferenceError(`Inference failed: ${message}`, { cause: error });\n}\n\n/**\n * A loaded tabular model, ready to answer.\n *\n * @example\n * ```ts\n * const predictor = await TabularPredictor.create(\"/models/classifier.onnx\");\n * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);\n * ```\n */\nexport class TabularPredictor {\n private constructor(\n private readonly session: ort.InferenceSession,\n /** What is loaded and how it is configured. */\n public readonly info: TabularPredictorInfo,\n ) {}\n\n /**\n * Load a model and describe its graph.\n *\n * @param source A URL string, or the model bytes (which is what an\n * offline app passes, having read them from the cache).\n * @param options Providers, warm-up and pass-through session options.\n * @throws {@link UnsupportedGraphError} when the runtime build lacks the\n * `ai.onnx.ml` operators — the WebGPU entry point does.\n * @throws {@link ModelLoadError} for any other load failure.\n */\n static async create(\n source: TabularModelSource,\n options: TabularPredictorOptions = {},\n ): Promise<TabularPredictor> {\n const providers = options.providers ?? DEFAULT_TABULAR_PROVIDERS;\n let session: ort.InferenceSession;\n try {\n session = await ort.InferenceSession.create(source as never, {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n });\n } catch (error) {\n throw asLoadError(error);\n }\n\n const outputNames = [...session.outputNames];\n const probabilityOutput = matchOutput(outputNames, PROBABILITY_HINTS);\n const labelOutput =\n outputNames.find((name) => name !== probabilityOutput && isLabelName(name)) ??\n outputNames.find((name) => name !== probabilityOutput) ??\n (outputNames[0] as string);\n\n const predictor = new TabularPredictor(session, {\n inputName: session.inputNames[0] as string,\n numFeatures: declaredFeatures(session),\n outputNames,\n labelOutput,\n probabilityOutput,\n isClassifier: probabilityOutput !== null,\n providers,\n });\n\n if (options.warmup !== false) await predictor.warmUp();\n return predictor;\n }\n\n /**\n * Run one throwaway inference so the first real call is not the slow one.\n *\n * Skipped when the graph does not declare a feature count, since there\n * is no shape to synthesise. Failures are swallowed: a warm-up that\n * cannot run is not a reason to refuse to serve.\n */\n async warmUp(): Promise<void> {\n const features = this.info.numFeatures;\n if (features === null) return;\n try {\n await this.predict([new Array<number>(features).fill(0)]);\n } catch {\n /* a failed warm-up must not prevent serving */\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 produces them, and the\n * call's duration.\n * @throws {@link FeatureShapeError} when the batch is empty, ragged, or\n * the wrong width — checked here so the failure names the mismatch\n * instead of surfacing as an opaque runtime error.\n * @throws {@link InferenceError} when the session runs but its outputs\n * cannot be read.\n */\n async predict(rows: readonly FeatureRow[]): Promise<TabularPrediction> {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new FeatureShapeError(\n \"predict() needs at least one row, shaped [[f1, f2, ...]].\",\n );\n }\n const width = rows[0]?.length ?? 0;\n if (width === 0) {\n throw new FeatureShapeError(\"The first row has no feature values.\");\n }\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 const expected = this.info.numFeatures;\n if (expected !== null && width !== expected) {\n throw new FeatureShapeError(\n `The model expects ${expected} features per row, got ${width}.`,\n );\n }\n\n const flat = new Float32Array(rows.length * width);\n for (let index = 0; index < rows.length; index += 1) {\n flat.set(rows[index] as number[], index * width);\n }\n const tensor = new ort.Tensor(\"float32\", flat, [rows.length, width]);\n\n const started = performance.now();\n let outputs: ort.InferenceSession.OnnxValueMapType;\n try {\n outputs = await this.session.run({ [this.info.inputName]: tensor });\n } catch (error) {\n throw asRunError(error);\n }\n const ms = performance.now() - started;\n\n const labelTensor = outputs[this.info.labelOutput];\n if (labelTensor?.data === undefined) {\n throw new InferenceError(\n `The model produced no readable \"${this.info.labelOutput}\" output.`,\n );\n }\n\n const labels: PredictedLabel[] = Array.from(\n labelTensor.data as ArrayLike<unknown>,\n toLabel,\n );\n\n const probabilities: number[][] = [];\n if (this.info.probabilityOutput !== null) {\n const scores = outputs[this.info.probabilityOutput];\n if (scores?.data !== undefined) {\n const values = Array.from(scores.data as ArrayLike<number>, Number);\n const classes = values.length / rows.length;\n for (let index = 0; index < rows.length; index += 1) {\n probabilities.push(values.slice(index * classes, (index + 1) * classes));\n }\n }\n }\n\n return { labels, probabilities, numRows: rows.length, ms };\n }\n\n /**\n * Release the session's memory.\n *\n * Worth calling on a route that swaps models: the WebAssembly heap does\n * not shrink on garbage collection alone.\n */\n async dispose(): Promise<void> {\n await this.session.release?.();\n }\n}\n\n/**\n * Whether an output name looks like a label rather than a score.\n *\n * @param name The graph output name.\n * @returns `true` when the name matches a known label convention.\n */\nfunction isLabelName(name: string): boolean {\n const lowered = name.toLowerCase();\n return LABEL_HINTS.some((hint) => lowered.includes(hint));\n}\n"],"mappings":";;;AA8CA,IAAa,IAA+C,CAAC,MAAM,GAG7D,IAAc;CAAC;CAAS;CAAS;CAAY;AAAQ,GAGrD,IAAoB,CAAC,cAAc,OAAO,GAG1C,IAAwB;AAS9B,SAAS,EAAY,GAA0B,GAAyC;CACpF,KAAK,IAAM,KAAQ,GAAO;EACtB,IAAM,IAAQ,EAAM,MAAM,MAAS,EAAK,YAAY,CAAC,CAAC,SAAS,CAAI,CAAC;EACpE,IAAI,MAAU,KAAA,GAAW,OAAO;CACpC;CACA,OAAO;AACX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W,GAAM,CAAC,EAAK,QAAQ,CAAK,CAAC,GAE7D,IAAU,YAAY,IAAI,GAC5B;EACJ,IAAI;GACA,IAAU,MAAM,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,YAAY,EAAO,CAAC;EACtE,SAAS,GAAO;GACZ,MAAM,EAAW,CAAK;EAC1B;EACA,IAAM,IAAK,YAAY,IAAI,IAAI,GAEzB,IAAc,EAAQ,KAAK,KAAK;EACtC,IAAI,GAAa,SAAS,KAAA,GACtB,MAAM,IAAI,EACN,mCAAmC,KAAK,KAAK,YAAY,UAC7D;EAGJ,IAAM,IAA2B,MAAM,KACnC,EAAY,MACZ,CACJ,GAEM,IAA4B,CAAC;EACnC,IAAI,KAAK,KAAK,sBAAsB,MAAM;GACtC,IAAM,IAAS,EAAQ,KAAK,KAAK;GACjC,IAAI,GAAQ,SAAS,KAAA,GAAW;IAC5B,IAAM,IAAS,MAAM,KAAK,EAAO,MAA2B,MAAM,GAC5D,IAAU,EAAO,SAAS,EAAK;IACrC,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAK,QAAQ,KAAS,GAC9C,EAAc,KAAK,EAAO,MAAM,IAAQ,IAAU,IAAQ,KAAK,CAAO,CAAC;GAE/E;EACJ;EAEA,OAAO;GAAE;GAAQ;GAAe,SAAS,EAAK;GAAQ;EAAG;CAC7D;CAQA,MAAM,UAAyB;EAC3B,MAAM,KAAK,QAAQ,UAAU;CACjC;AACJ;AAQA,SAAS,EAAY,GAAuB;CACxC,IAAM,IAAU,EAAK,YAAY;CACjC,OAAO,EAAY,MAAM,MAAS,EAAQ,SAAS,CAAI,CAAC;AAC5D"}
1
+ {"version":3,"file":"predictor.js","names":[],"sources":["../../src/tabular/predictor.ts"],"sourcesContent":["/**\n * Running a scikit-learn model in the browser, offline.\n *\n * The model file is produced by `tempest-fastapi-sdk`'s\n * `export_sklearn_to_onnx`. This is everything between that file and an\n * answer — the same glue the Python `OnnxPredictor` provides on a device,\n * with the browser's own traps handled:\n *\n * - **int64 labels arrive as `bigint`.** ONNX Runtime Web surfaces the\n * label tensor as a `BigInt64Array`, so a caller comparing `label === 1`\n * silently gets `false` and `JSON.stringify` throws. Labels are converted.\n * - **`ai.onnx.ml` needs the right build.** Measured: importing\n * `onnxruntime-web/webgpu` loads a WebAssembly binary without those\n * operators, and session creation fails with `No Op registered for\n * TreeEnsembleClassifier`. That failure is translated into an error that\n * names the import.\n * - **Which output is which.** A classifier returns `label` and\n * `probabilities`; a regressor returns a single `variable`. Indexing by\n * position works until the day you deploy the other kind.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { configuredOrtAssetPath } from \"./assets\";\nimport {\n FeatureShapeError,\n InferenceError,\n ModelLoadError,\n UnsupportedGraphError,\n} from \"./exceptions\";\nimport type {\n FeatureRow,\n PredictedLabel,\n TabularModelSource,\n TabularPrediction,\n TabularPredictorInfo,\n TabularPredictorOptions,\n} from \"./types\";\n\n/**\n * Import ONNX Runtime Web, only when a model is actually being loaded.\n *\n * Static import would make every consumer of this subpath install the peer,\n * including apps that only ever touch `CompactPredictor` — whose whole\n * point is not needing a runtime. Found by installing the published\n * package into an empty project, which is the only place the difference\n * shows.\n *\n * @returns The runtime module.\n * @throws {@link ModelLoadError} when the peer is not installed, naming it.\n */\nasync function loadRuntime(): Promise<typeof ort> {\n try {\n return (await import(\"onnxruntime-web\")) as typeof ort;\n } catch (error) {\n throw new ModelLoadError(\n \"The ONNX route needs the optional peer dependency: \" +\n \"npm install onnxruntime-web. For a model with no runtime at \" +\n \"all, export it with edge_pipeline(compact=True) and load it \" +\n \"through CompactPredictor.\",\n { cause: error },\n );\n }\n}\n\n/**\n * Execution providers used when the caller does not choose.\n *\n * WebAssembly only, and deliberately: scikit-learn graphs are `ai.onnx.ml`\n * operators, which the WebGPU backend does not implement. There is no\n * speed left on the table here — a 10-tree forest predicts a row in about\n * 0.05 ms in Chromium.\n */\nexport const DEFAULT_TABULAR_PROVIDERS: readonly string[] = [\"wasm\"];\n\n/** Output names that indicate predicted classes rather than scores. */\nconst LABEL_HINTS = [\"label\", \"class\", \"variable\", \"output\"] as const;\n\n/** Output names that indicate class scores. */\nconst PROBABILITY_HINTS = [\"probabilit\", \"score\"] as const;\n\n/** Largest plausible feature count; anything above is a dynamic-dim sentinel. */\nconst MAX_DECLARED_FEATURES = 1_000_000;\n\n/**\n * Pick the first output whose name contains one of `hints`.\n *\n * @param names Graph output names.\n * @param hints Lowercase substrings to look for.\n * @returns The matching name, or `null`.\n */\nfunction matchOutput(names: readonly string[], hints: readonly string[]): string | null {\n for (const hint of hints) {\n const found = names.find((name) => name.toLowerCase().includes(hint));\n if (found !== undefined) return found;\n }\n return null;\n}\n\n/**\n * Read the declared feature count from the input metadata.\n *\n * A dynamic batch dimension is reported as a symbolic string or as an\n * out-of-range number (`4294967295` — an unsigned `-1`), so only a sane\n * positive integer in the second position is trusted.\n *\n * @param session The loaded session.\n * @returns The feature count, or `null` when the graph does not declare one.\n */\nfunction declaredFeatures(session: ort.InferenceSession): number | null {\n const metadata = session.inputMetadata?.[0];\n if (metadata === undefined || metadata.isTensor !== true) return null;\n const dimension = metadata.shape[1];\n if (typeof dimension !== \"number\") return null;\n if (!Number.isInteger(dimension) || dimension <= 0) return null;\n return dimension > MAX_DECLARED_FEATURES ? null : dimension;\n}\n\n/**\n * Convert one raw label value into a JS-friendly label.\n *\n * @param value A tensor element: `bigint` for int64, `number` for float,\n * `string` for a string-labelled classifier.\n * @returns The label as a number or string.\n */\nfunction toLabel(value: unknown): PredictedLabel {\n if (typeof value === \"bigint\") return Number(value);\n if (typeof value === \"number\") return value;\n return String(value);\n}\n\n/**\n * Translate a session-creation failure into an error naming its cause.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asLoadError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes(\"No Op registered\")) {\n return new UnsupportedGraphError(\n \"This runtime build has no kernels for the model's operators. \" +\n \"scikit-learn exports use the ai.onnx.ml domain, which is missing \" +\n 'from the WebGPU build: import \"onnxruntime-web\", not ' +\n '\"onnxruntime-web/webgpu\". Original error: ' +\n message,\n { cause: error },\n );\n }\n return new ModelLoadError(`Failed to load the model: ${message}`, { cause: error });\n}\n\n/**\n * Translate a run failure into an error naming its cause.\n *\n * Measured: an export made with skl2onnx's default (ZipMap enabled) has a\n * probability output that is a sequence of maps, and ONNX Runtime Web\n * refuses to read non-tensor values — `Reading data from non-tensor typed\n * value is not supported`. That message describes the runtime's limitation,\n * not the fix, so it is replaced by one that names the export flag.\n *\n * @param error Whatever ONNX Runtime threw.\n * @returns The error to surface.\n */\nfunction asRunError(error: unknown): Error {\n const message = error instanceof Error ? error.message : String(error);\n if (\n message.includes(\"non-tensor typed value\") ||\n message.includes(\"Can't access output tensor data\")\n ) {\n return new InferenceError(\n \"The model has a non-tensor output, which ONNX Runtime Web cannot \" +\n \"read. A scikit-learn export made with ZipMap enabled returns a \" +\n \"sequence of maps per row — re-export with export_sklearn_to_onnx, \" +\n `which disables it. Original error: ${message}`,\n { cause: error },\n );\n }\n return new InferenceError(`Inference failed: ${message}`, { cause: error });\n}\n\n/**\n * A loaded tabular model, ready to answer.\n *\n * @example\n * ```ts\n * const predictor = await TabularPredictor.create(\"/models/classifier.onnx\");\n * const { labels, probabilities } = await predictor.predict([[5.1, 3.5, 1.4, 0.2]]);\n * ```\n */\nexport class TabularPredictor {\n private constructor(\n private readonly runtime: typeof ort,\n private readonly session: ort.InferenceSession,\n /** What is loaded and how it is configured. */\n public readonly info: TabularPredictorInfo,\n ) {}\n\n /**\n * Load a model and describe its graph.\n *\n * @param source A URL string, or the model bytes (which is what an\n * offline app passes, having read them from the cache).\n * @param options Providers, warm-up and pass-through session options.\n * @throws {@link UnsupportedGraphError} when the runtime build lacks the\n * `ai.onnx.ml` operators — the WebGPU entry point does.\n * @throws {@link ModelLoadError} for any other load failure.\n */\n static async create(\n source: TabularModelSource,\n options: TabularPredictorOptions = {},\n ): Promise<TabularPredictor> {\n const providers = options.providers ?? DEFAULT_TABULAR_PROVIDERS;\n const runtime = await loadRuntime();\n const assets = configuredOrtAssetPath();\n if (assets !== undefined) runtime.env.wasm.wasmPaths = assets;\n\n let session: ort.InferenceSession;\n try {\n session = await runtime.InferenceSession.create(source as never, {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n });\n } catch (error) {\n throw asLoadError(error);\n }\n\n const outputNames = [...session.outputNames];\n const probabilityOutput = matchOutput(outputNames, PROBABILITY_HINTS);\n const labelOutput =\n outputNames.find((name) => name !== probabilityOutput && isLabelName(name)) ??\n outputNames.find((name) => name !== probabilityOutput) ??\n (outputNames[0] as string);\n\n const predictor = new TabularPredictor(runtime, session, {\n inputName: session.inputNames[0] as string,\n numFeatures: declaredFeatures(session),\n outputNames,\n labelOutput,\n probabilityOutput,\n isClassifier: probabilityOutput !== null,\n providers,\n });\n\n if (options.warmup !== false) await predictor.warmUp();\n return predictor;\n }\n\n /**\n * Run one throwaway inference so the first real call is not the slow one.\n *\n * Skipped when the graph does not declare a feature count, since there\n * is no shape to synthesise. Failures are swallowed: a warm-up that\n * cannot run is not a reason to refuse to serve.\n */\n async warmUp(): Promise<void> {\n const features = this.info.numFeatures;\n if (features === null) return;\n try {\n await this.predict([new Array<number>(features).fill(0)]);\n } catch {\n /* a failed warm-up must not prevent serving */\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 produces them, and the\n * call's duration.\n * @throws {@link FeatureShapeError} when the batch is empty, ragged, or\n * the wrong width — checked here so the failure names the mismatch\n * instead of surfacing as an opaque runtime error.\n * @throws {@link InferenceError} when the session runs but its outputs\n * cannot be read.\n */\n async predict(rows: readonly FeatureRow[]): Promise<TabularPrediction> {\n if (!Array.isArray(rows) || rows.length === 0) {\n throw new FeatureShapeError(\n \"predict() needs at least one row, shaped [[f1, f2, ...]].\",\n );\n }\n const width = rows[0]?.length ?? 0;\n if (width === 0) {\n throw new FeatureShapeError(\"The first row has no feature values.\");\n }\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 const expected = this.info.numFeatures;\n if (expected !== null && width !== expected) {\n throw new FeatureShapeError(\n `The model expects ${expected} features per row, got ${width}.`,\n );\n }\n\n const flat = new Float32Array(rows.length * width);\n for (let index = 0; index < rows.length; index += 1) {\n flat.set(rows[index] as number[], index * width);\n }\n const tensor = new this.runtime.Tensor(\"float32\", flat, [rows.length, width]);\n\n const started = performance.now();\n let outputs: ort.InferenceSession.OnnxValueMapType;\n try {\n outputs = await this.session.run({ [this.info.inputName]: tensor });\n } catch (error) {\n throw asRunError(error);\n }\n const ms = performance.now() - started;\n\n const labelTensor = outputs[this.info.labelOutput];\n if (labelTensor?.data === undefined) {\n throw new InferenceError(\n `The model produced no readable \"${this.info.labelOutput}\" output.`,\n );\n }\n\n const labels: PredictedLabel[] = Array.from(\n labelTensor.data as ArrayLike<unknown>,\n toLabel,\n );\n\n const probabilities: number[][] = [];\n if (this.info.probabilityOutput !== null) {\n const scores = outputs[this.info.probabilityOutput];\n if (scores?.data !== undefined) {\n const values = Array.from(scores.data as ArrayLike<number>, Number);\n const classes = values.length / rows.length;\n for (let index = 0; index < rows.length; index += 1) {\n probabilities.push(values.slice(index * classes, (index + 1) * classes));\n }\n }\n }\n\n return { labels, probabilities, numRows: rows.length, ms };\n }\n\n /**\n * Release the session's memory.\n *\n * Worth calling on a route that swaps models: the WebAssembly heap does\n * not shrink on garbage collection alone.\n */\n async dispose(): Promise<void> {\n await this.session.release?.();\n }\n}\n\n/**\n * Whether an output name looks like a label rather than a score.\n *\n * @param name The graph output name.\n * @returns `true` when the name matches a known label convention.\n */\nfunction isLabelName(name: string): boolean {\n const lowered = name.toLowerCase();\n return LABEL_HINTS.some((hint) => l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AM,GAC5D,IAAU,EAAO,SAAS,EAAK;IACrC,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAK,QAAQ,KAAS,GAC9C,EAAc,KAAK,EAAO,MAAM,IAAQ,IAAU,IAAQ,KAAK,CAAO,CAAC;GAE/E;EACJ;EAEA,OAAO;GAAE;GAAQ;GAAe,SAAS,EAAK;GAAQ;EAAG;CAC7D;CAQA,MAAM,UAAyB;EAC3B,MAAM,KAAK,QAAQ,UAAU;CACjC;AACJ;AAQA,SAAS,EAAY,GAAuB;CACxC,IAAM,IAAU,EAAK,YAAY;CACjC,OAAO,EAAY,MAAM,MAAS,EAAQ,SAAS,CAAI,CAAC;AAC5D"}
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/predictor.cjs"),i=require("./tabular/manifest.cjs"),a=require("./tabular/use-tabular-predictor.cjs");exports.DEFAULT_MODEL_CACHE=n.DEFAULT_MODEL_CACHE,exports.DEFAULT_TABULAR_PROVIDERS=r.DEFAULT_TABULAR_PROVIDERS,exports.FeatureShapeError=t.FeatureShapeError,exports.InferenceError=t.InferenceError,exports.MANIFEST_FILENAME=i.MANIFEST_FILENAME,exports.ModelFetchError=t.ModelFetchError,exports.ModelLoadError=t.ModelLoadError,exports.ORT_WASM_ASSETS=e.ORT_WASM_ASSETS,exports.SUPPORTED_MANIFEST_SCHEMA=i.SUPPORTED_MANIFEST_SCHEMA,exports.TabularError=t.TabularError,exports.TabularPredictor=r.TabularPredictor,exports.UnsupportedGraphError=t.UnsupportedGraphError,exports.cacheModelBytes=n.cacheModelBytes,exports.clearModelCache=n.clearModelCache,exports.configureOrtAssets=e.configureOrtAssets,exports.fetchEdgeManifest=i.fetchEdgeManifest,exports.fetchModelBytes=n.fetchModelBytes,exports.isModelCached=n.isModelCached,exports.loadEdgePackage=i.loadEdgePackage,exports.ortAssetUrls=e.ortAssetUrls,exports.useTabularPredictor=a.useTabularPredictor;
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.configuredOrtAssetPath=e.configuredOrtAssetPath,exports.fetchEdgeManifest=a.fetchEdgeManifest,exports.fetchModelBytes=n.fetchModelBytes,exports.isModelCached=n.isModelCached,exports.loadEdgePackage=a.loadEdgePackage,exports.ortAssetUrls=e.ortAssetUrls,exports.useTabularPredictor=o.useTabularPredictor;