ibm-watson
Version:
Client library to use the IBM Watson Services
265 lines (264 loc) • 14.7 kB
JavaScript
;
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var async = require("async");
var extend = require("extend");
var isStream = require("isstream");
var common_1 = require("../lib/common");
var RecognizeStream = require("../lib/recognize-stream");
var GeneratedSpeechToTextV1 = require("./v1-generated");
/**
* Check if there is a corpus that is still being processed
* @private
* @param corporaList
* @return {boolean}
*/
function isProcessing(corporaList) {
return corporaList.corpora.some(function (record) { return record['status'] === 'being_processed'; });
}
/**
* Check if corpora has been analyzed
* @private
* @param corporaList
* @return {boolean}
*/
function isAnalyzed(corporaList) {
return corporaList.corpora.some(function (record) { return record['status'] === 'analyzed'; });
}
var SpeechToTextV1 = /** @class */ (function (_super) {
__extends(SpeechToTextV1, _super);
function SpeechToTextV1(options) {
return _super.call(this, options) || this;
}
/**
* Waits while corpora analysis status is 'being_processes', fires callback once the status is 'analyzed'
*
* Note: the code will throw an error in case there in no corpus in the customization
*
*
* @param {Object} params The parameters
* @param {String} params.customization_id - The GUID of the custom language model
* @param {Number} [params.interval=5000] - (milliseconds) - how long to wait between status checks
* @param {Number} [params.times=30] - maximum number of attempts
* @param {Function} callback
*/
SpeechToTextV1.prototype.whenCorporaAnalyzed = function (params) {
return __awaiter(this, void 0, void 0, function () {
var self, res, result, sttError, err_1, options;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, self.listCorpora({
customizationId: params === null || params === void 0 ? void 0 : params.customizationId
})];
case 2:
res = _a.sent();
result = res.result;
if (!result.corpora.length) {
sttError = new Error('Customization has no corpa and therefore corpus cannot be analyzed');
sttError.code = SpeechToTextV1.ERR_NO_CORPORA;
return [2 /*return*/, Promise.reject(sttError)];
}
return [3 /*break*/, 4];
case 3:
err_1 = _a.sent();
return [2 /*return*/, Promise.reject(err_1)];
case 4:
options = extend({
interval: 5000,
times: 30
}, params, {
errorFilter: function (err) {
// if it's a timeout error, then listCorpora is called again after params.interval
// otherwise the error is passed back to the user
// if the params.times limit is reached, the error will be passed to the user regardless
return err.code === SpeechToTextV1.ERR_TIMEOUT;
}
});
return [2 /*return*/, async.retry(options, function (done) { return __awaiter(_this, void 0, void 0, function () {
var res, corpora, sttError, err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, self.listCorpora({
customizationId: params === null || params === void 0 ? void 0 : params.customizationId
})];
case 1:
res = _a.sent();
corpora = res.result;
if (corpora !== undefined && isProcessing(corpora)) {
sttError = new Error('Corpora is still being processed, try increasing interval or times params');
sttError.code = SpeechToTextV1.ERR_TIMEOUT;
done(sttError);
}
else if (corpora !== undefined && isAnalyzed(corpora)) {
done(null, corpora);
}
else {
done(new Error('Unexpected corpus analysis status'));
}
return [3 /*break*/, 3];
case 2:
err_2 = _a.sent();
done(err_2);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); })];
}
});
});
};
SpeechToTextV1.prototype.recognizeUsingWebSocket = function (params) {
var streamParams = extend(params, {}, {
// pass the Authenticator to the RecognizeStream object
authenticator: this.getAuthenticator(),
serviceUrl: this.baseOptions.serviceUrl,
// if the user configured a custom https client, use it in the websocket method
// let httpsAgent take precedence, default to null
agent: this.baseOptions.httpsAgent || this.baseOptions.httpAgent || null,
// allow user to disable ssl verification when using websockets
disableSslVerification: this.baseOptions.disableSslVerification
});
// include analytics headers
var sdkHeaders = (0, common_1.getSdkHeaders)('speech_to_text', 'v1', 'recognizeUsingWebSocket');
streamParams.headers = extend(true, sdkHeaders, streamParams.headers);
return new RecognizeStream(streamParams);
};
SpeechToTextV1.prototype.recognize = function (params) {
if (params && params.audio && isStream(params.audio) && !params.contentType) {
return Promise.reject(new Error('If providing `audio` as a Stream, `contentType` is required.'));
}
return _super.prototype.recognize.call(this, params);
};
/**
* Waits while a customization status is 'pending' or 'training', fires callback once the status is 'ready' or 'available'.
*
* Note: the customization will remain in 'pending' status until at least one word corpus is added.
*
* See http://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#list_models for status details.
*
* @param {Object} params The parameters
* @param {String} params.customization_id - The GUID of the custom language model
* @param {Number} [params.interval=5000] - (milliseconds) - how log to wait between status checks
* @param {Number} [params.times=30] - maximum number of attempts
* @param {Function} callback
*/
SpeechToTextV1.prototype.whenCustomizationReady = function (params) {
return __awaiter(this, void 0, void 0, function () {
var self, options;
var _this = this;
return __generator(this, function (_a) {
self = this;
options = extend({
interval: 5000,
times: 30
}, params, {
errorFilter: function (err) {
// if it's a timeout error, then getLanguageModel is called again after params.interval
// otherwise the error is passed back to the user
// if the params.times limit is reached, the error will be passed to the user regardless
return err.code === SpeechToTextV1.ERR_TIMEOUT;
}
});
return [2 /*return*/, async.retry(options, function (done) { return __awaiter(_this, void 0, void 0, function () {
var res, customization, sttError, err_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, self.getLanguageModel({
customizationId: params === null || params === void 0 ? void 0 : params.customizationId
})];
case 1:
res = _a.sent();
customization = res.result;
if (customization.status === 'pending' ||
customization.status === 'training') {
sttError = new Error('Customization is still pending, try increasing interval or times params');
sttError.code = SpeechToTextV1.ERR_TIMEOUT;
done(sttError);
}
else if (customization.status === 'ready' ||
customization.status === 'available') {
done(null, customization);
}
else if (customization.status === 'failed') {
done(new Error('Customization training failed'));
}
else {
done(new Error('Unexpected customization status: ' + customization.status));
}
return [3 /*break*/, 3];
case 2:
err_3 = _a.sent();
done(err_3);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); })];
});
});
};
SpeechToTextV1.ERR_NO_CORPORA = 'ERR_NO_CORPORA';
SpeechToTextV1.ERR_TIMEOUT = 'ERR_TIMEOUT';
return SpeechToTextV1;
}(GeneratedSpeechToTextV1));
module.exports = SpeechToTextV1;