Socket
Socket
Sign inDemoInstall

@picovoice/cheetah-node

Package Overview
Dependencies
0
Maintainers
6
Versions
8
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.1.1 to 2.0.0

.eslintignore

4

copy.js
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -13,3 +13,3 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

const mkdirp = require("mkdirp");
const { mkdirp } = require("mkdirp");
const ncp = require("ncp").ncp;

@@ -16,0 +16,0 @@

"use strict";
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -19,3 +19,3 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

const platforms_1 = require("./platforms");
const DEFAULT_MODEL_PATH = "../lib/common/cheetah_params.pv";
const DEFAULT_MODEL_PATH = '../lib/common/cheetah_params.pv';
/**

@@ -45,3 +45,3 @@ * Node.js binding for Cheetah streaming speech-to-text engine

constructor(accessKey, options = {}) {
assert(typeof accessKey === "string");
assert(typeof accessKey === 'string');
if (accessKey === null ||

@@ -52,3 +52,3 @@ accessKey === undefined ||

}
const { modelPath = path.resolve(__dirname, DEFAULT_MODEL_PATH), libraryPath = (0, platforms_1.getSystemLibraryPath)(), endpointDurationSec = 1.0, enableAutomaticPunctuation = false } = options;
const { modelPath = path.resolve(__dirname, DEFAULT_MODEL_PATH), libraryPath = (0, platforms_1.getSystemLibraryPath)(), endpointDurationSec = 1.0, enableAutomaticPunctuation = false, } = options;
if (endpointDurationSec < 0) {

@@ -63,16 +63,17 @@ throw new RangeError(`Duration of endpoint value in 'endpointDurationSec' must be a positive number: ${endpointDurationSec}`);

}
const pvCheetah = require(libraryPath);
const pvCheetah = require(libraryPath); // eslint-disable-line
this._pvCheetah = pvCheetah;
let cheetahHandleAndStatus = null;
try {
pvCheetah.set_sdk("nodejs");
cheetahHandleAndStatus = pvCheetah.init(accessKey, modelPath, endpointDurationSec, enableAutomaticPunctuation);
}
catch (err) {
(0, errors_1.pvStatusToException)(err.code, err);
(0, errors_1.pvStatusToException)(pv_status_t_1.default[err.code], err);
}
const status = cheetahHandleAndStatus.status;
if (status !== pv_status_t_1.default.SUCCESS) {
(0, errors_1.pvStatusToException)(status, "Cheetah failed to initialize");
this.handlePvStatus(status, 'Cheetah failed to initialize');
}
this._handle = cheetahHandleAndStatus.handle;
this._pvCheetah = pvCheetah;
this._sampleRate = pvCheetah.sample_rate();

@@ -108,3 +109,3 @@ this._frameLength = pvCheetah.frame_length();

* The specific array length can be attained by calling `Cheetah.frameLength`. This function operates on single-channel audio.
* @returns {string, bool} Inferred transcription, and a flag indicating if an endpoint has been detected.
* @returns {string, boolean} Inferred transcription, and a flag indicating if an endpoint has been detected.
*/

@@ -116,3 +117,3 @@ process(pcm) {

this._handle === undefined) {
throw new errors_1.CheetahInvalidStateError("Cheetah is not initialized");
throw new errors_1.CheetahInvalidStateError('Cheetah is not initialized');
}

@@ -130,11 +131,11 @@ if (pcm === undefined || pcm === null) {

catch (err) {
(0, errors_1.pvStatusToException)(err.code, err);
(0, errors_1.pvStatusToException)(pv_status_t_1.default[err.code], err);
}
const status = partialTranscriptAndStatus.status;
if (status !== pv_status_t_1.default.SUCCESS) {
(0, errors_1.pvStatusToException)(status, "Cheetah failed to process the audio frame");
this.handlePvStatus(status, 'Cheetah failed to process the audio frame');
}
return [
partialTranscriptAndStatus.transcript,
partialTranscriptAndStatus.is_endpoint === 0 ? false : true,
partialTranscriptAndStatus.is_endpoint !== 0,
];

@@ -151,3 +152,3 @@ }

this._handle === undefined) {
throw new errors_1.CheetahInvalidStateError("Cheetah is not initialized");
throw new errors_1.CheetahInvalidStateError('Cheetah is not initialized');
}

@@ -159,7 +160,7 @@ let transcriptAndStatus = null;

catch (err) {
(0, errors_1.pvStatusToException)(err.code, err);
(0, errors_1.pvStatusToException)(pv_status_t_1.default[err.code], err);
}
const status = transcriptAndStatus.status;
if (status !== pv_status_t_1.default.SUCCESS) {
(0, errors_1.pvStatusToException)(status, "Cheetah failed to process the audio frame");
this.handlePvStatus(status, 'Cheetah failed to flush');
}

@@ -185,7 +186,17 @@ return transcriptAndStatus.transcript;

else {
console.warn("Cheetah is not initialized");
// eslint-disable-next-line no-console
console.warn('Cheetah is not initialized');
}
}
handlePvStatus(status, message) {
const errorObject = this._pvCheetah.get_error_stack();
if (errorObject.status === pv_status_t_1.default.SUCCESS) {
(0, errors_1.pvStatusToException)(status, message, errorObject.message_stack);
}
else {
(0, errors_1.pvStatusToException)(status, "Unable to get Cheetah error state");
}
}
}
exports.default = Cheetah;
//# sourceMappingURL=cheetah.js.map
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,7 +11,27 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.pvStatusToException = exports.CheetahActivationRefused = exports.CheetahActivationThrottled = exports.CheetahActivationLimitReached = exports.CheetahActivationError = exports.CheetahRuntimeError = exports.CheetahInvalidStateError = exports.CheetahKeyError = exports.CheetahStopIterationError = exports.CheetahInvalidArgumentError = exports.CheetahIoError = exports.CheetahOutOfMemoryError = exports.CheetahError = void 0;
exports.pvStatusToException = exports.CheetahActivationRefusedError = exports.CheetahActivationThrottledError = exports.CheetahActivationLimitReachedError = exports.CheetahActivationError = exports.CheetahRuntimeError = exports.CheetahInvalidStateError = exports.CheetahKeyError = exports.CheetahStopIterationError = exports.CheetahInvalidArgumentError = exports.CheetahIOError = exports.CheetahOutOfMemoryError = exports.CheetahError = void 0;
const pv_status_t_1 = require("./pv_status_t");
class CheetahError extends Error {
_message;
_messageStack;
constructor(message, messageStack = []) {
super(CheetahError.errorToString(message, messageStack));
this._message = message;
this._messageStack = messageStack;
}
get message() {
return this._message;
}
get messageStack() {
return this._messageStack;
}
static errorToString(initial, messageStack) {
let msg = initial;
if (messageStack.length > 0) {
msg += `: ${messageStack.reduce((acc, value, index) => acc + '\n [' + index + '] ' + value, '')}`;
}
return msg;
}
}

@@ -22,5 +42,5 @@ exports.CheetahError = CheetahError;

exports.CheetahOutOfMemoryError = CheetahOutOfMemoryError;
class CheetahIoError extends CheetahError {
class CheetahIOError extends CheetahError {
}
exports.CheetahIoError = CheetahIoError;
exports.CheetahIOError = CheetahIOError;
class CheetahInvalidArgumentError extends CheetahError {

@@ -44,38 +64,39 @@ }

exports.CheetahActivationError = CheetahActivationError;
class CheetahActivationLimitReached extends CheetahError {
class CheetahActivationLimitReachedError extends CheetahError {
}
exports.CheetahActivationLimitReached = CheetahActivationLimitReached;
class CheetahActivationThrottled extends CheetahError {
exports.CheetahActivationLimitReachedError = CheetahActivationLimitReachedError;
class CheetahActivationThrottledError extends CheetahError {
}
exports.CheetahActivationThrottled = CheetahActivationThrottled;
class CheetahActivationRefused extends CheetahError {
exports.CheetahActivationThrottledError = CheetahActivationThrottledError;
class CheetahActivationRefusedError extends CheetahError {
}
exports.CheetahActivationRefused = CheetahActivationRefused;
function pvStatusToException(pvStatus, errorMessage) {
exports.CheetahActivationRefusedError = CheetahActivationRefusedError;
function pvStatusToException(pvStatus, errorMessage, messageStack = []) {
switch (pvStatus) {
case pv_status_t_1.default.OUT_OF_MEMORY:
throw new CheetahOutOfMemoryError(errorMessage);
throw new CheetahOutOfMemoryError(errorMessage, messageStack);
case pv_status_t_1.default.IO_ERROR:
throw new CheetahIoError(errorMessage);
throw new CheetahIOError(errorMessage, messageStack);
case pv_status_t_1.default.INVALID_ARGUMENT:
throw new CheetahInvalidArgumentError(errorMessage);
throw new CheetahInvalidArgumentError(errorMessage, messageStack);
case pv_status_t_1.default.STOP_ITERATION:
throw new CheetahStopIterationError(errorMessage);
throw new CheetahStopIterationError(errorMessage, messageStack);
case pv_status_t_1.default.KEY_ERROR:
throw new CheetahKeyError(errorMessage);
throw new CheetahKeyError(errorMessage, messageStack);
case pv_status_t_1.default.INVALID_STATE:
throw new CheetahInvalidStateError(errorMessage);
throw new CheetahInvalidStateError(errorMessage, messageStack);
case pv_status_t_1.default.RUNTIME_ERROR:
throw new CheetahRuntimeError(errorMessage);
throw new CheetahRuntimeError(errorMessage, messageStack);
case pv_status_t_1.default.ACTIVATION_ERROR:
throw new CheetahActivationError(errorMessage);
throw new CheetahActivationError(errorMessage, messageStack);
case pv_status_t_1.default.ACTIVATION_LIMIT_REACHED:
throw new CheetahActivationLimitReached(errorMessage);
throw new CheetahActivationLimitReachedError(errorMessage, messageStack);
case pv_status_t_1.default.ACTIVATION_THROTTLED:
throw new CheetahActivationThrottled(errorMessage);
throw new CheetahActivationThrottledError(errorMessage, messageStack);
case pv_status_t_1.default.ACTIVATION_REFUSED:
throw new CheetahActivationRefused(errorMessage);
throw new CheetahActivationRefusedError(errorMessage, messageStack);
default:
// eslint-disable-next-line no-console
console.warn(`Unmapped error code: ${pvStatus}`);
throw new CheetahError(errorMessage);
throw new CheetahError(errorMessage, messageStack);
}

@@ -82,0 +103,0 @@ }

//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,5 +11,5 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInt16Frames = exports.checkWaveFile = exports.CheetahStopIterationError = exports.CheetahRuntimeError = exports.CheetahOutOfMemoryError = exports.CheetahKeyError = exports.CheetahIoError = exports.CheetahInvalidStateError = exports.CheetahInvalidArgumentError = exports.CheetahError = exports.CheetahActivationThrottled = exports.CheetahActivationRefused = exports.CheetahActivationLimitReached = exports.CheetahActivationError = exports.Cheetah = void 0;
exports.getInt16Frames = exports.checkWaveFile = exports.CheetahErrors = exports.Cheetah = void 0;
const cheetah_1 = require("./cheetah");

@@ -20,15 +20,4 @@ exports.Cheetah = cheetah_1.default;

Object.defineProperty(exports, "checkWaveFile", { enumerable: true, get: function () { return wave_util_1.checkWaveFile; } });
const errors_1 = require("./errors");
Object.defineProperty(exports, "CheetahError", { enumerable: true, get: function () { return errors_1.CheetahError; } });
Object.defineProperty(exports, "CheetahOutOfMemoryError", { enumerable: true, get: function () { return errors_1.CheetahOutOfMemoryError; } });
Object.defineProperty(exports, "CheetahIoError", { enumerable: true, get: function () { return errors_1.CheetahIoError; } });
Object.defineProperty(exports, "CheetahInvalidArgumentError", { enumerable: true, get: function () { return errors_1.CheetahInvalidArgumentError; } });
Object.defineProperty(exports, "CheetahStopIterationError", { enumerable: true, get: function () { return errors_1.CheetahStopIterationError; } });
Object.defineProperty(exports, "CheetahKeyError", { enumerable: true, get: function () { return errors_1.CheetahKeyError; } });
Object.defineProperty(exports, "CheetahInvalidStateError", { enumerable: true, get: function () { return errors_1.CheetahInvalidStateError; } });
Object.defineProperty(exports, "CheetahRuntimeError", { enumerable: true, get: function () { return errors_1.CheetahRuntimeError; } });
Object.defineProperty(exports, "CheetahActivationError", { enumerable: true, get: function () { return errors_1.CheetahActivationError; } });
Object.defineProperty(exports, "CheetahActivationLimitReached", { enumerable: true, get: function () { return errors_1.CheetahActivationLimitReached; } });
Object.defineProperty(exports, "CheetahActivationThrottled", { enumerable: true, get: function () { return errors_1.CheetahActivationThrottled; } });
Object.defineProperty(exports, "CheetahActivationRefused", { enumerable: true, get: function () { return errors_1.CheetahActivationRefused; } });
const CheetahErrors = require("./errors");
exports.CheetahErrors = CheetahErrors;
//# sourceMappingURL=index.js.map
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,3 +11,3 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });

@@ -19,17 +19,17 @@ exports.getSystemLibraryPath = exports.getPlatform = void 0;

const errors_1 = require("./errors");
const SYSTEM_LINUX = "linux";
const SYSTEM_MAC = "darwin";
const SYSTEM_WINDOWS = "win32";
const X86_64 = "x64";
const ARM_32 = "arm";
const ARM_64 = "arm64";
const PLATFORM_JETSON = "jetson";
const PLATFORM_LINUX = "linux";
const PLATFORM_MAC = "mac";
const PLATFORM_RASPBERRY_PI = "raspberry-pi";
const PLATFORM_WINDOWS = "windows";
const ARM_CPU_64 = "-aarch64";
const ARM_CPU_CORTEX_A53 = "cortex-a53";
const ARM_CPU_CORTEX_A57 = "cortex-a57";
const ARM_CPU_CORTEX_A72 = "cortex-a72";
const SYSTEM_LINUX = 'linux';
const SYSTEM_MAC = 'darwin';
const SYSTEM_WINDOWS = 'win32';
const X86_64 = 'x64';
const ARM_32 = 'arm';
const ARM_64 = 'arm64';
const PLATFORM_JETSON = 'jetson';
const PLATFORM_LINUX = 'linux';
const PLATFORM_MAC = 'mac';
const PLATFORM_RASPBERRY_PI = 'raspberry-pi';
const PLATFORM_WINDOWS = 'windows';
const ARM_CPU_64 = '-aarch64';
const ARM_CPU_CORTEX_A53 = 'cortex-a53';
const ARM_CPU_CORTEX_A57 = 'cortex-a57';
const ARM_CPU_CORTEX_A72 = 'cortex-a72';
const SUPPORTED_NODEJS_SYSTEMS = new Set([

@@ -40,3 +40,3 @@ SYSTEM_LINUX,

]);
const LIBRARY_PATH_PREFIX = "../lib/";
const LIBRARY_PATH_PREFIX = '../lib/';
const SYSTEM_TO_LIBRARY_PATH = new Map();

@@ -56,6 +56,6 @@ SYSTEM_TO_LIBRARY_PATH.set(`${SYSTEM_MAC}/${X86_64}`, `${PLATFORM_MAC}/x86_64/pv_cheetah.node`);

function getCpuPart() {
const cpuInfo = fs.readFileSync("/proc/cpuinfo", "ascii");
for (let infoLine of cpuInfo.split("\n")) {
if (infoLine.includes("CPU part")) {
let infoLineSplit = infoLine.split(" ");
const cpuInfo = fs.readFileSync('/proc/cpuinfo', 'ascii');
for (const infoLine of cpuInfo.split('\n')) {
if (infoLine.includes('CPU part')) {
const infoLineSplit = infoLine.split(' ');
return infoLineSplit[infoLineSplit.length - 1].toLowerCase();

@@ -69,6 +69,6 @@ }

switch (cpuPart) {
case "0xd03":
case "0xd08":
case '0xd03':
case '0xd08':
return PLATFORM_RASPBERRY_PI;
case "0xd07":
case '0xd07':
return PLATFORM_JETSON;

@@ -80,4 +80,4 @@ default:

function getLinuxMachine(arch) {
let archInfo = "";
if (arch == ARM_64) {
let archInfo = '';
if (arch === ARM_64) {
archInfo = ARM_CPU_64;

@@ -87,7 +87,7 @@ }

switch (cpuPart) {
case "0xd03":
case '0xd03':
return ARM_CPU_CORTEX_A53 + archInfo;
case "0xd07":
case '0xd07':
return ARM_CPU_CORTEX_A57 + archInfo;
case "0xd08":
case '0xd08':
return ARM_CPU_CORTEX_A72 + archInfo;

@@ -111,5 +111,3 @@ default:

}
else {
return getLinuxPlatform();
}
return getLinuxPlatform();
}

@@ -138,9 +136,7 @@ throw `System ${system}/${arch} is not supported by this library.`;

else if (arch === ARM_32 || arch === ARM_64) {
let linuxMachine = getLinuxMachine(arch);
const linuxMachine = getLinuxMachine(arch);
if (linuxMachine !== null) {
return absoluteLibraryPath(SYSTEM_TO_LIBRARY_PATH.get(`${SYSTEM_LINUX}/${linuxMachine}`));
}
else {
throw new errors_1.CheetahRuntimeError(`System ${system}/${arch} is not supported by this library for this CPU.`);
}
throw new errors_1.CheetahRuntimeError(`System ${system}/${arch} is not supported by this library for this CPU.`);
}

@@ -153,3 +149,6 @@ break;

}
break;
}
default:
break;
}

@@ -156,0 +155,0 @@ }

//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,3 +11,3 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });

@@ -14,0 +14,0 @@ var PvStatus;

"use strict";
/*
Copyright 2022 Picovoice Inc.
Copyright 2022-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

@@ -5,0 +5,0 @@ file accompanying this source.

@@ -1,2 +0,2 @@

import { CheetahOptions } from "./types";
import { CheetahOptions } from './types';
/**

@@ -46,3 +46,3 @@ * Node.js binding for Cheetah streaming speech-to-text engine

* The specific array length can be attained by calling `Cheetah.frameLength`. This function operates on single-channel audio.
* @returns {string, bool} Inferred transcription, and a flag indicating if an endpoint has been detected.
* @returns {string, boolean} Inferred transcription, and a flag indicating if an endpoint has been detected.
*/

@@ -63,3 +63,4 @@ process(pcm: Int16Array): [string, boolean];

release(): void;
private handlePvStatus;
}
//# sourceMappingURL=cheetah.d.ts.map

@@ -1,7 +0,13 @@

import PvStatus from "./pv_status_t";
import PvStatus from './pv_status_t';
export declare class CheetahError extends Error {
private readonly _message;
private readonly _messageStack;
constructor(message: string, messageStack?: string[]);
get message(): string;
get messageStack(): string[];
private static errorToString;
}
export declare class CheetahOutOfMemoryError extends CheetahError {
}
export declare class CheetahIoError extends CheetahError {
export declare class CheetahIOError extends CheetahError {
}

@@ -20,9 +26,9 @@ export declare class CheetahInvalidArgumentError extends CheetahError {

}
export declare class CheetahActivationLimitReached extends CheetahError {
export declare class CheetahActivationLimitReachedError extends CheetahError {
}
export declare class CheetahActivationThrottled extends CheetahError {
export declare class CheetahActivationThrottledError extends CheetahError {
}
export declare class CheetahActivationRefused extends CheetahError {
export declare class CheetahActivationRefusedError extends CheetahError {
}
export declare function pvStatusToException(pvStatus: PvStatus, errorMessage: string): void;
export declare function pvStatusToException(pvStatus: PvStatus, errorMessage: string, messageStack?: string[]): CheetahError;
//# sourceMappingURL=errors.d.ts.map

@@ -1,6 +0,6 @@

import Cheetah from "./cheetah";
import { getInt16Frames, checkWaveFile } from "./wave_util";
import { CheetahInitOptions, CheetahInputOptions, CheetahOptions } from "./types";
import { CheetahError, CheetahOutOfMemoryError, CheetahIoError, CheetahInvalidArgumentError, CheetahStopIterationError, CheetahKeyError, CheetahInvalidStateError, CheetahRuntimeError, CheetahActivationError, CheetahActivationLimitReached, CheetahActivationThrottled, CheetahActivationRefused } from "./errors";
export { Cheetah, CheetahActivationError, CheetahActivationLimitReached, CheetahActivationRefused, CheetahActivationThrottled, CheetahError, CheetahInitOptions, CheetahInputOptions, CheetahInvalidArgumentError, CheetahInvalidStateError, CheetahIoError, CheetahKeyError, CheetahOptions, CheetahOutOfMemoryError, CheetahRuntimeError, CheetahStopIterationError, checkWaveFile, getInt16Frames, };
import Cheetah from './cheetah';
import { getInt16Frames, checkWaveFile } from './wave_util';
import { CheetahInitOptions, CheetahInputOptions, CheetahOptions } from './types';
import * as CheetahErrors from "./errors";
export { Cheetah, CheetahErrors, CheetahInitOptions, CheetahInputOptions, CheetahOptions, checkWaveFile, getInt16Frames, };
//# sourceMappingURL=index.d.ts.map

@@ -1,3 +0,3 @@

export declare function getPlatform(): "linux" | "jetson" | "mac" | "raspberry-pi" | "windows";
export declare function getPlatform(): string;
export declare function getSystemLibraryPath(): string;
//# sourceMappingURL=platforms.d.ts.map

@@ -1,10 +0,10 @@

export declare type CheetahInitOptions = {
export type CheetahInitOptions = {
endpointDurationSec?: number;
enableAutomaticPunctuation?: boolean;
};
export declare type CheetahInputOptions = {
export type CheetahInputOptions = {
modelPath?: string;
libraryPath?: string;
};
export declare type CheetahOptions = CheetahInitOptions & CheetahInputOptions;
export type CheetahOptions = CheetahInitOptions & CheetahInputOptions;
//# sourceMappingURL=types.d.ts.map
//
// Copyright 2020-2021 Picovoice Inc.
// Copyright 2020-2023 Picovoice Inc.
//

@@ -11,3 +11,3 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });

@@ -20,11 +20,14 @@ exports.getInt16Frames = exports.checkWaveFile = void 0;

let valid = true;
if (waveFile.bitDepth !== "16") {
console.error("Audio bit depth must be 16-bit");
if (waveFile.bitDepth !== '16') {
// eslint-disable-next-line no-console
console.error('Audio bit depth must be 16-bit');
valid = false;
}
if (waveFile.fmt.numChannels !== 1) {
console.error("Audio must be single channel");
// eslint-disable-next-line no-console
console.error('Audio must be single channel');
valid = false;
}
if (waveFile.fmt.sampleRate !== engineSampleRate) {
// eslint-disable-next-line no-console
console.error(`Audio sample rate ${waveFile.sampleRate} does not match Picovoice sample rate ${engineSampleRate}`);

@@ -38,3 +41,3 @@ valid = false;

const samples = waveFile.getSamples(false, Int16Array);
let frames = chunkArray(samples, frameLength);
const frames = chunkArray(samples, frameLength);
// throw out remainder / partial frame

@@ -41,0 +44,0 @@ if (frames[frames.length - 1].length !== frameLength) {

{
"name": "@picovoice/cheetah-node",
"version": "1.1.1",
"version": "2.0.0",
"description": "Picovoice Cheetah Node.js binding",

@@ -13,3 +13,4 @@ "main": "dist/index.js",

"prepare": "node copy.js",
"test": "jest --no-cache"
"test": "jest --no-cache",
"lint": "eslint . --ext .js,.ts"
},

@@ -42,5 +43,9 @@ "repository": {

"@types/jest": "^27.4.1",
"@types/node": "^17.0.21",
"@types/node": "^18.11.9",
"@typescript-eslint/eslint-plugin": "^5.19.0",
"@typescript-eslint/parser": "^5.19.0",
"eslint": "^8.13.0",
"eslint-plugin-jest": "^27.1.6",
"jest": "^27.5.1",
"mkdirp": "^1.0.4",
"mkdirp": "^3.0.1",
"ncp": "^2.0.0",

@@ -54,3 +59,3 @@ "npm-run-all": "^4.1.5",

"engines": {
"node": ">=12.0.0"
"node": ">=16.0.0"
},

@@ -57,0 +62,0 @@ "cpu": [

@@ -18,3 +18,3 @@ # Cheetah Binding for Node.js

- Node.js 12+
- Node.js 16+
- Runs on Linux (x86_64), macOS (x86_64, arm64), Windows (x86_64), Raspberry Pi (4, 3), and NVIDIA Jetson Nano.

@@ -39,3 +39,3 @@

```javascript
const Cheetah = require("@picovoice/cheetah-node");
const {Cheetah} = require("@picovoice/cheetah-node");

@@ -42,0 +42,0 @@ const accessKey = "${ACCESS_KEY}"; // Obtained from the Picovoice Console (https://console.picovoice.ai/)

//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -12,7 +12,7 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

import * as fs from "fs";
import * as path from "path";
import * as assert from "assert";
import * as fs from 'fs';
import * as path from 'path';
import * as assert from 'assert';
import PvStatus from "./pv_status_t";
import PvStatus from './pv_status_t';

@@ -23,17 +23,18 @@ import {

pvStatusToException,
} from "./errors";
} from './errors';
import {
CheetahOptions,
} from "./types";
import { CheetahOptions } from './types';
import {getSystemLibraryPath} from "./platforms";
import { getSystemLibraryPath } from './platforms';
const DEFAULT_MODEL_PATH = "../lib/common/cheetah_params.pv";
const DEFAULT_MODEL_PATH = '../lib/common/cheetah_params.pv';
type CheetahHandleAndStatus = { handle: any; status: PvStatus };
type TranscriptAndStatus = { transcript: string; status: PvStatus };
type PartialTranscriptAndStatus = { transcript: string; is_endpoint: number, status: PvStatus };
type PartialTranscriptAndStatus = {
transcript: string;
is_endpoint: number;
status: PvStatus;
};
/**

@@ -65,6 +66,4 @@ * Node.js binding for Cheetah streaming speech-to-text engine

*/
constructor(
accessKey: string,
options: CheetahOptions = {}) {
assert(typeof accessKey === "string");
constructor(accessKey: string, options: CheetahOptions = {}) {
assert(typeof accessKey === 'string');
if (

@@ -82,3 +81,3 @@ accessKey === null ||

endpointDurationSec = 1.0,
enableAutomaticPunctuation = false
enableAutomaticPunctuation = false,
} = options;

@@ -104,6 +103,9 @@

const pvCheetah = require(libraryPath);
const pvCheetah = require(libraryPath); // eslint-disable-line
this._pvCheetah = pvCheetah;
let cheetahHandleAndStatus: CheetahHandleAndStatus | null = null;
try {
pvCheetah.set_sdk("nodejs");
cheetahHandleAndStatus = pvCheetah.init(

@@ -116,3 +118,3 @@ accessKey,

} catch (err: any) {
pvStatusToException(<PvStatus>err.code, err);
pvStatusToException(PvStatus[err.code as keyof typeof PvStatus], err);
}

@@ -122,7 +124,6 @@

if (status !== PvStatus.SUCCESS) {
pvStatusToException(status, "Cheetah failed to initialize");
this.handlePvStatus(status, 'Cheetah failed to initialize');
}
this._handle = cheetahHandleAndStatus!.handle;
this._pvCheetah = pvCheetah;
this._sampleRate = pvCheetah.sample_rate();

@@ -162,3 +163,3 @@ this._frameLength = pvCheetah.frame_length();

* The specific array length can be attained by calling `Cheetah.frameLength`. This function operates on single-channel audio.
* @returns {string, bool} Inferred transcription, and a flag indicating if an endpoint has been detected.
* @returns {string, boolean} Inferred transcription, and a flag indicating if an endpoint has been detected.
*/

@@ -173,3 +174,3 @@ process(pcm: Int16Array): [string, boolean] {

) {
throw new CheetahInvalidStateError("Cheetah is not initialized");
throw new CheetahInvalidStateError('Cheetah is not initialized');
}

@@ -191,3 +192,3 @@

} catch (err: any) {
pvStatusToException(<PvStatus>err.code, err);
pvStatusToException(PvStatus[err.code as keyof typeof PvStatus], err);
}

@@ -197,3 +198,3 @@

if (status !== PvStatus.SUCCESS) {
pvStatusToException(status, "Cheetah failed to process the audio frame");
this.handlePvStatus(status, 'Cheetah failed to process the audio frame');
}

@@ -203,3 +204,3 @@

partialTranscriptAndStatus!.transcript,
partialTranscriptAndStatus!.is_endpoint === 0 ? false : true,
partialTranscriptAndStatus!.is_endpoint !== 0,
];

@@ -219,3 +220,3 @@ }

) {
throw new CheetahInvalidStateError("Cheetah is not initialized");
throw new CheetahInvalidStateError('Cheetah is not initialized');
}

@@ -227,3 +228,3 @@

} catch (err: any) {
pvStatusToException(<PvStatus>err.code, err);
pvStatusToException(PvStatus[err.code as keyof typeof PvStatus], err);
}

@@ -233,3 +234,3 @@

if (status !== PvStatus.SUCCESS) {
pvStatusToException(status, "Cheetah failed to process the audio frame");
this.handlePvStatus(status, 'Cheetah failed to flush');
}

@@ -246,3 +247,3 @@

*/
release() {
release(): void {
if (this._handle !== 0) {

@@ -256,5 +257,15 @@ try {

} else {
console.warn("Cheetah is not initialized");
// eslint-disable-next-line no-console
console.warn('Cheetah is not initialized');
}
}
private handlePvStatus(status: PvStatus, message: string): void {
const errorObject = this._pvCheetah.get_error_stack();
if (errorObject.status === PvStatus.SUCCESS) {
pvStatusToException(status, message, errorObject.message_stack);
} else {
pvStatusToException(status, "Unable to get Cheetah error state");
}
}
}
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,10 +11,41 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
import PvStatus from "./pv_status_t";
import PvStatus from './pv_status_t';
export class CheetahError extends Error {}
export class CheetahError extends Error {
private readonly _message: string;
private readonly _messageStack: string[];
constructor(message: string, messageStack: string[] = []) {
super(CheetahError.errorToString(message, messageStack));
this._message = message;
this._messageStack = messageStack;
}
get message(): string {
return this._message;
}
get messageStack(): string[] {
return this._messageStack;
}
private static errorToString(
initial: string,
messageStack: string[]
): string {
let msg = initial;
if (messageStack.length > 0) {
msg += `: ${messageStack.reduce((acc, value, index) =>
acc + '\n [' + index + '] ' + value, '')}`;
}
return msg;
}
}
export class CheetahOutOfMemoryError extends CheetahError {}
export class CheetahIoError extends CheetahError {}
export class CheetahIOError extends CheetahError {}
export class CheetahInvalidArgumentError extends CheetahError {}

@@ -26,34 +57,39 @@ export class CheetahStopIterationError extends CheetahError {}

export class CheetahActivationError extends CheetahError {}
export class CheetahActivationLimitReached extends CheetahError {}
export class CheetahActivationThrottled extends CheetahError {}
export class CheetahActivationRefused extends CheetahError {}
export class CheetahActivationLimitReachedError extends CheetahError {}
export class CheetahActivationThrottledError extends CheetahError {}
export class CheetahActivationRefusedError extends CheetahError {}
export function pvStatusToException(pvStatus: PvStatus, errorMessage: string) {
export function pvStatusToException(
pvStatus: PvStatus,
errorMessage: string,
messageStack: string[] = []
): CheetahError {
switch (pvStatus) {
case PvStatus.OUT_OF_MEMORY:
throw new CheetahOutOfMemoryError(errorMessage);
throw new CheetahOutOfMemoryError(errorMessage, messageStack);
case PvStatus.IO_ERROR:
throw new CheetahIoError(errorMessage);
throw new CheetahIOError(errorMessage, messageStack);
case PvStatus.INVALID_ARGUMENT:
throw new CheetahInvalidArgumentError(errorMessage);
throw new CheetahInvalidArgumentError(errorMessage, messageStack);
case PvStatus.STOP_ITERATION:
throw new CheetahStopIterationError(errorMessage);
throw new CheetahStopIterationError(errorMessage, messageStack);
case PvStatus.KEY_ERROR:
throw new CheetahKeyError(errorMessage);
throw new CheetahKeyError(errorMessage, messageStack);
case PvStatus.INVALID_STATE:
throw new CheetahInvalidStateError(errorMessage);
throw new CheetahInvalidStateError(errorMessage, messageStack);
case PvStatus.RUNTIME_ERROR:
throw new CheetahRuntimeError(errorMessage);
throw new CheetahRuntimeError(errorMessage, messageStack);
case PvStatus.ACTIVATION_ERROR:
throw new CheetahActivationError(errorMessage);
throw new CheetahActivationError(errorMessage, messageStack);
case PvStatus.ACTIVATION_LIMIT_REACHED:
throw new CheetahActivationLimitReached(errorMessage);
throw new CheetahActivationLimitReachedError(errorMessage, messageStack);
case PvStatus.ACTIVATION_THROTTLED:
throw new CheetahActivationThrottled(errorMessage);
throw new CheetahActivationThrottledError(errorMessage, messageStack);
case PvStatus.ACTIVATION_REFUSED:
throw new CheetahActivationRefused(errorMessage);
throw new CheetahActivationRefusedError(errorMessage, messageStack);
default:
// eslint-disable-next-line no-console
console.warn(`Unmapped error code: ${pvStatus}`);
throw new CheetahError(errorMessage);
throw new CheetahError(errorMessage, messageStack);
}
}
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,7 +11,7 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
import Cheetah from "./cheetah";
import Cheetah from './cheetah';
import {getInt16Frames, checkWaveFile} from "./wave_util"
import { getInt16Frames, checkWaveFile } from './wave_util';

@@ -22,38 +22,14 @@ import {

CheetahOptions,
} from "./types";
} from './types';
import {
CheetahError,
CheetahOutOfMemoryError,
CheetahIoError,
CheetahInvalidArgumentError,
CheetahStopIterationError,
CheetahKeyError,
CheetahInvalidStateError,
CheetahRuntimeError,
CheetahActivationError,
CheetahActivationLimitReached,
CheetahActivationThrottled,
CheetahActivationRefused,
} from "./errors";
import * as CheetahErrors from "./errors";
export {
Cheetah,
CheetahActivationError,
CheetahActivationLimitReached,
CheetahActivationRefused,
CheetahActivationThrottled,
CheetahError,
CheetahErrors,
CheetahInitOptions,
CheetahInputOptions,
CheetahInvalidArgumentError,
CheetahInvalidStateError,
CheetahIoError,
CheetahKeyError,
CheetahOptions,
CheetahOutOfMemoryError,
CheetahRuntimeError,
CheetahStopIterationError,
checkWaveFile,
getInt16Frames,
};
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,28 +11,28 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { CheetahRuntimeError } from "./errors";
import { CheetahRuntimeError } from './errors';
const SYSTEM_LINUX = "linux";
const SYSTEM_MAC = "darwin";
const SYSTEM_WINDOWS = "win32";
const SYSTEM_LINUX = 'linux';
const SYSTEM_MAC = 'darwin';
const SYSTEM_WINDOWS = 'win32';
const X86_64 = "x64";
const ARM_32 = "arm";
const ARM_64 = "arm64";
const X86_64 = 'x64';
const ARM_32 = 'arm';
const ARM_64 = 'arm64';
const PLATFORM_JETSON = "jetson";
const PLATFORM_LINUX = "linux";
const PLATFORM_MAC = "mac";
const PLATFORM_RASPBERRY_PI = "raspberry-pi";
const PLATFORM_WINDOWS = "windows";
const PLATFORM_JETSON = 'jetson';
const PLATFORM_LINUX = 'linux';
const PLATFORM_MAC = 'mac';
const PLATFORM_RASPBERRY_PI = 'raspberry-pi';
const PLATFORM_WINDOWS = 'windows';
const ARM_CPU_64 = "-aarch64";
const ARM_CPU_CORTEX_A53 = "cortex-a53";
const ARM_CPU_CORTEX_A57 = "cortex-a57";
const ARM_CPU_CORTEX_A72 = "cortex-a72";
const ARM_CPU_64 = '-aarch64';
const ARM_CPU_CORTEX_A53 = 'cortex-a53';
const ARM_CPU_CORTEX_A57 = 'cortex-a57';
const ARM_CPU_CORTEX_A72 = 'cortex-a72';

@@ -45,3 +45,3 @@ const SUPPORTED_NODEJS_SYSTEMS = new Set([

const LIBRARY_PATH_PREFIX = "../lib/";
const LIBRARY_PATH_PREFIX = '../lib/';
const SYSTEM_TO_LIBRARY_PATH = new Map();

@@ -85,11 +85,11 @@ SYSTEM_TO_LIBRARY_PATH.set(

function absoluteLibraryPath(libraryPath: string) {
function absoluteLibraryPath(libraryPath: string): string {
return path.resolve(__dirname, LIBRARY_PATH_PREFIX, libraryPath);
}
function getCpuPart() {
const cpuInfo = fs.readFileSync("/proc/cpuinfo", "ascii");
for (let infoLine of cpuInfo.split("\n")) {
if (infoLine.includes("CPU part")) {
let infoLineSplit = infoLine.split(" ");
function getCpuPart(): string {
const cpuInfo = fs.readFileSync('/proc/cpuinfo', 'ascii');
for (const infoLine of cpuInfo.split('\n')) {
if (infoLine.includes('CPU part')) {
const infoLineSplit = infoLine.split(' ');
return infoLineSplit[infoLineSplit.length - 1].toLowerCase();

@@ -101,9 +101,9 @@ }

function getLinuxPlatform() {
function getLinuxPlatform(): string {
const cpuPart = getCpuPart();
switch (cpuPart) {
case "0xd03":
case "0xd08":
case '0xd03':
case '0xd08':
return PLATFORM_RASPBERRY_PI;
case "0xd07":
case '0xd07':
return PLATFORM_JETSON;

@@ -115,5 +115,5 @@ default:

function getLinuxMachine(arch: string) {
let archInfo = "";
if (arch == ARM_64) {
function getLinuxMachine(arch: string): string {
let archInfo = '';
if (arch === ARM_64) {
archInfo = ARM_CPU_64;

@@ -124,7 +124,7 @@ }

switch (cpuPart) {
case "0xd03":
case '0xd03':
return ARM_CPU_CORTEX_A53 + archInfo;
case "0xd07":
case '0xd07':
return ARM_CPU_CORTEX_A57 + archInfo;
case "0xd08":
case '0xd08':
return ARM_CPU_CORTEX_A72 + archInfo;

@@ -136,3 +136,3 @@ default:

export function getPlatform() {
export function getPlatform(): string {
const system = os.platform();

@@ -152,5 +152,4 @@ const arch = os.arch();

return PLATFORM_LINUX;
} else {
return getLinuxPlatform();
}
return getLinuxPlatform();
}

@@ -161,3 +160,3 @@

export function getSystemLibraryPath() {
export function getSystemLibraryPath(): string {
const system = os.platform();

@@ -186,3 +185,3 @@ const arch = os.arch();

} else if (arch === ARM_32 || arch === ARM_64) {
let linuxMachine = getLinuxMachine(arch);
const linuxMachine = getLinuxMachine(arch);
if (linuxMachine !== null) {

@@ -192,7 +191,6 @@ return absoluteLibraryPath(

);
} else {
throw new CheetahRuntimeError(
`System ${system}/${arch} is not supported by this library for this CPU.`
);
}
throw new CheetahRuntimeError(
`System ${system}/${arch} is not supported by this library for this CPU.`
);
}

@@ -207,3 +205,6 @@ break;

}
break;
}
default:
break;
}

@@ -210,0 +211,0 @@ }

//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,3 +11,3 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';

@@ -14,0 +14,0 @@ enum PvStatus {

/*
Copyright 2022 Picovoice Inc.
Copyright 2022-2023 Picovoice Inc.
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

@@ -11,5 +11,5 @@ file accompanying this source.

export type CheetahInitOptions = {
endpointDurationSec?: number
endpointDurationSec?: number;
enableAutomaticPunctuation?: boolean;
}
};

@@ -19,5 +19,4 @@ export type CheetahInputOptions = {

libraryPath?: string;
};
}
export type CheetahOptions = CheetahInitOptions & CheetahInputOptions;
export type CheetahOptions = CheetahInitOptions & CheetahInputOptions;
//
// Copyright 2020-2021 Picovoice Inc.
// Copyright 2020-2023 Picovoice Inc.
//

@@ -11,5 +11,5 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
function chunkArray(array:Int16Array, size:number): Int16Array[] {
function chunkArray(array: Int16Array, size: number): Int16Array[] {
return Array.from({ length: Math.ceil(array.length / size) }, (v, index) =>

@@ -20,7 +20,11 @@ array.slice(index * size, index * size + size)

export function checkWaveFile(waveFile: any, engineSampleRate:number): boolean {
export function checkWaveFile(
waveFile: any,
engineSampleRate: number
): boolean {
let valid = true;
if (waveFile.bitDepth !== "16") {
console.error("Audio bit depth must be 16-bit");
if (waveFile.bitDepth !== '16') {
// eslint-disable-next-line no-console
console.error('Audio bit depth must be 16-bit');
valid = false;

@@ -30,3 +34,4 @@ }

if (waveFile.fmt.numChannels !== 1) {
console.error("Audio must be single channel");
// eslint-disable-next-line no-console
console.error('Audio must be single channel');
valid = false;

@@ -36,2 +41,3 @@ }

if (waveFile.fmt.sampleRate !== engineSampleRate) {
// eslint-disable-next-line no-console
console.error(

@@ -46,7 +52,9 @@ `Audio sample rate ${waveFile.sampleRate} does not match Picovoice sample rate ${engineSampleRate}`

export function getInt16Frames(waveFile: any, frameLength:number): Int16Array[] {
export function getInt16Frames(
waveFile: any,
frameLength: number
): Int16Array[] {
const samples = waveFile.getSamples(false, Int16Array);
let frames = chunkArray(samples, frameLength);
const frames = chunkArray(samples, frameLength);

@@ -53,0 +61,0 @@ // throw out remainder / partial frame

//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,16 +11,23 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
import {Cheetah, CheetahInvalidArgumentError, getInt16Frames, checkWaveFile} from "../src";
import * as fs from "fs";
import * as path from "path";
import {WaveFile} from "wavefile";
import {
Cheetah,
CheetahErrors,
} from '../src';
import * as fs from 'fs';
import { WaveFile } from 'wavefile';
import {getSystemLibraryPath} from "../src/platforms";
import { getSystemLibraryPath } from '../src/platforms';
const MODEL_PATH = "./lib/common/cheetah_params.pv";
import {
TRANSCRIPT,
getAudioFile,
getModelPath,
getTestParameters,
} from './test_utils';
const WAV_PATH = "../../../resources/audio_samples/test.wav";
const TRANSCRIPT =
"Mr quilter is the apostle of the middle classes and we are glad to welcome his gospel";
const MODEL_PATH = getModelPath();
const TEST_PARAMETERS = getTestParameters();
const WAV_PATH = "test.wav";

@@ -30,28 +37,59 @@ const libraryPath = getSystemLibraryPath();

const ACCESS_KEY = process.argv
.filter((x) => x.startsWith("--access_key="))[0]
.split("--access_key=")[1];
.filter(x => x.startsWith('--access_key='))[0]
.split('--access_key=')[1];
function cheetahProcessWaveFile(
engineInstance: Cheetah,
relativeWaveFilePath: string
): [string, boolean] {
const waveFilePath = path.join(__dirname, relativeWaveFilePath);
const levenshteinDistance = (words1: string[], words2: string[]) => {
const res = Array.from(
Array(words1.length + 1),
() => new Array(words2.length + 1)
);
for (let i = 0; i <= words1.length; i++) {
res[i][0] = i;
}
for (let j = 0; j <= words2.length; j++) {
res[0][j] = j;
}
for (let i = 1; i <= words1.length; i++) {
for (let j = 1; j <= words2.length; j++) {
res[i][j] = Math.min(
res[i - 1][j] + 1,
res[i][j - 1] + 1,
res[i - 1][j - 1] +
(words1[i - 1].toUpperCase() === words2[j - 1].toUpperCase() ? 0 : 1)
);
}
}
return res[words1.length][words2.length];
};
const characterErrorRate = (
transcript: string,
expectedTranscript: string
): number => {
const ed = levenshteinDistance(
transcript.split(''),
expectedTranscript.split('')
);
return ed / expectedTranscript.length;
};
const loadPcm = (audioFile: string): Int16Array => {
const waveFilePath = getAudioFile(audioFile);
const waveBuffer = fs.readFileSync(waveFilePath);
const waveAudioFile = new WaveFile(waveBuffer);
if (!checkWaveFile(waveAudioFile, engineInstance.sampleRate)) {
console.error(
"Audio file did not meet requirements. Wave file must be 16KHz, 16-bit, linear PCM (mono)."
);
return ["", false];
}
const pcm: any = waveAudioFile.getSamples(false, Int16Array);
return pcm;
};
const frames = getInt16Frames(waveAudioFile, engineInstance.frameLength);
const cheetahProcessWaveFile = (
engineInstance: Cheetah,
audioFile: string
): [string, boolean] => {
const pcm = loadPcm(audioFile);
let transcript = "";
let transcript = '';
let isEndpoint = false;
for (let i = 0; i < frames.length; i++) {
const frame = frames[i];
const [partialTranscript, partialIsEndpoint] =
engineInstance.process(frame);
for (let i = 0; i < pcm.length - engineInstance.frameLength; i += engineInstance.frameLength) {
const [partialTranscript, partialIsEndpoint] = engineInstance.process(pcm.slice(i, i + engineInstance.frameLength));
transcript += partialTranscript;

@@ -64,45 +102,78 @@ isEndpoint = partialIsEndpoint;

return [transcript, isEndpoint];
}
};
describe("Defaults", () => {
test("successful process", () => {
let cheetahEngine = new Cheetah(ACCESS_KEY);
let [transcript, isEndpoint] = cheetahProcessWaveFile(
cheetahEngine,
WAV_PATH
);
const testCheetahProcess = (
_: string,
transcript: string,
testPunctuation: boolean,
errorRate: number,
audioFile: string
) => {
let cheetahEngine = new Cheetah(ACCESS_KEY, {
enableAutomaticPunctuation: testPunctuation,
});
expect(transcript).toBe(TRANSCRIPT);
expect(isEndpoint).toBe(false);
let [res, __] = cheetahProcessWaveFile(cheetahEngine, audioFile);
cheetahEngine.release();
});
expect(
characterErrorRate(res, transcript) < errorRate
).toBeTruthy();
test("successful process with endpoint detection", () => {
let cheetahEngine = new Cheetah(ACCESS_KEY, {endpointDurationSec: 0.2});
cheetahEngine.release();
};
let [transcript, isEndpoint] = cheetahProcessWaveFile(
cheetahEngine,
WAV_PATH
);
describe('successful processes', () => {
it.each(TEST_PARAMETERS)(
'testing process `%p`',
(
language: string,
transcript: string,
_: string,
errorRate: number,
audioFile: string
) => {
testCheetahProcess(
language,
transcript,
false,
errorRate,
audioFile
);
}
);
expect(transcript).toBe(TRANSCRIPT);
expect(isEndpoint).toBe(true);
it.each(TEST_PARAMETERS)(
'testing process `%p` with punctuation',
(
language: string,
_: string,
transcriptWithPunctuation: string,
errorRate: number,
audioFile: string
) => {
testCheetahProcess(
language,
transcriptWithPunctuation,
true,
errorRate,
audioFile
);
}
);
});
cheetahEngine.release();
});
test("Empty AccessKey", () => {
describe('Defaults', () => {
test('Empty AccessKey', () => {
expect(() => {
let cheetahEngine = new Cheetah("");
}).toThrow(CheetahInvalidArgumentError);
new Cheetah('');
}).toThrow(CheetahErrors.CheetahInvalidArgumentError);
});
});
describe("manual paths", () => {
test("manual model path", () => {
let cheetahEngine = new Cheetah(ACCESS_KEY, {modelPath: MODEL_PATH});
describe('manual paths', () => {
test('manual model path', () => {
let cheetahEngine = new Cheetah(ACCESS_KEY, { modelPath: MODEL_PATH });
let [transcript, isEndpoint] = cheetahProcessWaveFile(
let [transcript, _] = cheetahProcessWaveFile(
cheetahEngine,

@@ -113,13 +184,13 @@ WAV_PATH

expect(transcript).toBe(TRANSCRIPT);
expect(isEndpoint).toBe(false);
cheetahEngine.release();
});
test("manual model and library path", () => {
let cheetahEngine = new Cheetah(
ACCESS_KEY,
{modelPath: MODEL_PATH, libraryPath: libraryPath, endpointDurationSec: 0.2});
test('manual model and library path', () => {
let cheetahEngine = new Cheetah(ACCESS_KEY, {
modelPath: MODEL_PATH,
libraryPath: libraryPath,
endpointDurationSec: 0.2,
});
let [transcript, isEndpoint] = cheetahProcessWaveFile(
let [transcript, _] = cheetahProcessWaveFile(
cheetahEngine,

@@ -130,21 +201,26 @@ WAV_PATH

expect(transcript).toBe(TRANSCRIPT);
expect(isEndpoint).toBe(true);
cheetahEngine.release();
});
});
test("Enable automatic punctuation", () => {
let cheetahEngine = new Cheetah(
ACCESS_KEY,
{enableAutomaticPunctuation: true, endpointDurationSec: 0.2});
describe("error message stack", () => {
test("message stack cleared after read", () => {
let error: string[] = [];
try {
new Cheetah('invalid', { modelPath: MODEL_PATH });
} catch (e: any) {
error = e.messageStack;
}
let [transcript, _] = cheetahProcessWaveFile(
cheetahEngine,
WAV_PATH
);
expect(error.length).toBeGreaterThan(0);
expect(error.length).toBeLessThanOrEqual(8);
expect(transcript).toBe('Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel.');
cheetahEngine.release();
try {
new Cheetah('invalid', { modelPath: MODEL_PATH });
} catch (e: any) {
for (let i = 0; i < error.length; i++) {
expect(error[i]).toEqual(e.messageStack[i]);
}
}
});
});
//
// Copyright 2022 Picovoice Inc.
// Copyright 2022-2023 Picovoice Inc.
//

@@ -11,36 +11,35 @@ // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"

//
"use strict";
'use strict';
import {Cheetah, getInt16Frames} from "../src";
import * as fs from "fs";
import * as path from "path";
import {performance} from "perf_hooks";
import { Cheetah, getInt16Frames } from '../src';
import * as fs from 'fs';
import * as path from 'path';
import { performance } from 'perf_hooks';
import {WaveFile} from "wavefile";
import { WaveFile } from 'wavefile';
const WAV_PATH = "../../../resources/audio_samples/test.wav";
const WAV_PATH = '../../../resources/audio_samples/test.wav';
const ACCESS_KEY =
process.argv
.filter((x) => x.startsWith("--access_key="))[0]
?.split("--access_key=")[1] ?? "";
.filter(x => x.startsWith('--access_key='))[0]
?.split('--access_key=')[1] ?? '';
const NUM_TEST_ITERATIONS = Number(
process.argv
.filter((x) => x.startsWith("--num_test_iterations="))[0]
?.split("--num_test_iterations=")[1] ?? 0
.filter(x => x.startsWith('--num_test_iterations='))[0]
?.split('--num_test_iterations=')[1] ?? 0
);
const INIT_PERFORMANCE_THRESHOLD_SEC = Number(
process.argv
.filter((x) => x.startsWith("--init_performance_threshold_sec="))[0]
?.split("--init_performance_threshold_sec=")[1] ?? 0
.filter(x => x.startsWith('--init_performance_threshold_sec='))[0]
?.split('--init_performance_threshold_sec=')[1] ?? 0
);
const PROC_PERFORMANCE_THRESHOLD_SEC = Number(
process.argv
.filter((x) => x.startsWith("--proc_performance_threshold_sec="))[0]
?.split("--proc_performance_threshold_sec=")[1] ?? 0
.filter(x => x.startsWith('--proc_performance_threshold_sec='))[0]
?.split('--proc_performance_threshold_sec=')[1] ?? 0
);
describe("Performance", () => {
test("init performance", () => {
describe('Performance', () => {
test('init performance', () => {
let perfResults = [];

@@ -50,3 +49,3 @@ for (let i = 0; i < NUM_TEST_ITERATIONS; i++) {

let cheetahEngine = new Cheetah(ACCESS_KEY);
let init_time = performance.now() - before;
let initTime = performance.now() - before;

@@ -56,3 +55,3 @@ cheetahEngine.release();

if (i > 0) {
perfResults.push(init_time);
perfResults.push(initTime);
}

@@ -63,8 +62,8 @@ }

let avgPerfSec = Number((avgPerfMs / 1000).toFixed(3));
console.log("Average init performance: " + avgPerfSec);
// eslint-disable-next-line no-console
console.log('Average init performance: ' + avgPerfSec);
expect(avgPerfSec).toBeLessThanOrEqual(INIT_PERFORMANCE_THRESHOLD_SEC);
});
test("proc performance", () => {
test('proc performance', () => {
let cheetahEngine = new Cheetah(ACCESS_KEY);

@@ -79,3 +78,3 @@

for (let i = 0; i < NUM_TEST_ITERATIONS; i++) {
let totalProcTime = 0
let totalProcTime = 0;
for (let i = 0; i < frames.length; i++) {

@@ -97,5 +96,6 @@ const frame = frames[i];

let avgPerfSec = Number((avgPerfMs / 1000).toFixed(3));
console.log("Average proc performance: " + avgPerfSec);
// eslint-disable-next-line no-console
console.log('Average proc performance: ' + avgPerfSec);
expect(avgPerfSec).toBeLessThanOrEqual(PROC_PERFORMANCE_THRESHOLD_SEC);
});
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc