New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@privateid/cryptonets-web-sdk

Package Overview
Dependencies
Maintainers
5
Versions
226
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@privateid/cryptonets-web-sdk - npm Package Compare versions

Comparing version 2.0.8-alpha to 2.0.9-alpha

29

dist/apiUtils.d.ts

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

import { Base64 } from './types';
import { Base64, DLType } from './types';
export declare const postImages: (image: Base64) => Promise<Response>;

@@ -18,6 +18,27 @@ /**

export declare function getUser(uuid: string): Promise<string>;
export declare function sendVerifyCode({ guid, phone, pin }: {
guid: string;
export declare function sendSmsCode({ id, phone }: {
id: string;
phone: string;
pin: string;
}): Promise<string>;
export declare function sendEnrollSms({ id }: {
id: string;
}): Promise<string>;
export declare function uploadPortrait({ id, portrait }: {
id: string;
portrait: string;
}): Promise<string>;
declare type UploadDlProps = {
id: string;
type: DLType;
image: string;
barcode?: string;
};
export declare function uploadDL({ id, type, image, barcode }: UploadDlProps): Promise<string>;
export declare function getStatus({ id }: {
id: string;
}): Promise<string>;
export declare function updateUser({ id, attributes }: {
id: string;
attributes: any;
}): Promise<string>;
export {};

@@ -114,7 +114,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

hostUrl: window.location.href,
version: "1.0",
version: '1.0',
api_key: process.env.REACT_APP_API_KEY,
email_address: email,
token,
action: "exact_url"
action: 'exact_url',
}),

@@ -157,6 +157,6 @@ };

body: JSON.stringify({
userPoolId: "us-east-1_YUVlMRGQO",
userPoolId: 'us-east-1_YUVlMRGQO',
username: email,
attributeName,
attributeValue
attributeValue,
}),

@@ -173,4 +173,4 @@ };

body: JSON.stringify({
userPoolId: "us-east-1_YUVlMRGQO",
UUID: uuid.substring(0, 16)
userPoolId: 'us-east-1_YUVlMRGQO',
UUID: uuid.substring(0, 16),
}),

@@ -182,17 +182,70 @@ };

}
export function sendVerifyCode({ guid, phone, pin }) {
export function sendSmsCode({ id, phone }) {
return __awaiter(this, void 0, void 0, function* () {
const requestOptions = {
method: 'POST',
body: JSON.stringify({
guid,
phone,
type: 'phone',
pin,
}),
body: JSON.stringify({ guid: id, phone }),
};
const res = yield fetch(`${apiUrl}/user/send_code`, requestOptions);
const res = yield fetch(`${apiUrl}/user/sms_code`, requestOptions);
return res.json();
});
}
export function sendEnrollSms({ id }) {
return __awaiter(this, void 0, void 0, function* () {
const requestOptions = {
method: 'POST',
body: JSON.stringify({ token: id }),
};
const res = yield fetch(`${apiUrl}/user/send_redirectSms`, requestOptions);
return res.json();
});
}
export function uploadPortrait({ id, portrait }) {
return __awaiter(this, void 0, void 0, function* () {
const requestOptions = {
method: 'POST',
body: JSON.stringify({ token: id, portrait }),
};
const res = yield fetch(`${apiUrl}/user/upload/portrait`, requestOptions);
return res.json();
});
}
export function uploadDL({ id, type, image, barcode }) {
return __awaiter(this, void 0, void 0, function* () {
const payload = {
token: id,
type,
image,
barcode,
};
const requestOptions = {
method: 'POST',
body: JSON.stringify(payload),
};
const res = yield fetch(`${apiUrl}/user/upload/dl`, requestOptions);
return res.json();
});
}
export function getStatus({ id }) {
return __awaiter(this, void 0, void 0, function* () {
const payload = { token: id };
const requestOptions = {
method: 'POST',
body: JSON.stringify(payload),
};
const res = yield fetch(`${apiUrl}/user/status`, requestOptions);
return res.json();
});
}
export function updateUser({ id, attributes }) {
return __awaiter(this, void 0, void 0, function* () {
const payload = { token: id, attributes };
const requestOptions = {
method: 'POST',
body: JSON.stringify(payload),
};
const res = yield fetch(`${apiUrl}/user/update`, requestOptions);
return res.json();
});
}
//# sourceMappingURL=apiUtils.js.map

@@ -0,0 +0,0 @@ declare let mediaStream: MediaStream;

@@ -0,0 +0,0 @@ let mediaStream = null;

@@ -0,0 +0,0 @@ export declare const facingMode: {

@@ -0,0 +0,0 @@ export const facingMode = {

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -9,3 +9,3 @@ import { CameraFaceMode, FaceStatuses, Base64, DocType } from './types';

*/
export declare const openCamera: (domElement: string, requireHD?: boolean | null, deviceId?: string | null, requestFaceMode?: CameraFaceMode | null) => Promise<{
export declare const openCamera: (domElement: string, requireHD: boolean, deviceId?: string | null, requestFaceMode?: CameraFaceMode | null) => Promise<{
stream: MediaStream | null;

@@ -32,3 +32,7 @@ devices: MediaDeviceInfo[] | null;

*/
export declare const isValid: (action?: boolean, image?: ImageData) => Promise<{
export declare const isValid: (action: boolean, callback: (input: {
status: FaceStatuses;
result?: number;
returnValue?: any;
}) => void, image?: ImageData) => Promise<{
result: number | string;

@@ -98,2 +102,16 @@ imageData?: ImageData;

}, element?: string, deviceId?: string): Promise<unknown>;
export declare function enrollOneFA(callback: (input: {
status: FaceStatuses;
result?: number;
returnValue?: any;
progress?: number;
portrait?: Base64;
}) => void, element?: string, deviceId?: string): Promise<unknown>;
export declare function predictOneFA(callback: (input: {
status: FaceStatuses;
result?: number;
returnValue?: any;
progress?: number;
portrait?: Base64;
}) => void, element?: string, deviceId?: string): Promise<unknown>;
/**

@@ -112,3 +130,2 @@ * This function performs continuious predict/enroll, the camera should already be open. the functions performs the identification return the result then restart again.

}) => void): Promise<void>;
export declare function checkPhoneVersions(): Promise<boolean>;
export {};

245

dist/faceModule.js

@@ -17,3 +17,3 @@ /* eslint-disable default-param-last */

import { proxy } from 'comlink';
import { isValidInternal, FHE_enroll, createImages, getDebugType, getIsSIMD, iOS, isMobileFunc, scanDocument, deleteUUID, getPortraitBase64, isValidBarCode, printLogs, setDefaultCameraDeviceId, getDefaultCameraDeviceId, } from './utils';
import { isValidInternal, FHE_enroll, FHE_enrollOnefa, FHE_predictOnefa, createImages, getDebugType, getIsSIMD, iOS, isMobileFunc, scanDocument, deleteUUID, getPortraitBase64, isValidBarCode, printLogs, setDefaultCameraDeviceId, getDefaultCameraDeviceId, } from './utils';
import { CameraFaceMode, ImageType, FaceStatuses, DocType, LOGTYPE } from './types';

@@ -55,5 +55,5 @@ import { facingMode } from './constants';

const isResponse = response_str.length > 0;
// console.log('================[JS RESPONSE]: response_str', isResponse ? JSON.parse(response_str) : '');
// console.log('[JS RESPONSE]: operation', operation || 'null');
// console.log('[JS RESPONSE]: id', id || 'null');
console.log('================[JS RESPONSE]: response_str', isResponse ? JSON.parse(response_str) : '');
console.log('[JS RESPONSE]: operation', operation || 'null');
console.log('[JS RESPONSE]: id', id || 'null');
if (isResponse) {

@@ -71,5 +71,5 @@ const returnValue = JSON.parse(response_str);

const isResponse = response_str.length > 0;
// console.log('================[JS RESPONSE]: response_str', isResponse ? JSON.parse(response_str) : '');
// console.log('[JS RESPONSE]: operation', operation || 'null');
// console.log('[JS RESPONSE]: id', id || 'null');
console.log('================[JS RESPONSE]: response_str', isResponse ? JSON.parse(response_str) : '');
console.log('[JS RESPONSE]: operation', operation || 'null');
console.log('[JS RESPONSE]: id', id || 'null');
if (isResponse) {

@@ -82,2 +82,15 @@ const returnValue = JSON.parse(response_str);

};
const createResultIsValid = (callback) => (operation, id, response_str) => {
const isResponse = response_str.length > 0;
console.log('================[JS RESPONSE]: response_str', isResponse ? JSON.parse(response_str) : '');
console.log('[JS RESPONSE]: operation', operation || 'null');
console.log('[JS RESPONSE]: id', id || 'null');
if (isResponse) {
const returnValue = JSON.parse(response_str);
const { result } = returnValue;
if (operation === 'is_valid') {
callback({ status: FaceStatuses.WASM_RESPONSE, result, returnValue });
}
}
};
export const deleteUser = (uuid, callback) => {

@@ -102,3 +115,2 @@ printLogs('----1-----', '', debugType);

}
printLogs("devices after filter", { requestFaceMode, devices }, debugType);
let stream;

@@ -198,2 +210,3 @@ let hasError = true;

videoElement = domElement;
yield navigator.mediaDevices.getUserMedia({ audio: false, video: true });
try {

@@ -246,3 +259,3 @@ let devices = [];

*/
export const openCamera = (domElement, requireHD = false, deviceId = null, requestFaceMode = null) => __awaiter(void 0, void 0, void 0, function* () {
export const openCamera = (domElement, requireHD, deviceId = null, requestFaceMode = null) => __awaiter(void 0, void 0, void 0, function* () {
videoElement = domElement;

@@ -276,2 +289,3 @@ faceMode = requestFaceMode;

devices = devices.filter((d) => d.kind === 'videoinput');
console.log('====> video input device available', devices);
printLogs('=====> MY DEVICES??? ', devices, debugType);

@@ -303,13 +317,14 @@ if (devices.length === 0) {

}, []);
console.log('====> devices after filtering from require HD ', devices);
}
if (devices.length === 0) {
return {
stream: null,
devices: null,
faceMode: null,
settings: null,
status: false,
errorMessage: requireHD ? 'No HD camera found' : 'No camera found',
};
}
// if (devices.length === 0) {
// return {
// stream: null,
// devices: null,
// faceMode: null,
// settings: null,
// status: false,
// errorMessage: requireHD ? 'No HD camera found' : 'No camera found',
// };
// }
// eslint-disable-next-line @typescript-eslint/ban-ts-comment

@@ -344,3 +359,4 @@ // @ts-ignore

stream = yield navigator.mediaDevices.getUserMedia(constraints);
hasError = false;
if (stream)
hasError = false;
}

@@ -368,3 +384,4 @@ catch (e) {

stream = yield navigator.mediaDevices.getUserMedia(constraints);
hasError = false;
if (stream)
hasError = false;
}

@@ -379,3 +396,3 @@ catch (e) {

}
console.log('video tracks?', stream.getVideoTracks());
// console.log('video tracks?', stream.getVideoTracks());
const track = stream.getVideoTracks()[0];

@@ -412,8 +429,5 @@ const capabilities = track.getCapabilities();

let devices = [];
yield navigator.mediaDevices.getUserMedia({ video: true, audio: false }).then((mediaStream) => {
const stream = mediaStream;
const tracks = stream.getTracks();
// console.log('tracks to stop', tracks);
tracks.forEach((track) => track.stop());
});
if (mediaStream) {
mediaStream.getTracks().forEach((track) => track.stop());
}
devices = yield navigator.mediaDevices.enumerateDevices();

@@ -433,4 +447,2 @@ devices = devices.filter((d) => d.kind === 'videoinput');

const deviceCapabilites = getDefaultDevice();
console.log('switch device capabilities', { deviceCapabilites });
// if(deviceCapabilites.length >0 )
const getBestResolution = () => __awaiter(void 0, void 0, void 0, function* () {

@@ -467,24 +479,23 @@ let resolution = deviceCapabilites[0].width.max > 2560 ? 2560 : deviceCapabilites[0].width.max;

// eslint-disable-next-line no-nested-ternary
const constraints = {
audio: false,
video: {
width: { ideal: cameraWidthMobile },
height: { ideal: cameraHeightMobile },
facingMode: facingMode[faceMode],
},
};
const constraints = isMobileFunc()
? {
audio: false,
video: {
width: { min: 1280, ideal: cameraWidthMobile },
height: { min: 720, ideal: cameraHeightMobile },
facingMode: facingMode[faceMode],
},
}
: {
audio: false,
video: {
width: { ideal: cameraWidth },
height: { ideal: cameraHeight },
facingMode: faceMode,
deviceId: mediaDevice,
},
};
let stream;
if (isMobileFunc()) {
printLogs(" Setting Mobile constraint ", "", debugType);
let hasContraintError = true;
while (hasContraintError) {
try {
stream = yield navigator.mediaDevices.getUserMedia(constraints);
hasContraintError = false;
}
catch (e) {
console.log(e);
}
}
}
if (isMobileFunc())
stream = yield navigator.mediaDevices.getUserMedia(constraints);
else

@@ -509,3 +520,4 @@ stream = yield getBestResolution();

*/
export const isValid = (action = false, image) => __awaiter(void 0, void 0, void 0, function* () {
export const isValid = (action = false, callback, image) => __awaiter(void 0, void 0, void 0, function* () {
privid_wasm_result = createResultIsValid(callback);
if (image) {

@@ -549,7 +561,10 @@ const { result } = yield isValidInternal(image.data, image.width, image.height, isSimd, action, debugType, proxy(privid_wasm_result));

}
const resultData = yield isValidInternal(imageData.data, imageData.width, imageData.height, isSimd, action, debugType, proxy(privid_wasm_result));
const { result } = resultData;
const { result } = yield isValidInternal(imageData.data, imageData.width, imageData.height, isSimd, action, debugType, proxy(privid_wasm_result));
return { result, imageData };
});
export const predictAge = (action = false, image) => __awaiter(void 0, void 0, void 0, function* () {
// const sampleCallback = (returnedData: any) => {
// console.log('ISVALID callback returned data', returnedData);
// };
// privid_wasm_result = createResultFuncIsValid(sampleCallback);
if (image) {

@@ -697,3 +712,3 @@ const result = yield isValidInternal(image.data, image.width, image.height, isSimd, action, debugType, proxy(privid_wasm_result));

while (originalImages.length < (action ? ENROLL_REQUIRED_IMAGES : PREDICT_REQUIRED_IMAGES)) {
const { result, imageData } = yield isValid(action);
const { result, imageData } = yield isValid(action, () => { });
if (typeof result === 'string')

@@ -734,2 +749,111 @@ return;

}
export function enrollOneFA(callback, element, deviceId) {
return __awaiter(this, void 0, void 0, function* () {
printLogs('--------------------ENROLL_ONE_FA-----------------------', '', debugType);
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
// let stream: MediaStream;
// if (element) {
// videoElement = element;
// const camera = await openCamera(element, false, deviceId);
// stream = camera.stream;
// }
let portrait;
setTimeout(() => __awaiter(this, void 0, void 0, function* () {
const originalImages = [];
while (originalImages.length < 10) {
let result;
let imageData;
let hasError = true;
while (hasError) {
try {
const resultData = yield isValid(true, () => { });
result = resultData.result;
imageData = resultData.imageData;
hasError = false;
}
catch (e) {
console.log(e);
}
}
if (typeof result === 'string')
return;
if (typeof result === 'number' && result === 0) {
originalImages.push(imageData);
callback({
status: FaceStatuses.VALID_FACE,
result,
progress: (originalImages.length * 100) / 10,
});
}
else {
callback({ status: FaceStatuses.INVALID_FACE, result });
}
}
portrait = yield getPortraitBase64(originalImages[0]);
privid_wasm_result = createResultFunc(callback, portrait);
const { result, href } = yield FHE_enrollOnefa(originalImages, isSimd, debugType, proxy(privid_wasm_result));
if (isDebugWithImages) {
yield createImages(href, ImageType.augmented, true);
yield createImages(originalImages, ImageType.original, true);
}
currentOperation = { operation: 'enroll', id: result };
// eslint-disable-next-line prefer-destructuring
if (result === -1) {
// eslint-disable-next-line consistent-return
return enrollOneFA(callback, element, deviceId);
}
// if (element) stream.getTracks().forEach((track) => track.stop());
resolve(portrait);
}), 1000);
}));
});
}
export function predictOneFA(callback, element, deviceId) {
return __awaiter(this, void 0, void 0, function* () {
printLogs('---------------------PREDICT_ONE_FA----------------------', '', debugType);
return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
let stream;
if (element) {
videoElement = element;
const camera = yield openCamera(element, false, deviceId);
stream = camera.stream;
}
let portrait;
setTimeout(() => __awaiter(this, void 0, void 0, function* () {
const originalImages = [];
while (originalImages.length < 1) {
const { result, imageData } = yield isValid(false, () => { });
if (typeof result === 'string')
return;
if (typeof result === 'number' && result === 0) {
originalImages.push(imageData);
callback({
status: FaceStatuses.VALID_FACE,
result,
progress: (originalImages.length * 100) / PREDICT_REQUIRED_IMAGES,
});
}
else {
callback({ status: FaceStatuses.INVALID_FACE, result });
}
}
portrait = yield getPortraitBase64(originalImages[0]);
privid_wasm_result = createResultFunc(callback, portrait);
const { result, href } = yield FHE_predictOnefa(originalImages, isSimd, debugType, proxy(privid_wasm_result));
if (isDebugWithImages) {
yield createImages(href, ImageType.augmented, true);
yield createImages(originalImages, ImageType.original, true);
}
currentOperation = { operation: 'predict', id: result };
// eslint-disable-next-line prefer-destructuring
if (result === -1) {
// eslint-disable-next-line consistent-return
return predictOneFA(callback, element, deviceId);
}
// if (element && !action) stream.getTracks().forEach((track) => track.stop());
resolve(portrait);
}), 1000);
}));
});
}
/**

@@ -749,3 +873,3 @@ * This function performs continuious predict/enroll, the camera should already be open. the functions performs the identification return the result then restart again.

while (originalImages.length < (action ? ENROLL_REQUIRED_IMAGES : PREDICT_REQUIRED_IMAGES)) {
const { result, imageData } = yield isValid(action);
const { result, imageData } = yield isValid(action, () => { });
isValidResult = result;

@@ -820,11 +944,2 @@ if (typeof result === 'string')

}
export function checkPhoneVersions() {
return __awaiter(this, void 0, void 0, function* () {
const { os, version } = detect();
if (os === "iOS" && parseInt(version, 10) < 15 || os === "android" && parseInt(version, 10) < 11) {
return true;
}
return false;
});
}
//# sourceMappingURL=faceModule.js.map

@@ -0,0 +0,0 @@ /**

@@ -0,0 +0,0 @@ /* eslint-disable camelcase */

@@ -51,2 +51,6 @@ export declare type Base64 = ArrayBuffer | string;

}
export declare enum DLType {
FRONT = "front",
BACK = "back"
}
declare global {

@@ -69,2 +73,10 @@ interface Window {

}>;
FHE_enrollOnefa: (originalImages: Array<ImageData>, simd: boolean, debug_type: string, cb: any) => Promise<{
result: number;
href: ImageData[];
}>;
FHE_predictOnefa: (originalImages: Array<ImageData>, simd: boolean, debug_type: string, cb: any) => Promise<{
result: number;
href: ImageData[];
}>;
scanDocument: (imageInput: ImageData, simd: boolean, cb: any, debug_type: string) => Promise<{

@@ -71,0 +83,0 @@ result: number;

@@ -58,2 +58,7 @@ /**

})(LOGTYPE || (LOGTYPE = {}));
export var DLType;
(function (DLType) {
DLType["FRONT"] = "front";
DLType["BACK"] = "back";
})(DLType || (DLType = {}));
//# sourceMappingURL=types.js.map

@@ -8,2 +8,8 @@ import { Base64, ImageType, LOGTYPE } from './types';

href: ImageData[];
}>, FHE_enrollOnefa: (originalImages: ImageData[], simd: boolean, debug_type: string, cb: any) => Promise<{
result: number;
href: ImageData[];
}>, FHE_predictOnefa: (originalImages: ImageData[], simd: boolean, debug_type: string, cb: any) => Promise<{
result: number;
href: ImageData[];
}>, voicePredict: (buffer: ArrayBuffer) => Promise<number>, isValidVoice: (data: ArrayBuffer, action: boolean, params: {

@@ -10,0 +16,0 @@ [key: string]: number;

@@ -15,5 +15,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

const functions = wrap(new Worker('./workers/wasm.worker.js'));
export const { isLoad, isValidInternal, FHE_enroll,
// FHE_enrollOnefa,
voicePredict, isValidVoice, scanDocument, deleteUUID, isValidBarCode, configureBlur, } = functions;
export const { isLoad, isValidInternal, FHE_enroll, FHE_enrollOnefa, FHE_predictOnefa, voicePredict, isValidVoice, scanDocument, deleteUUID, isValidBarCode, configureBlur, } = functions;
export function iOS() {

@@ -20,0 +18,0 @@ return ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform);

@@ -0,0 +0,0 @@ import { VoiceStatuses } from './types';

@@ -0,0 +0,0 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -5,3 +5,3 @@ {

"description": "CryptoNets WebAssembly SDK",
"version": "2.0.8-alpha",
"version": "2.0.9-alpha",
"keywords": [

@@ -8,0 +8,0 @@ "Face recognition",

@@ -47,3 +47,3 @@ <h1 align="center">CryptoNets WebAssembly SDK</h1>

```bsh
"prestart": "cp -R ./node_modules/@privateid/cryptonets-web-sdk/wasm public/ && cp -R ./node_modules/@privateid/cryptonets-web-sdk/workers public/",
"prestart": "cp -R ./node_modules/@privateid/cryptonets-web-sdk/wasm public/&& cp -R ./node_modules/@privateid/cryptonets-web-sdk/workers public/",
"prebuild": "cp -R ./node_modules/@privateid/cryptonets-web-sdk/wasm public/ && cp -R ./node_modules/@privateid/cryptonets-web-sdk/workers public/"

@@ -83,3 +83,3 @@ ```

const { devices, faceMode } = await openCamera(element, requireHD, deviceID, requestFaceMode);
const { devices, faceMode } = await openCamera(element);
```

@@ -89,20 +89,2 @@

##### Parameters
| Param | Description | Required | Data type |
|-----------------|------------------------------------------|----------|-------------------|
| element | Element id of the video tag in the DOM | required | string |
|-----------------|------------------------------------------|----------|-------------------|
| requiredHD | Strictly use 2560x1440 camera resolution | required | boolean |
| | (recommended for documentScan) when TRUE | | |
| | FALSE does not require strict camera | | |
| | resolution. | | |
|-----------------|------------------------------------------|----------|-------------------|
| deviceID | Camera ID of the camera to be used | optional | string |
|-----------------|------------------------------------------|----------|-------------------|
| requestFaceMode | For mobile devices, to use "front" or | optional | "front" or "back" |
| | "back" of phone camera. default: "front" | | |
|-----------------|------------------------------------------|----------|-------------------|
#### Switch to another camera

@@ -165,24 +147,2 @@

## Predict Age
Live demo: [https://age.devel.private.id]
predictAge only exercises the `is_valid()` call and does not find identity. The function detects if there is a valid face in the camera view or in an ImageData Array and then it is predicting the age of the face detected.
predictAge accepts two parameters.
- action: false for prediction (less restrictive), and true for enrollment (more restrictive). We recommend using false as your default.
- ImageData: array of an image data to perform the face captcha on (optional)
```javascript
import { predictAge } from '@privateid/cryptonets-web-sdk';
const {result, imageData, ageData} = predictAge (false);
```
Returned data:
result: Result is the status code returned by the WASM module (same with isValid).
imageData: array of an image data where the predictAge face captcha and agePredict is performed
ageData: this is an object with the age predicted by the WASM.
## Enroll or predict

@@ -234,3 +194,3 @@

| action | True (enroll) / false (predict) |
| callback | The callback to be executed on each status |
callback | The callback to be executed on each status

@@ -237,0 +197,0 @@

{
"version": "8181.1"
"version": "9271.1"
}
{
"version": "8181.0"
"version": "9271.0"
}
{
"version": "12021.009765625"
}
{
"version": "12021.009765625"
}
{
"version": "12021.009765625"
}

@@ -400,3 +400,2 @@ /* eslint-disable no-eval */

privid_wasm_result = cb;
console.log("data?", { originalImages, simd, action, debug_type, cb, config })
if (!wasmPrivModule) {

@@ -436,3 +435,3 @@ console.log('loaded for first wsm wrkr', simd, action);

let result = null;
console.log("enroll modules??", wasmPrivModule);
try {

@@ -487,3 +486,207 @@ result = wasmPrivModule._FHE_enroll_predict(

const FHE_enrollOnefa = (originalImages, simd, debug_type = 0, cb) =>
new Promise(async (resolve) => {
privid_wasm_result = cb;
if (!wasmPrivModule) {
console.log('loaded for first wsm wrkr', simd, action);
await isLoad(simd, apiUrl, apiKey, wasmModule, debugType);
}
// console.log('-------WASM----WORKER------', simd, action);
const numImages = originalImages.length;
const imageInput = flatten(
originalImages.map((x) => x.data),
Uint8Array,
);
const version = wasmPrivModule._get_version();
console.log('Version = ', version);
// const encoder = new TextEncoder();
// const config_bytes = encoder.encode(`${config}\0`);
// const configInputSize = config.length;
// const configInputPtr = wasmPrivModule._malloc(configInputSize);
// wasmPrivModule.HEAP8.set(config_bytes, configInputPtr / config_bytes.BYTES_PER_ELEMENT);
const imageInputSize = imageInput.length * imageInput.BYTES_PER_ELEMENT;
const imageInputPtr = wasmPrivModule._malloc(imageInputSize);
wasmPrivModule.HEAP8.set(imageInput, imageInputPtr / imageInput.BYTES_PER_ELEMENT);
const BufferSize = wasmPrivModule._spl_image_embedding_length();
// outupt ptr
const outputBufferSize = BufferSize * 4 * 80;
const outputBufferPtr = wasmPrivModule._malloc(outputBufferSize);
const augmBufferSize = 224 * 224 * 4 * 100;
const augmBufferPtr = wasmPrivModule._malloc(augmBufferSize);
const resultFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
// create a pointer to interger to hold the length of the output buffer
const resultLenPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
let result = null;
console.log('wasmPrivModule', wasmPrivModule);
// console.log('[FAR_DEBUG] : Calling session preparation')
const sessionFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
const s_result = wasmPrivModule._privid_initialize_session_join(sessionFirstPtr, null);
if (s_result) {
console.log('[FAR_DEBUG] : session initialized successfully');
} else {
console.log('[FAR_DEBUG] : session initialized failed');
}
// console.log('[FAR_DEBUG] : Getting session second pointer')
const [sessionSecPtr] = new Uint32Array(wasmPrivModule.HEAPU8.buffer, sessionFirstPtr, 1);
// console.log(`[FAR_DEBUG] : Session second pointer = [${ sessionSecPtr }]`)
// console.log('[FAR_DEBUG] : Calling enroll_onefa')
try {
result = await wasmPrivModule._privid_enroll_onefa(
sessionSecPtr /* session pointer */,
null /* user configuration */,
0 /* user configuration length */,
imageInputPtr /* input images */,
numImages /* number of input images */,
originalImages[0].data.length /* size of one image */,
originalImages[0].width /* width of one image */,
originalImages[0].height /* height of one image */,
null /* embeddings output */,
null /* length of embeddings out */,
true /* remove bad embeddings flag */,
null /* augmentations out buffer */,
null /* length of augmentations out buffer */,
resultFirstPtr /* operation result output buffer */,
resultLenPtr /* operation result buffer length */,
);
} catch (e) {
console.error('---------__E__-------', e);
}
// console.log('[FAR_DEBUG] : enroll_onefa done')
const href = [];
if (['900', '901', '902', '903'].includes(debug_type)) {
const num = action ? 80 : 1;
const AugmputArray = new Uint8Array(wasmPrivModule.HEAPU8.buffer, augmBufferPtr, 224 * 224 * 4 * num);
const img_width = 224;
const img_height = 224;
const dataLength = 200704;
const numImages = AugmputArray.length / dataLength;
for (let i = 0; i < numImages; i++) {
const img = AugmputArray.slice(i * dataLength, (i + 1) * dataLength);
const img_data = Uint8ClampedArray.from(img);
const image = new ImageData(img_data, img_width, img_height);
href.push(image);
}
}
wasmPrivModule._free(imageInputPtr);
wasmPrivModule._free(outputBufferPtr);
wasmPrivModule._free(augmBufferPtr);
wasmPrivModule._free(resultFirstPtr);
resolve({ result, href });
});
const FHE_predictOnefa = (originalImages, simd, debug_type = 0, cb) =>
new Promise(async (resolve) => {
privid_wasm_result = cb;
if (!wasmPrivModule) {
console.log('loaded for first wsm wrkr', simd, action);
await isLoad(simd, apiUrl, apiKey, wasmModule, debugType);
}
const numImages = originalImages.length;
const imageInput = flatten(
originalImages.map((x) => x.data),
Uint8Array,
);
const version = wasmPrivModule._get_version();
console.log('Version = ', version);
const imageInputSize = imageInput.length * imageInput.BYTES_PER_ELEMENT;
const imageInputPtr = wasmPrivModule._malloc(imageInputSize);
wasmPrivModule.HEAP8.set(imageInput, imageInputPtr / imageInput.BYTES_PER_ELEMENT);
const BufferSize = wasmPrivModule._spl_image_embedding_length();
// outupt ptr
const outputBufferSize = BufferSize * 4 * 80;
const outputBufferPtr = wasmPrivModule._malloc(outputBufferSize);
const augmBufferSize = 224 * 224 * 4 * 100;
const augmBufferPtr = wasmPrivModule._malloc(augmBufferSize);
const resultFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
// create a pointer to interger to hold the length of the output buffer
const resultLenPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
let result = null;
console.log('wasmPrivModule', wasmPrivModule);
const sessionFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
const s_result = wasmPrivModule._privid_initialize_session_join(sessionFirstPtr, null);
if (s_result) {
console.log('[FAR_DEBUG] : session initialized successfully');
} else {
console.log('[FAR_DEBUG] : session initialized failed');
}
const [sessionSecPtr] = new Uint32Array(wasmPrivModule.HEAPU8.buffer, sessionFirstPtr, 1);
try {
result = await wasmPrivModule._privid_predict_onefa(
sessionSecPtr /* session pointer */,
null /* user configuration */,
0 /* user configuration length */,
imageInputPtr /* input images */,
numImages /* number of input images */,
originalImages[0].data.length /* size of one image */,
originalImages[0].width /* width of one image */,
originalImages[0].height /* height of one image */,
null /* embeddings output */,
null /* length of embeddings out */,
true /* remove bad embeddings flag */,
null /* augmentations out buffer */,
null /* length of augmentations out buffer */,
resultFirstPtr /* operation result output buffer */,
resultLenPtr /* operation result buffer length */,
);
} catch (e) {
console.error('---------__E__-------', e);
}
const href = [];
if (['900', '901', '902', '903'].includes(debug_type)) {
const num = action ? 80 : 1;
const AugmputArray = new Uint8Array(wasmPrivModule.HEAPU8.buffer, augmBufferPtr, 224 * 224 * 4 * num);
const img_width = 224;
const img_height = 224;
const dataLength = 200704;
const numImages = AugmputArray.length / dataLength;
for (let i = 0; i < numImages; i++) {
const img = AugmputArray.slice(i * dataLength, (i + 1) * dataLength);
const img_data = Uint8ClampedArray.from(img);
const image = new ImageData(img_data, img_width, img_height);
href.push(image);
}
}
wasmPrivModule._free(imageInputPtr);
wasmPrivModule._free(outputBufferPtr);
wasmPrivModule._free(augmBufferPtr);
wasmPrivModule._free(resultFirstPtr);
resolve({ result, href });
});
const isValidInternal = (data, width, height, simd, action, debug_type = 0, cb) =>

@@ -503,10 +706,11 @@ new Promise(async (resolve) => {

const outputBufferFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
const outputBufferLenPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
// const outputBufferFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
// const outputBufferLenPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
const resultFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
// const resultFirstPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
// create a pointer to interger to hold the length of the output buffer
const resultLenPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
// const resultLenPtr = wasmPrivModule._malloc(Int32Array.BYTES_PER_ELEMENT);
wasmPrivModule._is_valid(
console.log('[FAR_DEBUG] : Calling is_valid');
const result = await wasmPrivModule._is_valid(
action,

@@ -516,23 +720,49 @@ isValidPtr,

height,
outputBufferFirstPtr,
outputBufferLenPtr,
resultFirstPtr,
resultLenPtr,
null,
0,
null, /* resultFirstPtr, */
0, /* resultLenPtr, */
);
console.log('[FAR_DEBUG] : is_valid result = ', result);
if ( result === 0 ) {
console.log('[FAR_DEBUG] : Operation executed successfully. Result shall be returned in the JS callback synchronously or asynchronously');
} else {
console.log('[FAR_DEBUG] : Operation failed to execute');
}
const [resultLength] = new Uint32Array(wasmPrivModule.HEAPU8.buffer, resultLenPtr, 1);
const [resultSecPtr] = new Uint32Array(wasmPrivModule.HEAPU8.buffer, resultFirstPtr, 1);
const resultDataArray = new Uint8Array(wasmPrivModule.HEAPU8.buffer, resultSecPtr, resultLength);
const resultString = String.fromCharCode.apply(null, resultDataArray);
const resultData = JSON.parse(resultString);
wasmPrivModule._free(outputBufferFirstPtr);
wasmPrivModule._free(outputBufferLenPtr);
wasmPrivModule._free(resultFirstPtr);
wasmPrivModule._free(resultLenPtr);
/*
console.log('[FAR_DEBUG] : is_valid result = ', result);
if ( result === 0 ) {
// The callback shall be called synchronously so after reading the result we can
// immediately free the buffer
const [resultLength] = new Uint32Array(wasmPrivModule.HEAPU8.buffer, resultLenPtr, 1);
console.log('[FAR_DEBUG] : Result Length = ', resultLength);
if (resultLength > 0) {
const [resultSecPtr] = new Uint32Array(wasmPrivModule.HEAPU8.buffer, resultFirstPtr, 1);
const resultDataArray = new Uint8Array(wasmPrivModule.HEAPU8.buffer, resultSecPtr, resultLength);
const resultString = String.fromCharCode.apply(null, resultDataArray);
console.log('[FAR_DEBUG] : Result String = ', resultString);
console.log('[FAR_DEBUG] : Freeing the internally allocated memory at ', resultFirstPtr);
wasmPrivModule._FHE_free_api_memory(resultFirstPtr);
}
// Free the local pointers
wasmPrivModule._free(resultFirstPtr);
wasmPrivModule._free(resultLenPtr);
} else if ( result < 0 ) {
// Some error occurred, so callback shall not be called and there is no memory assigned
// to provided buffer
wasmPrivModule._free(resultFirstPtr);
wasmPrivModule._free(resultLenPtr);
} else if ( result > 0 ) {
// The callback shall be called asynchronously and input buffers shall not be used as
// the results shall be returned in locally allocated buffer
wasmPrivModule._free(resultFirstPtr);
wasmPrivModule._free(resultLenPtr);
}
*/
console.log('[FAR_DEBUG] : Now freeing the locally allocated buffers');
wasmPrivModule._free(isValidPtr);
console.log('[FAR_DEBUG] : Done with is_valid');
resolve(resultData);
resolve({ result });
});

@@ -673,2 +903,4 @@

FHE_enroll,
FHE_enrollOnefa,
FHE_predictOnefa,
isValidInternal,

@@ -675,0 +907,0 @@ isLoad,

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 too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc