Download web-src/src/standard-worker.ts from sasakiy84/bibform: direct link, hf CLI and curl.
- Browser
- Download file 6.87 kB
-
https://huggingface.co/sasakiy84/bibform/resolve/main/web-src/src/standard-worker.ts
- Command line
-
hf download hf://sasakiy84/bibform/web-src/src/standard-worker.ts
-
curl -L -o standard-worker.ts https://huggingface.co/sasakiy84/bibform/resolve/main/web-src/src/standard-worker.ts
6.87 kB
| import { decompress } from 'fzstd'; | |
| import { env, InferenceSession, Tensor } from 'onnxruntime-web/wasm'; | |
| import { loadBinary } from './lite'; | |
| const directory = new URL('./standard/', import.meta.url); | |
| const runtime = new URL('./runtime/', import.meta.url); | |
| const sessions = new Map<string, Promise<InferenceSession>>(); | |
| const encodedGraphs = new Map<string, ArrayBuffer>(); | |
| const graphs = [ | |
| 'primary-encoder', 'primary-features', 'auxiliary-features', | |
| 'primary-roles', 'auxiliary-roles', 'primary-names', 'auxiliary-names', 'primary-span-scores', | |
| 'selector', 'title_merge_selector', 'version_span_selector', 'title', 'edition', 'resource', | |
| ]; | |
| let primaryBytes: Promise<Uint8Array> | undefined; | |
| let initialized: Promise<BrowserPython> | undefined; | |
| interface BrowserPython { | |
| globals: { set(name: string, value: string): void }; | |
| registerJsModule(name: string, module: { run_graph: typeof runGraph; tokenize_citation(text: string): Uint32Array }): void; | |
| unpackArchive(bytes: ArrayBuffer, format: 'zip', options: { extractDir: string }): void; | |
| runPythonAsync(code: string): Promise<unknown>; | |
| } | |
| interface NumPyBuffer { | |
| getBuffer(format: string): { | |
| readonly data: ArrayBufferView; | |
| readonly offset: number; | |
| release(): void; | |
| }; | |
| } | |
| interface WasmTokenizer { | |
| default(path: URL): Promise<unknown>; | |
| CitationTokenizer: new (definition: string) => { encode(text: string): Uint32Array }; | |
| } | |
| async function asset(path: string): Promise<Response> { | |
| const response = await fetch(new URL(path, directory)); | |
| if (!response.ok) throw new Error(`通常版のファイルを読み込めませんでした(${response.status})`); | |
| return response; | |
| } | |
| async function compressed(path: string): Promise<Uint8Array> { | |
| const bytes = encodedGraphs.get(path) ?? await (await asset(path)).arrayBuffer(); | |
| const graph = decompress(new Uint8Array(bytes)); | |
| encodedGraphs.delete(path); | |
| return graph; | |
| } | |
| async function prefetchGraphs(): Promise<void> { | |
| const files = [...graphs.map((name) => `${name}.onnx.zst`), 'auxiliary-encoder.delta.zst']; | |
| await Promise.all(files.map(async (file) => { | |
| if (!encodedGraphs.has(file)) encodedGraphs.set(file, await (await asset(file)).arrayBuffer()); | |
| })); | |
| } | |
| async function openSession(name: string): Promise<InferenceSession> { | |
| let bytes: Uint8Array; | |
| if (name === 'primary-encoder' || name === 'auxiliary-encoder') { | |
| primaryBytes ??= compressed('primary-encoder.onnx.zst'); | |
| const base = await primaryBytes; | |
| if (name === 'auxiliary-encoder') { | |
| const difference = await compressed('auxiliary-encoder.delta.zst'); | |
| if (base.length !== difference.length) throw new Error('通常版エンコーダーの容量が一致しません'); | |
| for (let index = 0; index < base.length; index++) difference[index] += base[index]; | |
| bytes = difference; | |
| primaryBytes = undefined; | |
| } else { | |
| bytes = base; | |
| } | |
| } else { | |
| bytes = await compressed(`${name}.onnx.zst`); | |
| } | |
| return InferenceSession.create(bytes, { executionProviders: ['wasm'], graphOptimizationLevel: 'basic' }); | |
| } | |
| function loadSession(name: string): Promise<InferenceSession> { | |
| const cached = sessions.get(name); | |
| if (cached) return cached; | |
| const request = openSession(name).catch((error: unknown) => { | |
| sessions.delete(name); | |
| throw error; | |
| }); | |
| sessions.set(name, request); | |
| return request; | |
| } | |
| async function runGraph( | |
| name: string, metadata: string, ...arrays: NumPyBuffer[] | |
| ): Promise<{ data: Float32Array; dims: readonly number[] }[]> { | |
| const descriptors: [string, 'int64' | 'float32', number[]][] = JSON.parse(metadata); | |
| const inputs = new Map<string, Tensor>(); | |
| for (const [index, [key, kind, dims]] of descriptors.entries()) { | |
| const count = dims.reduce((product, size) => product * size, 1); | |
| const view = arrays[index].getBuffer(kind === 'int64' ? 'i64' : 'f32'); | |
| try { | |
| if (view.data instanceof BigInt64Array && kind === 'int64') { | |
| inputs.set(key, new Tensor(kind, view.data.slice(view.offset, view.offset + count), dims)); | |
| } else if (view.data instanceof Float32Array && kind === 'float32') { | |
| inputs.set(key, new Tensor(kind, view.data.slice(view.offset, view.offset + count), dims)); | |
| } else { | |
| throw new Error(`通常版の入力形式を扱えません(${key})`); | |
| } | |
| } finally { | |
| view.release(); | |
| } | |
| } | |
| const active = await loadSession(name); | |
| const result = await active.run(Object.fromEntries(inputs)); | |
| return active.outputNames.map((key) => { | |
| const { data, dims } = result[key]; | |
| if (!(data instanceof Float32Array)) throw new Error('通常版の出力形式を扱えません'); | |
| return { data, dims }; | |
| }); | |
| } | |
| async function initialize(): Promise<BrowserPython> { | |
| const base = new URL('pyodide/', directory); | |
| const pyodideScript = new URL('pyodide.mjs', base).href; | |
| const tokenizerScript = new URL('tokenizer/bibform_tokenizer.js', directory).href; | |
| const pyodideModule: { loadPyodide(config: { indexURL: string; packages: string[] }): Promise<BrowserPython> } = | |
| await import(pyodideScript); | |
| const tokenizerModule: WasmTokenizer = await import(tokenizerScript); | |
| const [pyodide, definition, archive, bridge, ort] = await Promise.all([ | |
| pyodideModule.loadPyodide({ indexURL: base.href, packages: ['numpy'] }), | |
| asset('tokenizer.json').then((response) => response.text()), | |
| asset('decoder.zip').then((response) => response.arrayBuffer()), | |
| asset('browser.py').then((response) => response.text()), | |
| loadBinary(new URL('ort-wasm-simd-threaded.wasm.gz', runtime)), | |
| tokenizerModule.default(new URL('tokenizer/bibform_tokenizer_bg.wasm', directory)), | |
| prefetchGraphs(), | |
| ]); | |
| env.wasm.numThreads = 1; | |
| env.wasm.wasmPaths = runtime.href; | |
| env.wasm.wasmBinary = ort; | |
| const tokenizer = new tokenizerModule.CitationTokenizer(definition); | |
| pyodide.registerJsModule('bibform_worker', { run_graph: runGraph, tokenize_citation: (text: string) => tokenizer.encode(text) }); | |
| pyodide.unpackArchive(archive, 'zip', { extractDir: '/bibform' }); | |
| await pyodide.runPythonAsync(bridge); | |
| return pyodide; | |
| } | |
| self.addEventListener('message', async (event: MessageEvent<unknown>): Promise<void> => { | |
| if (typeof event.data !== 'string') return; | |
| try { | |
| initialized ??= initialize().catch((error: unknown) => { | |
| initialized = undefined; | |
| throw error; | |
| }); | |
| const pyodide = await initialized; | |
| pyodide.globals.set('citation', event.data); | |
| const result: unknown = await pyodide.runPythonAsync('json.dumps(decoder.predict(citation), ensure_ascii=False)'); | |
| if (typeof result !== 'string') throw new Error('通常版の出力を取得できませんでした'); | |
| self.postMessage({ result }); | |
| } catch (error) { | |
| console.error(error); | |
| self.postMessage({ error: '通常版で解析できませんでした。' }); | |
| } | |
| }); | |