@sign-speak/react-sdk
Version:
Unlock Sign Language Recognition, Avatar, and Speech Recognition.
303 lines (302 loc) • 15.5 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
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 __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SignSpeakWebSocket = void 0;
var key_1 = require("./key");
var SignSpeakWebSocket = /** @class */ (function () {
function SignSpeakWebSocket(config, onPrediction) {
this.config = config;
this.socket = null;
this.mediaRecorder = null;
this.stream = null;
this.isConnected = false;
this.onPrediction = onPrediction;
}
/**
* Initializes the WebSocket connection.
*/
SignSpeakWebSocket.prototype.connect = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (this.isConnected) {
console.warn("WebSocket already connected.");
return [2 /*return*/];
}
this.socket = new WebSocket("wss://api.sign-speak.com/stream-recognize-sign");
return [2 /*return*/, new Promise(function (resolve, reject) {
_this.socket.addEventListener("open", function () {
// Send configuration details including API key and any other custom settings.
var _a = _this.config, deviceId = _a.deviceId, includeFeedback = _a.includeFeedback, singleRecognitionMode = _a.singleRecognitionMode, model = _a.model, sliceLength = _a.sliceLength, configWithoutDeviceId = __rest(_a, ["deviceId", "includeFeedback", "singleRecognitionMode", "model", "sliceLength"]);
_this.socket.send(JSON.stringify(__assign({ api_key: (0, key_1.getKey)(), model: model, single_recognition_mode: singleRecognitionMode !== null && singleRecognitionMode !== void 0 ? singleRecognitionMode : false, slice_length: sliceLength !== null && sliceLength !== void 0 ? sliceLength : 500 }, configWithoutDeviceId)));
_this.isConnected = true;
resolve();
});
_this.socket.addEventListener("error", function (err) {
reject(err);
});
_this.socket.addEventListener("message", function (event) { return _this.handleMessage(event); });
_this.socket.addEventListener("close", function (event) {
_this.socket = null;
_this.isConnected = false;
});
})];
});
});
};
/**
* Handles incoming messages from the WebSocket.
*/
SignSpeakWebSocket.prototype.handleMessage = function (event) {
var data;
try {
data = JSON.parse(event.data);
}
catch (err) {
console.warn("Received non-JSON from recognition socket:", event.data);
return;
}
if (data === "OUT_OF_QUOTA") {
console.error("SignSpeak quota exceeded.");
return;
}
this.onPrediction(data);
};
/**
* Streams live video from a MediaDevice.
* If a deviceId is specified in the config, it will be used.
*/
SignSpeakWebSocket.prototype.streamLiveVideo = function () {
var _a;
return __awaiter(this, void 0, void 0, function () {
var constraints, _b, isChrome, options;
var _this = this;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!this.isConnected) {
throw new Error("WebSocket connection not established. Call `connect()` first.");
}
constraints = {
video: this.config.deviceId
? { deviceId: { exact: this.config.deviceId } }
: true,
};
_b = this;
return [4 /*yield*/, navigator.mediaDevices.getUserMedia(constraints)];
case 1:
_b.stream = _c.sent();
isChrome = navigator.userAgent.includes("chrome") &&
!navigator.userAgent.includes("edge") &&
!navigator.userAgent.includes("opr") &&
!navigator.userAgent.includes("crios");
options = isChrome
? { bitsPerSecond: 1000000, mimeType: "video/webm;codecs=VP9" }
: { bitsPerSecond: 1000000 };
this.mediaRecorder = new MediaRecorder(this.stream, options);
this.mediaRecorder.ondataavailable = function (e) {
var blob = new Blob([e.data], { type: "video/mp4" });
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = function () {
if (reader.result && _this.socket) {
_this.socket.send(reader.result);
}
};
};
this.mediaRecorder.start((_a = this.config.sliceLength) !== null && _a !== void 0 ? _a : 500);
return [2 /*return*/];
}
});
});
};
/**
* Streams video segments over the WebSocket asynchronously.
* Accepts an async iterable (or generator) that yields video segments (File or Blob)
* one at a time. Each segment is sent over the WebSocket with a delay matching sliceLength.
*
* This method can be used instead of streamLiveVideo() if you wish to provide
* your own video segments asynchronously.
*
* @param videoStream An async iterable of video segments (File or Blob).
*/
SignSpeakWebSocket.prototype.streamVideoSegments = function (videoStream) {
var _a, videoStream_1, videoStream_1_1;
var _b, e_1, _c, _d;
var _e;
return __awaiter(this, void 0, void 0, function () {
var video, arrayBuffer, e_1_1;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
if (!this.isConnected) {
throw new Error("WebSocket connection not established. Call `connect()` first.");
}
_f.label = 1;
case 1:
_f.trys.push([1, 9, 10, 15]);
_a = true, videoStream_1 = __asyncValues(videoStream);
_f.label = 2;
case 2: return [4 /*yield*/, videoStream_1.next()];
case 3:
if (!(videoStream_1_1 = _f.sent(), _b = videoStream_1_1.done, !_b)) return [3 /*break*/, 8];
_d = videoStream_1_1.value;
_a = false;
_f.label = 4;
case 4:
_f.trys.push([4, , 6, 7]);
video = _d;
return [4 /*yield*/, video.arrayBuffer()];
case 5:
arrayBuffer = _f.sent();
(_e = this.socket) === null || _e === void 0 ? void 0 : _e.send(arrayBuffer);
return [3 /*break*/, 7];
case 6:
_a = true;
return [7 /*endfinally*/];
case 7: return [3 /*break*/, 2];
case 8: return [3 /*break*/, 15];
case 9:
e_1_1 = _f.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 15];
case 10:
_f.trys.push([10, , 13, 14]);
if (!(!_a && !_b && (_c = videoStream_1.return))) return [3 /*break*/, 12];
return [4 /*yield*/, _c.call(videoStream_1)];
case 11:
_f.sent();
_f.label = 12;
case 12: return [3 /*break*/, 14];
case 13:
if (e_1) throw e_1.error;
return [7 /*endfinally*/];
case 14: return [7 /*endfinally*/];
case 15: return [2 /*return*/];
}
});
});
};
/**
* Stops the streaming process and sends a termination signal.
* @param closeSocket If true, the WebSocket connection will close.
*/
SignSpeakWebSocket.prototype.stopStreaming = function (closeSocket) {
if (closeSocket === void 0) { closeSocket = true; }
return __awaiter(this, void 0, void 0, function () {
var finalDataPromise;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.mediaRecorder) return [3 /*break*/, 2];
// We need to wait for the final mediarecorder packet before sending the close signal.
// If we do not, the final slice_length will be cut off.
this.mediaRecorder.ondataavailable = null;
finalDataPromise = new Promise(function (resolve, reject) {
_this.mediaRecorder.addEventListener("dataavailable", function (e) {
var blob = new Blob([e.data], { type: "video/mp4" });
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = function () {
if (reader.result && _this.socket) {
_this.socket.send(reader.result);
}
resolve();
};
reader.onerror = reject;
}, { once: true });
});
this.mediaRecorder.stop();
return [4 /*yield*/, finalDataPromise];
case 1:
_a.sent();
_a.label = 2;
case 2:
// Send the termination signal.
if (this.socket) {
this.socket.send(closeSocket ? "DONE" : "NEXT");
}
return [2 /*return*/];
}
});
});
};
/**
* Disconnects the WebSocket.
*/
SignSpeakWebSocket.prototype.disconnect = function () {
var _a;
if (this.isConnected) {
(_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
this.socket = null;
this.isConnected = false;
}
};
return SignSpeakWebSocket;
}());
exports.SignSpeakWebSocket = SignSpeakWebSocket;