|
| 1 | +import { InferenceSession, Tensor } from 'ext:ai/onnxruntime/onnx.js'; |
| 2 | + |
| 3 | +const DEFAULT_HUGGING_FACE_OPTIONS = { |
| 4 | + hostname: 'https://huggingface.co', |
| 5 | + path: { |
| 6 | + template: '{REPO_ID}/resolve/{REVISION}/onnx/{MODEL_FILE}?donwload=true', |
| 7 | + revision: 'main', |
| 8 | + modelFile: 'model_quantized.onnx', |
| 9 | + }, |
| 10 | +}; |
| 11 | + |
| 12 | +/** |
| 13 | + * An user friendly API for onnx backend |
| 14 | + */ |
| 15 | +class UserInferenceSession { |
| 16 | + inner; |
| 17 | + |
| 18 | + id; |
| 19 | + inputs; |
| 20 | + outputs; |
| 21 | + |
| 22 | + constructor(session) { |
| 23 | + this.inner = session; |
| 24 | + |
| 25 | + this.id = session.sessionId; |
| 26 | + this.inputs = session.inputNames; |
| 27 | + this.outputs = session.outputNames; |
| 28 | + } |
| 29 | + |
| 30 | + static async fromUrl(modelUrl) { |
| 31 | + if (modelUrl instanceof URL) { |
| 32 | + modelUrl = modelUrl.toString(); |
| 33 | + } |
| 34 | + |
| 35 | + const encoder = new TextEncoder(); |
| 36 | + const modelUrlBuffer = encoder.encode(modelUrl); |
| 37 | + const session = await InferenceSession.fromBuffer(modelUrlBuffer); |
| 38 | + |
| 39 | + return new UserInferenceSession(session); |
| 40 | + } |
| 41 | + |
| 42 | + static async fromHuggingFace(repoId, opts = {}) { |
| 43 | + const hostname = opts?.hostname ?? DEFAULT_HUGGING_FACE_OPTIONS.hostname; |
| 44 | + const pathOpts = { |
| 45 | + ...DEFAULT_HUGGING_FACE_OPTIONS.path, |
| 46 | + ...opts?.path, |
| 47 | + }; |
| 48 | + |
| 49 | + const modelPath = pathOpts.template |
| 50 | + .replaceAll('{REPO_ID}', repoId) |
| 51 | + .replaceAll('{REVISION}', pathOpts.revision) |
| 52 | + .replaceAll('{MODEL_FILE}', pathOpts.modelFile); |
| 53 | + |
| 54 | + if (!URL.canParse(modelPath, hostname)) { |
| 55 | + throw Error(`[Invalid URL] Couldn't parse the model path: "${modelPath}"`); |
| 56 | + } |
| 57 | + |
| 58 | + return await UserInferenceSession.fromUrl(new URL(modelPath, hostname)); |
| 59 | + } |
| 60 | + |
| 61 | + async run(inputs) { |
| 62 | + return await this.inner.run(inputs); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +class UserTensor extends Tensor { |
| 67 | + constructor(type, data, dim) { |
| 68 | + super(type, data, dim); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +export default { |
| 73 | + RawSession: UserInferenceSession, |
| 74 | + Tensor: UserTensor, |
| 75 | +}; |
0 commit comments