Skip to content

Support React Native #118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 181 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
181 commits
Select commit Hold shift + click to select a range
1aefcb6
Support for ReactNative
hans00 May 17, 2023
38acc1e
Correct module import
hans00 May 17, 2023
0d7faf0
Update package-lock
hans00 May 17, 2023
c1da2c8
fix errors
hans00 May 17, 2023
bb550f1
fix error
hans00 May 17, 2023
35d8f18
Merge branch 'xenova:main' into main
hans00 May 17, 2023
83cd1e6
Prevent fallback WASM on RN
hans00 May 17, 2023
f64e61b
Let native side load binary file, instead load as buffer
hans00 May 17, 2023
85d75ef
Fix 0 size tensor
hans00 May 17, 2023
392dc67
Correct version
hans00 May 17, 2023
c9cada9
Constantly fetch arraybuffer
hans00 May 17, 2023
20f128f
Replace `Uint8Array` as `Buffer` on RN
hans00 May 17, 2023
891a0a4
Revert version
hans00 May 17, 2023
fd302ae
Merge native codes
hans00 May 19, 2023
37e89cf
Fix test
hans00 May 19, 2023
9ee7504
Disable `image-encode` and `image-decode` for web
hans00 May 19, 2023
91ecc47
Sync code
hans00 May 19, 2023
17bc3e8
Use `RNFS.downloadFile` to avoid OOM on large model file.
hans00 May 19, 2023
58c2468
Correct download progress order
hans00 May 19, 2023
52be4db
Fix bug
hans00 May 19, 2023
e0683b3
Merge branch 'xenova:main' into main
hans00 May 19, 2023
362a0c7
Fix error
hans00 May 19, 2023
c633a2d
Use `interpolate_data` instead `resize-image-data`
hans00 May 19, 2023
798edec
Correct params
hans00 May 19, 2023
8c66b31
Support `react-native-gcanvas` to improve image parse performance
hans00 May 19, 2023
874340c
Correct algorithm impl
hans00 May 20, 2023
e9c2872
Use `interpolate_data` to resize
hans00 May 20, 2023
7fad900
Reuse code
hans00 May 20, 2023
327fb59
`ImageData` not need wrap with `Uint8ClampedArray`
hans00 May 20, 2023
ac85425
Add switch to enable use GCanvas
hans00 May 20, 2023
7b9232f
Support gCanvas on `resize`, `crop` and `pad`
hans00 May 21, 2023
47711c8
Force use latest `jpeg-js`
hans00 May 21, 2023
c2f01bd
Use `XRegExp` to support unicode on RN
hans00 May 21, 2023
185c58f
Revert "Use `XRegExp` to support unicode on RN"
hans00 May 21, 2023
e86687d
Add missing var
hans00 May 21, 2023
b7521c5
Set `useGCanvas` default true, instead env check
hans00 May 21, 2023
1730bea
Log full tensor on browser
hans00 May 21, 2023
ff64922
Merge branch 'xenova:main' into main
hans00 May 22, 2023
0e54440
Update package-lock.json
hans00 May 22, 2023
3f32b71
Use dynamic import to select backend
hans00 May 25, 2023
fd0fa22
Add `onnxruntime-react-native` in optional
hans00 May 25, 2023
3edb592
Set browser ignore
hans00 May 25, 2023
4f6b788
Fix runtime setup
hans00 May 25, 2023
0ac4b4e
Default export `onnxruntime-common`
hans00 May 25, 2023
0a260c5
Add missing var
hans00 May 25, 2023
7b2667b
Fix `browser` field for `react-native`
hans00 May 25, 2023
28e8f8d
Fix import
hans00 May 25, 2023
8069844
Fix build
hans00 May 25, 2023
a5682dd
Allow fallback `web` on node-like environment
hans00 May 25, 2023
77ac38e
Merge branch 'main' into merge
hans00 May 30, 2023
57e4bc8
Merge branch 'main' into merge
hans00 Jun 2, 2023
eee34a4
Merge branch 'xenova:main' into merge
hans00 Jun 30, 2023
e09f2d9
Correct variable
hans00 Jul 4, 2023
9e7d629
Fix error on load model
hans00 Jul 4, 2023
311cb9c
Merge branch 'main' into merge
hans00 Jul 12, 2023
6f85b28
Merge branch 'main' into merge
hans00 Jul 29, 2023
f27121d
Merge branch 'main' into merge
hans00 Aug 6, 2023
973f33a
Correct package.json
hans00 Aug 7, 2023
d70abf9
Export `isReady` promise
hans00 Aug 7, 2023
44f0668
Merge branch 'main' into merge
hans00 Aug 8, 2023
dff8dbb
Use `react-native` field to replace module
hans00 Aug 15, 2023
7d49523
Merge branch 'xenova:main' into merge
hans00 Aug 18, 2023
4b63d92
Add missing optionalDeps
hans00 Aug 22, 2023
2050020
Merge branch 'main' into merge
hans00 Aug 23, 2023
d6d42dc
Fix config file never cache
hans00 Aug 23, 2023
8aa2993
Merge branch 'xenova:main' into merge
hans00 Sep 8, 2023
f98160f
Fix missing var
hans00 Sep 8, 2023
214ba14
Avoid use preserve word
hans00 Sep 11, 2023
7fe660b
Support `OffscreenCanvas` polyfill without `document`
hans00 Oct 3, 2023
b95a836
Merge branch 'main' into merge
hans00 Oct 3, 2023
d14ec8e
Fix `type` is missing
hans00 Oct 12, 2023
d49b0d0
Merge branch 'xenova:main' into merge
hans00 Oct 24, 2023
2fdf3e6
Opt-out wasm for RN and wait runtime loaded
hans00 Oct 30, 2023
ee89374
Merge branch 'main' into merge
hans00 Nov 10, 2023
95526e0
Merge branch 'xenova:main' into merge
hans00 Nov 16, 2023
2d54b61
Merge branch 'main' into merge
hans00 Dec 13, 2023
73b9131
Merge branch 'main' into merge
hans00 Dec 24, 2023
24726fa
Update `package-lock.json`
hans00 Dec 24, 2023
880348a
Fix error
hans00 Dec 24, 2023
1210102
Fix fetch binary for TTS
hans00 Dec 24, 2023
27e8434
Fix error when file cached
hans00 Dec 24, 2023
b16ad4c
Merge branch 'xenova:main' into merge
hans00 Dec 31, 2023
c5bbba5
Merge branch 'main' into merge
hans00 Jan 3, 2024
ad60a9b
Merge branch 'main' into merge
hans00 Jan 14, 2024
b42d06c
break trying load if backend error
hans00 Jan 17, 2024
2e15702
Fix web support
hans00 Jan 17, 2024
a94b45a
Bump onnxruntime
hans00 Jan 17, 2024
4a8a5bb
Remove `isReady` check
hans00 Jan 17, 2024
af1d6f6
Only continue on `Unsupported model type`
hans00 Jan 17, 2024
8a234c5
Continue on file 404 error
hans00 Jan 17, 2024
566ec32
Fix error on node
hans00 Jan 17, 2024
6e3affa
Exclude `wasm` for RN
hans00 Jan 18, 2024
79979e8
Merge branch 'xenova:main' into merge
hans00 Feb 1, 2024
c7aa59f
Merge branch 'main' into merge
hans00 Feb 13, 2024
3592613
Update `package-lock.json`
hans00 Feb 13, 2024
685b718
Support decode wav
hans00 Feb 17, 2024
2a35254
add `node-wav`
hans00 Feb 23, 2024
718c3d7
Merge branch 'main' into merge
hans00 Feb 23, 2024
755f5ba
Fix `package.json`
hans00 Feb 24, 2024
95faa44
Bump onnxruntime
hans00 Feb 24, 2024
c0dda59
Update `package-lock.json`
hans00 Feb 24, 2024
7fb93d9
Fix typo
hans00 Feb 24, 2024
d4d6ebf
Support Tensor of `[email protected]`
hans00 Feb 24, 2024
5a0d504
Correct algorithm implement
hans00 Feb 24, 2024
8cd25a4
Correct resample factor behavior
hans00 Feb 24, 2024
b597fa4
Rename `useGCanvas` to `useRNCanvas`
hans00 Feb 24, 2024
f7222ec
Better naming, change `useRNCanvas` to `rnUseCanvas`
hans00 Feb 24, 2024
5a23e2f
Fix `Tensor` index getter
hans00 Feb 25, 2024
a089ef0
Fix not work with spread transform
hans00 Feb 25, 2024
306b208
Add dispose to release memory
hans00 Feb 25, 2024
431983b
Support `crop` for ReactNative
hans00 Feb 25, 2024
060a2e5
Change to `image-codecs`
hans00 Feb 25, 2024
7ad4ef2
Setup `image-codecs`
hans00 Feb 25, 2024
b4a4bce
Correct URI format
hans00 Feb 25, 2024
9b7faf9
Fix bug
hans00 Feb 25, 2024
d697e77
Fix error process
hans00 Feb 28, 2024
173cc09
Correct error process
hans00 Feb 28, 2024
0d31927
Merge branch 'main' into merge
hans00 Mar 6, 2024
eb56058
Update package-lock.json
hans00 Mar 6, 2024
1a2bc57
Merge branch 'main' into merge
hans00 Mar 8, 2024
3dd8855
Disable WASM configure for React Native
hans00 Mar 18, 2024
b41e23c
Move `readFile` into `FileResponse`
hans00 Mar 26, 2024
840fa5c
Support load model from local path for RN & Node.js
hans00 Mar 26, 2024
9e15f15
Merge branch 'main' into merge
hans00 Mar 26, 2024
d81b459
Fix missing function
hans00 Mar 27, 2024
333c547
Update package-lock
hans00 Mar 27, 2024
0a29022
Fix missing var
hans00 Mar 27, 2024
dc05218
Use `fetch` for non-RN env
hans00 Mar 27, 2024
243f7fd
Cleanup invalid doc
hans00 Mar 27, 2024
bad3882
Add `session_options`
hans00 Apr 3, 2024
4098dd0
Fix `session_options` not work
hans00 Apr 3, 2024
800a476
Use same option for path load
hans00 Apr 3, 2024
c7fdd36
Fix `session_options`
hans00 Apr 3, 2024
c9bed9c
Correct logic
hans00 Apr 3, 2024
f835060
Fix model load
hans00 Apr 3, 2024
fbd7136
Return file path if not RN
hans00 Apr 4, 2024
6da74ff
Prevent readFile when get model path
hans00 Apr 8, 2024
3a3fa29
Merge branch 'main' into merge
hans00 Apr 20, 2024
22cbfe9
Update package-lock
hans00 Apr 20, 2024
c986a8c
Merge branch 'main' into merge
hans00 May 13, 2024
8df376b
Fix syntax
hans00 May 13, 2024
9f30f1b
Merge branch 'main' into merge
hans00 Jun 10, 2024
9109355
Fix model file download
hans00 Jun 18, 2024
918950e
Merge branch 'main' into merge
hans00 Jul 22, 2024
9015d03
Merge branch 'main' into merge
hans00 Oct 20, 2024
55b840c
Merge branch 'main' into merge
hans00 Jan 14, 2025
920de52
Fix typecheck
hans00 Jan 16, 2025
be329d2
Merge branch 'main' into merge
hans00 Jan 16, 2025
1cae87f
Fix missing var
hans00 Jan 16, 2025
0b90edf
Fix run on native
hans00 Jan 20, 2025
8c72a5d
Drop `read_audio` support for native
hans00 Jan 20, 2025
df5dc48
Use middleware to support multiple FS module
hans00 Jan 20, 2025
c3922f7
Merge branch 'huggingface:main' into merge
hans00 Jan 20, 2025
5da635a
Fix test
hans00 Jan 20, 2025
ed52df5
Correct import mapping
hans00 Jan 20, 2025
943c904
Bump `native-universal-fs`
hans00 Jan 20, 2025
33a6034
Default add xnnpaxk and cpu
hans00 Jan 20, 2025
7acc609
Correct default path for native
hans00 Jan 20, 2025
af4c6ab
Wait devices are resolved
hans00 Jan 20, 2025
3671a79
Fix FS detection
hans00 Jan 20, 2025
93d9d88
Bump `native-universal-fs`
hans00 Jan 20, 2025
c0e0bee
Correct import map
hans00 Jan 20, 2025
0a4cb43
Remove unused
hans00 Jan 20, 2025
8c0aca8
Remove unused
hans00 Feb 11, 2025
b9896b6
Use `__filename` + webpack define plugin to resolve module path
hans00 Feb 11, 2025
5401517
Make backend resolve syncally
hans00 Feb 11, 2025
7d09c5d
Merge branch 'main' into merge
hans00 Feb 11, 2025
cc3fa60
Update `package-lock.json`
hans00 Feb 11, 2025
8f4b0e3
Manually mock `react-native` for test
hans00 Feb 11, 2025
7285456
Fix test or non-RN env work
hans00 Feb 11, 2025
6f01fc0
Use `fetch` under `globalThis`
hans00 Feb 11, 2025
6a6c5b1
Merge branch 'huggingface:main' into merge
hans00 Feb 24, 2025
578fd5b
Merge branch 'main' into merge
hans00 Mar 13, 2025
07ccf2d
Download to cache dir if `useFSCache`
hans00 Mar 14, 2025
da6eafa
Fix download model
hans00 Mar 14, 2025
4c1da9b
Remove mistake
hans00 Mar 14, 2025
2486900
Fix model load
hans00 Mar 14, 2025
cbbf58e
Merge branch 'main' into merge
hans00 Apr 3, 2025
1db6417
Fix download target path
hans00 Apr 3, 2025
c746cf9
Remove `image-codecs`, let user implement them-self
hans00 Apr 14, 2025
9f3f32c
Merge branch 'main' into merge
hans00 Apr 22, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ export default {
// ],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
moduleNameMapper: {
'native-universal-fs': 'node:fs/promises',
'react-native': new URL('./tests/react-native.mock.js', import.meta.url).pathname,
},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
Expand Down
21,625 changes: 15,330 additions & 6,295 deletions package-lock.json

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,15 @@
"homepage": "https://github.com/huggingface/transformers.js#readme",
"dependencies": {
"@huggingface/jinja": "^0.3.4",
"native-universal-fs": "^0.2.0",
"onnxruntime-node": "1.21.0",
"onnxruntime-react-native": "1.20.1",
"onnxruntime-web": "1.22.0-dev.20250409-89f8206ba4",
"sharp": "^0.34.1"
},
"optionalDependencies": {
"path-browserify": "^1.0.1"
},
"devDependencies": {
"@types/jest": "^29.5.14",
"@types/node": "^22.10.1",
Expand All @@ -82,8 +87,20 @@
"README.md",
"LICENSE"
],
"react-native": {
"react-native": "react-native",
"fs": false,
"onnxruntime-web": false,
"onnxruntime-node": "onnxruntime-react-native",
"native-universal-fs": "native-universal-fs",
"sharp": false,
"path": "path-browserify",
"stream/web": false
},
"browser": {
"fs": false,
"native-universal-fs": false,
"react-native": false,
"path": false,
"url": false,
"sharp": false,
Expand Down
17 changes: 17 additions & 0 deletions src/backends/onnx.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { env, apis } from '../env.js';
// In either case, we select the default export if it exists, otherwise we use the named export.
import * as ONNX_NODE from 'onnxruntime-node';
import * as ONNX_WEB from 'onnxruntime-web';
import * as RN from 'react-native';

export { Tensor } from 'onnxruntime-common';

Expand All @@ -38,6 +39,9 @@ const DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({
webgpu: 'webgpu', // WebGPU
cuda: 'cuda', // CUDA
dml: 'dml', // DirectML
xnnpack: 'xnnpack', // XNNPACK
nnapi: 'nnapi', // NNAPI
coreml: 'coreml', // CoreML

webnn: { name: 'webnn', deviceType: 'cpu' }, // WebNN (default)
'webnn-npu': { name: 'webnn', deviceType: 'npu' }, // WebNN NPU
Expand All @@ -60,6 +64,19 @@ if (ORT_SYMBOL in globalThis) {
// If the JS runtime exposes their own ONNX runtime, use it
ONNX = globalThis[ORT_SYMBOL];

} else if (apis.IS_REACT_NATIVE_ENV) {
ONNX = ONNX_NODE.default ?? ONNX_NODE;

if (RN?.Platform?.OS === 'android') {
supportedDevices.push('nnapi', 'xnnpack', 'cpu');
defaultDevices = ['nnapi', 'cpu'];
} else if (RN?.Platform?.OS === 'ios') {
supportedDevices.push('coreml', 'xnnpack', 'cpu');
defaultDevices = ['coreml', 'cpu'];
} else {
supportedDevices.push('xnnpack', 'cpu');
defaultDevices = ['cpu'];
}
} else if (apis.IS_NODE_ENV) {
ONNX = ONNX_NODE.default ?? ONNX_NODE;

Expand Down
28 changes: 17 additions & 11 deletions src/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* @module env
*/

import * as NativeFS from 'native-universal-fs';
import fs from 'fs';
import path from 'path';
import url from 'url';
Expand All @@ -37,9 +38,11 @@ const IS_WEBNN_AVAILABLE = typeof navigator !== 'undefined' && 'ml' in navigator

const IS_PROCESS_AVAILABLE = typeof process !== 'undefined';
const IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === 'node';
const IS_FS_AVAILABLE = !isEmpty(fs);
const IS_FS_AVAILABLE = !isEmpty(fs) || !isEmpty(NativeFS);
const IS_PATH_AVAILABLE = !isEmpty(path);

const IS_REACT_NATIVE_ENV = typeof navigator !== 'undefined' && navigator.product === 'ReactNative';

/**
* A read-only object containing information about the APIs available in the current environment.
*/
Expand All @@ -50,6 +53,9 @@ export const apis = Object.freeze({
/** Whether we are running in a web worker environment */
IS_WEBWORKER_ENV,

/** Whether we are running in a React Native environment */
IS_REACT_NATIVE_ENV,

/** Whether the Cache API is available */
IS_WEB_CACHE_AVAILABLE,

Expand All @@ -75,16 +81,13 @@ export const apis = Object.freeze({
const RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE;

let dirname__ = './';
if (RUNNING_LOCALLY) {
// NOTE: We wrap `import.meta` in a call to `Object` to prevent Webpack from trying to bundle it in CommonJS.
// Although we get the warning: "Accessing import.meta directly is unsupported (only property access or destructuring is supported)",
// it is safe to ignore since the bundled value (`{}`) isn't used for CommonJS environments (we use __dirname instead).
const _import_meta_url = Object(import.meta).url;

if (_import_meta_url) {
dirname__ = path.dirname(path.dirname(url.fileURLToPath(_import_meta_url))) // ESM
if (IS_REACT_NATIVE_ENV) {
dirname__ = NativeFS.DocumentDirectoryPath;
} else if (RUNNING_LOCALLY) {
if (typeof __filename !== 'undefined') {
dirname__ = path.dirname(path.dirname(__filename));
} else if (typeof __dirname !== 'undefined') {
dirname__ = path.dirname(__dirname) // CommonJS
dirname__ = path.dirname(__dirname);
}
}

Expand Down Expand Up @@ -115,6 +118,7 @@ const localModelPath = RUNNING_LOCALLY
* @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available.
* @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available.
* @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available.
* @property {boolean} rnUseCanvas Whether to use the Canvas API to load images on React Native. By default, it is `true`.
* @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`.
* @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`.
* @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this must be an object which
Expand All @@ -129,7 +133,7 @@ export const env = {
/////////////////// Backends settings ///////////////////
// NOTE: These will be populated later by the backends themselves.
backends: {
// onnxruntime-web/onnxruntime-node
// onnxruntime-web/onnxruntime-node/onnxruntime-react-native
onnx: {},
},

Expand All @@ -142,6 +146,8 @@ export const env = {
localModelPath: localModelPath,
useFS: IS_FS_AVAILABLE,

rnUseCanvas: true,

/////////////////// Cache settings ///////////////////
useBrowserCache: IS_WEB_CACHE_AVAILABLE,

Expand Down
5 changes: 3 additions & 2 deletions src/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ import { apis, env } from './env.js';
import { WhisperGenerationConfig } from './models/whisper/generation_whisper.js';
import { whisper_language_to_code } from './models/whisper/common_whisper.js';


//////////////////////////////////////////////////
// Model types: used internally
const MODEL_TYPES = {
Expand Down Expand Up @@ -172,7 +173,7 @@ async function getSession(pretrained_model_name_or_path, fileName, options) {

// If the device is not specified, we use the default (supported) execution providers.
const selectedDevice = /** @type {import("./utils/devices.js").DeviceType} */(
device ?? (apis.IS_NODE_ENV ? 'cpu' : 'wasm')
device ?? (apis.IS_NODE_ENV || apis.IS_REACT_NATIVE_ENV ? 'cpu' : 'wasm')
);

const executionProviders = deviceToExecutionProviders(selectedDevice);
Expand Down Expand Up @@ -260,7 +261,7 @@ async function getSession(pretrained_model_name_or_path, fileName, options) {
);
}

const return_path = apis.IS_NODE_ENV && env.useFSCache;
const return_path = apis.IS_NODE_ENV && env.useFSCache || apis.IS_REACT_NATIVE_ENV;
const bufferOrPathPromise = getModelFile(pretrained_model_name_or_path, modelFileName, true, options, return_path);

// Handle onnx external data files
Expand Down
5 changes: 4 additions & 1 deletion src/pipelines.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ import {
topk,
} from './utils/tensor.js';
import { RawImage } from './utils/image.js';
import {
fetchBinary
} from './utils/hub.js';


/**
Expand Down Expand Up @@ -2881,7 +2884,7 @@ export class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPi
if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {
// Load from URL with fetch
speaker_embeddings = new Float32Array(
await (await fetch(speaker_embeddings)).arrayBuffer()
await (await fetchBinary(speaker_embeddings)).arrayBuffer()
);
}

Expand Down
4 changes: 3 additions & 1 deletion src/tokenizers.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import {
import { max, min, round } from './utils/maths.js';
import { Tensor } from './utils/tensor.js';

import { env } from './env.js';

import {
PriorityQueue,
TokenLattice,
Expand Down Expand Up @@ -2119,7 +2121,7 @@ class ByteLevelDecoder extends Decoder {
*/
convert_tokens_to_string(tokens) {
const text = tokens.join('');
const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));
const byteArray = Uint8Array.from([...text].map(c => this.byte_decoder[c]));
const decoded_text = this.text_decoder.decode(byteArray);
return decoded_text;
}
Expand Down
20 changes: 17 additions & 3 deletions src/utils/audio.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,16 @@ import {
} from './core.js';
import { apis } from '../env.js';
import fs from 'fs';
import * as NativeFS from 'native-universal-fs';
import { Tensor, matmul } from './tensor.js';


/**
* Helper function to read audio from a path/URL.
* @param {string|URL} url The path/URL to load the audio from.
* @param {number} sampling_rate The sampling rate to use when decoding the audio.
* @returns {Promise<Float32Array>} The decoded audio as a `Float32Array`.
*/
/**
* Helper function to read audio from a path/URL.
* @param {string|URL} url The path/URL to load the audio from.
Expand Down Expand Up @@ -814,9 +821,16 @@ export class RawAudio {
}
fn = saveBlob;
} else if (apis.IS_FS_AVAILABLE) {
fn = async (/** @type {string} */ path, /** @type {Blob} */ blob) => {
let buffer = await blob.arrayBuffer();
fs.writeFileSync(path, Buffer.from(buffer));
if (apis.IS_REACT_NATIVE_ENV) {
fn = async (/** @type {string} */ path, /** @type {Blob} */ blob) => {
let buffer = await blob.arrayBuffer();
await NativeFS.writeFile(path, Buffer.from(buffer).toString('base64'), 'base64');
}
} else {
fn = async (/** @type {string} */ path, /** @type {Blob} */ blob) => {
let buffer = await blob.arrayBuffer();
fs.writeFileSync(path, Buffer.from(buffer));
}
}
} else {
throw new Error('Unable to save because filesystem is disabled in this environment.')
Expand Down
3 changes: 3 additions & 0 deletions src/utils/devices.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export const DEVICE_TYPES = Object.freeze({
webgpu: 'webgpu', // WebGPU
cuda: 'cuda', // CUDA
dml: 'dml', // DirectML
xnnpack: 'xnnpack', // XNNPACK
nnapi: 'nnapi', // NNAPI
coreml: 'coreml', // CoreML

webnn: 'webnn', // WebNN (default)
'webnn-npu': 'webnn-npu', // WebNN NPU
Expand Down
11 changes: 11 additions & 0 deletions src/utils/generic.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ export const Callable = /** @type {any} */ (class {
return Object.setPrototypeOf(closure, new.target.prototype)
}

/**
* This method is called when the object is called as a function.
* @param {any} thisArg The value of `this` provided for the call.
* @param {any[]} args The arguments passed to the call.
* @returns {*} The result of calling the `_call` method.
* @throws {Error} If the subclass does not implement the `_call` method.
*/
apply(thisArg, args) {
return this._call(...args)
}

/**
* This method should be implemented in subclasses to provide the
* functionality of the callable object.
Expand Down
Loading