@picovoice/cheetah-react-native
Version:
Picovoice Cheetah React Native binding
204 lines (194 loc) • 9.12 kB
JavaScript
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
//
// Copyright 2022-2026 Picovoice Inc.
//
// You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
// file accompanying this source.
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
import { NativeModules } from 'react-native';
import * as CheetahErrors from './cheetah_errors';
const RCTCheetah = NativeModules.PvCheetah;
class Cheetah {
/**
* Static creator for initializing Cheetah given the model path.
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
* @param modelPath Path to the file containing model parameters.
* @param options Optional configuration arguments.
* @param options.device String representation of the device (e.g., CPU or GPU) to use for inference.
* If set to `best`, the most suitable device is selected automatically. If set to `gpu`, the engine uses the
* first available GPU device. To select a specific GPU device, set this argument to `gpu:${GPU_INDEX}`, where
* `${GPU_INDEX}` is the index of the target GPU. If set to `cpu`, the engine will run on the CPU with the
* default number of threads. To specify the number of threads, set this argument to `cpu:${NUM_THREADS}`,
* where `${NUM_THREADS}` is the desired number of threads.
* @param options.endpointDuration Duration of endpoint in seconds. A speech endpoint is detected when there is a
* chunk of audio (with a duration specified herein) after an utterance without any speech in it.
* Set duration to 0 to disable this. Default is 1 second.
* @param options.enableAutomaticPunctuation Set to `true` to enable automatic punctuation insertion.
* @param options.enableTextNormalization Set to `true` to enable text normalization. Enabling this feature
* improves the readability and formatting of Cheetah's transcriptions (e.g. converts number words to digits)
* at the cost of some additional latency.
* @returns An instance of the engine.
*/
static async create(accessKey, modelPath) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
device = 'best',
endpointDuration = 1.0,
enableAutomaticPunctuation = false,
enableTextNormalization = false
} = options;
try {
let {
handle,
frameLength,
sampleRate,
version
} = await RCTCheetah.create(accessKey, modelPath, device, endpointDuration, enableAutomaticPunctuation, enableTextNormalization);
return new Cheetah(handle, frameLength, sampleRate, version);
} catch (err) {
if (err instanceof CheetahErrors.CheetahError) {
throw err;
} else {
const nativeError = err;
throw this.codeToError(nativeError.code, nativeError.message);
}
}
}
constructor(handle, frameLength, sampleRate, version) {
_defineProperty(this, "_handle", void 0);
_defineProperty(this, "_frameLength", void 0);
_defineProperty(this, "_sampleRate", void 0);
_defineProperty(this, "_version", void 0);
this._handle = handle;
this._frameLength = frameLength;
this._sampleRate = sampleRate;
this._version = version;
}
/**
* Gets all available devices that Cheetah can use for inference. Each entry in the list can be the `device` argument
* of the constructor.
*
* @returns Array of all available devices that Cheetah can use for inference.
*/
static async getAvailableDevices() {
try {
return await RCTCheetah.getAvailableDevices();
} catch (err) {
if (err instanceof CheetahErrors.CheetahError) {
throw err;
} else {
const nativeError = err;
throw this.codeToError(nativeError.code, nativeError.message);
}
}
}
/**
* Process a frame of audio with the speech-to-text engine.
* @param frame An array of 16-bit pcm samples. The number of samples per frame can be attained by calling
* `Cheetah.frameLength`. The incoming audio needs to have a sample rate equal to `Cheetah.sampleRate`
* and be 16-bit linearly-encoded. Furthermore, Cheetah operates on single-channel audio.
* @returns {Promise<CheetahTranscript>} transcript of any newly-transcribed speech (if none is available then an
* empty string is returned) and a flag indicating if an endpoint has been detected.
*/
async process(frame) {
if (frame === undefined || frame === null) {
throw new CheetahErrors.CheetahInvalidArgumentError(`Frame array provided to process() is undefined or null`);
} else if (frame.length !== this._frameLength) {
throw new CheetahErrors.CheetahInvalidArgumentError(`Size of frame array provided to 'process' (${frame.length}) does not match the engine 'frameLength' (${this._frameLength})`);
}
// sample the first frame to check for non-integer values
if (!Number.isInteger(frame[0])) {
throw new CheetahErrors.CheetahInvalidArgumentError(`Non-integer frame values provided to process(): ${frame[0]}. Cheetah requires 16-bit integers`);
}
try {
return await RCTCheetah.process(this._handle, frame);
} catch (err) {
const nativeError = err;
throw Cheetah.codeToError(nativeError.code, nativeError.message);
}
}
/**
* Marks the end of the audio stream, flushes internal state of the object, and returns
* any remaining transcribed text.
*
* @returns {Promise<CheetahTranscript>} Any remaining transcribed text. If none is available then an empty string is returned.
*/
async flush() {
try {
return RCTCheetah.flush(this._handle);
} catch (err) {
const nativeError = err;
throw Cheetah.codeToError(nativeError.code, nativeError.message);
}
}
/**
* Frees memory that was allocated for Cheetah
*/
async delete() {
return RCTCheetah.delete(this._handle);
}
/**
* Gets the required number of audio samples per frame.
* @returns Required frame length.
*/
get frameLength() {
return this._frameLength;
}
/**
* Get the audio sample rate required by Cheetah.
* @returns Required sample rate.
*/
get sampleRate() {
return this._sampleRate;
}
/**
* Gets the version number of the Cheetah library.
* @returns Version of Cheetah
*/
get version() {
return this._version;
}
/**
* Gets the Error type given a code.
* @param code Code name of native Error.
* @param message Detailed message of the error.
*/
static codeToError(code, message) {
switch (code) {
case 'CheetahException':
return new CheetahErrors.CheetahError(message);
case 'CheetahMemoryException':
return new CheetahErrors.CheetahMemoryError(message);
case 'CheetahIOException':
return new CheetahErrors.CheetahIOError(message);
case 'CheetahInvalidArgumentException':
return new CheetahErrors.CheetahInvalidArgumentError(message);
case 'CheetahStopIterationException':
return new CheetahErrors.CheetahStopIterationError(message);
case 'CheetahKeyException':
return new CheetahErrors.CheetahKeyError(message);
case 'CheetahInvalidStateException':
return new CheetahErrors.CheetahInvalidStateError(message);
case 'CheetahRuntimeException':
return new CheetahErrors.CheetahRuntimeError(message);
case 'CheetahActivationException':
return new CheetahErrors.CheetahActivationError(message);
case 'CheetahActivationLimitException':
return new CheetahErrors.CheetahActivationLimitError(message);
case 'CheetahActivationThrottledException':
return new CheetahErrors.CheetahActivationThrottledError(message);
case 'CheetahActivationRefusedException':
return new CheetahErrors.CheetahActivationRefusedError(message);
default:
throw new Error(`unexpected code: ${code}, message: ${message}`);
}
}
}
export default Cheetah;
//# sourceMappingURL=cheetah.js.map