UNPKG

@picovoice/cheetah-react-native

Version:

Picovoice Cheetah React Native binding

172 lines (163 loc) 8.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _reactNative = require("react-native"); var CheetahErrors = _interopRequireWildcard(require("./cheetah_errors")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } 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); } const RCTCheetah = _reactNative.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.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. * @returns An instance of the engine. */ static async create(accessKey, modelPath) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const { endpointDuration = 1.0, enableAutomaticPunctuation = false } = options; try { let { handle, frameLength, sampleRate, version } = await RCTCheetah.create(accessKey, modelPath, endpointDuration, enableAutomaticPunctuation); 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; } /** * 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}`); } } } var _default = Cheetah; exports.default = _default; //# sourceMappingURL=cheetah.js.map