UNPKG

ekyc-sdk-arm

Version:

Automated Recognition Module

2 lines (1 loc) 10.6 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("face-api.js"),require("axios")):"function"==typeof define&&define.amd?define(["exports","face-api.js","axios"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["Narucha Narin"]={},e.FaceAPI,e.axios)}(this,(function(e,t,s){"use strict";function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function n(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var o,a,r,h=n(t),c=i(s);!function(e){e.FacingLeft="FacingLeft",e.FacingRight="FacingRight",e.MouthOpen="MouthOpen",e.Smiling="Smiling"}(o||(o={})),function(e){e.GET_RESULT="GET_RESULT",e.SAVE_TRANSACTION="SAVE_TRANSACTION",e.ERROR_API="ERROR_API"}(a||(a={})),function(e){e.CONSUMER="CONSUMER",e.APIKEY="APIKEY",e.JWT="JWT"}(r||(r={}));class u{AxiosCall;Path;ApiKey;TypeCall;constructor(e,t,s){this.Path=t,this.ApiKey=e,this.TypeCall=s;var i={};switch(s){case r.APIKEY:i={"x-api-key":this.ApiKey};break;case r.CONSUMER:i={"x-consumer-custom-id":this.ApiKey};break;case r.JWT:i={Authorization:`Bearer ${this.ApiKey}`}}this.AxiosCall=c.default.create({baseURL:this.Path,headers:i})}async GetConfig(){try{return await this.AxiosCall.get("/v1/liveness/config").then((e=>e.data))}catch(e){throw c.default.isAxiosError(e)?e.response?.data:new Error("different error than axios")}}async CreateSession(e){try{return await this.AxiosCall.post("/v1/liveness/session",e).then((e=>e.data))}catch(e){throw c.default.isAxiosError(e)?e.response?.data:new Error("different error than axios")}}async SaveTransaction(e){const t=new FormData;t.append("image",e.image),t.append("is_timeout",e.is_timeout.toString()),t.append("session_id",e.session_id),t.append("question_no",e.question_no.toString()),t.append("round",e.round.toString()),t.append("question",e.question);try{return await this.AxiosCall.post("/v1/liveness/save_trx",t).then((e=>e.data))}catch(e){if(c.default.isAxiosError(e))throw e.response?.data;throw e}}SetPathAPI(e){this.Path=e,this.AxiosCall=c.default.create({baseURL:this.Path})}GetPathAPI(){return this.Path}SetApiKey(e){this.ApiKey=e}GetApiKey(){return this.ApiKey}SetTypeCall(e){this.TypeCall=e;var t={};switch(e){case r.APIKEY:t={"x-api-key":this.ApiKey};break;case r.CONSUMER:t={"x-consumer-custom-id":this.ApiKey};break;case r.JWT:t={Authentication:`Bearer ${this.ApiKey}`}}this.AxiosCall=c.default.create({baseURL:this.Path,headers:t})}GetTypeCall(){return this.TypeCall}async Verify(e){const t=new FormData;t.append("cust_uuid",e.cust_uuid),t.append("source_image",e.source_image);try{return await this.AxiosCall.post("/v1/liveness/verify",t,{headers:{"Content-Type":"multipart/form-data"}}).then((e=>e.data))}catch(e){throw c.default.isAxiosError(e)?e.response?.data:new Error("different error than axios")}}async GetResult(e){const t=new FormData;t.append("session_id",e);try{return await this.AxiosCall.post("/v1/liveness/get_result",t,{headers:{"Content-Type":"multipart/form-data"}}).then((e=>e.data))}catch(e){throw c.default.isAxiosError(e)?e.response?.data:new Error("different error than axios")}}async CheckStatusService(e){try{return await this.AxiosCall.get(`/v1/liveness/status?cust_uuid=${e}`).then((e=>e.data))}catch(e){throw c.default.isAxiosError(e)?e.response?.data:new Error("different error than axios")}}}e.LivenessSDK=class{ApiKey="";PathAPI="http://localhost:8000";Cust_UUID="";LivenessService;MinConfident=.5;Round=0;QuestionNo=0;SessionID="";ProcessStatus=!1;centerConfident=.1;ConfigChannel={questions:0,question_list:[],question_timeout_in_second:0,retry_proof:0,retry_verification:0,session_expired_in_second:0};SessionQuestions;constructor(e,t="",s,i=.5){""!=t&&(this.PathAPI=t),this.ApiKey=e,this.SessionQuestions=[],this.LivenessService=new u(this.ApiKey,this.PathAPI,s),this.MinConfident=i}async GetConfig(){try{const e=await this.LivenessService.GetConfig();return this.ConfigChannel=this.CheckFormatConfig(e),this.ConfigChannel}catch(e){throw e}}GetConfidentConfig(){return this.MinConfident}CheckFormatConfig(e){return 1*e.questions&&(e.questions*=1),1*e.question_timeout_in_second&&(e.question_timeout_in_second*=1),1*e.retry_proof&&(e.retry_proof*=1),1*e.retry_verification&&(e.retry_verification*=1),1*e.session_expired_in_second&&(e.session_expired_in_second*=1),e}async CreateSession(e){this.Cust_UUID=e;const t={cust_uuid:this.Cust_UUID};try{const e=await this.LivenessService.CreateSession(t);this.Round=e.round,this.QuestionNo=1,this.ConfigChannel=this.CheckFormatConfig(e.config),this.SessionID=e.session_id;var s="",i="";0!=this.SessionQuestions.length&&(s=this.SessionQuestions.join(":"),i=this.SessionQuestions[this.QuestionNo-1]);for(let e=0;e<10;e++){for(this.SessionQuestions=[];this.SessionQuestions.length<this.ConfigChannel.questions;){const e=Math.floor(Math.random()*this.ConfigChannel.question_list.length);this.SessionQuestions.includes(this.ConfigChannel.question_list[e])||0==this.SessionQuestions.length&&this.ConfigChannel.question_list[e]==i||this.SessionQuestions.push(this.ConfigChannel.question_list[e])}if(this.SessionQuestions.join(":")!=s)break}return e}catch(e){throw c.default.isAxiosError(e),e}}GetQuestionSession(){return this.SessionQuestions}GetCurrentQuestion(){return this.QuestionNo<=this.SessionQuestions.length?{questions:this.SessionQuestions,question_no:this.QuestionNo,current_question:this.SessionQuestions[this.QuestionNo-1]}:{questions:this.SessionQuestions,current_question:"",question_no:this.QuestionNo}}GetSessionID(){return this.SessionID}async SaveTransaction(e,t=!1){var s;var i;s={image:e,is_timeout:t,session_id:this.SessionID,question_no:this.QuestionNo,round:this.Round,question:o[this.SessionQuestions[this.QuestionNo-1]]};try{const e=await this.LivenessService.SaveTransaction(s);if(e.condition_valid)if(this.QuestionNo===this.ConfigChannel.questions){const t=await this.LivenessService.GetResult(this.SessionID);(i=e).is_timeout=!1,i.session_status=!0,i.session={},i.result=t}else{(i=e).is_timeout=!1,i.session_status=!0,i.session={},i.result={},this.QuestionNo+=1}else{const t=e;i={session_id:t.session_id,condition_valid:t.condition_valid,is_timeout:!1,session_status:!0,details:{},session:{},result:{}};const s=await this.LivenessService.GetResult(this.SessionID);if(this.CheckPropertyInObj(t,"details","reason")){switch(t.details.reason){case"session_expire":i.session_status=!1;break;case"timeout":i.is_timeout=!0}"session_expire"!=t.details.reason&&"timeout"!=t.details.reason||(i={session_id:t.session_id,condition_valid:t.condition_valid,is_timeout:!1,session_status:!0,details:{},session:t.details,result:s})}else i={session_id:t.session_id,condition_valid:t.condition_valid,is_timeout:!1,session_status:!0,details:t.details,session:{},result:s}}return i}catch(e){if(c.default.isAxiosError(e))throw e;{const t=e;if("session_expire"===t.error.type)try{await this.LivenessService.GetResult(this.SessionID)}catch(e){throw e}throw t}}}CheckPropertyInObj(e,...t){return t.reduce(((e,t)=>e&&e[t]),e)}async LoadModels(e){const t=e;await Promise.all([h.loadFaceLandmarkModel(t),h.loadFaceLandmarkTinyModel(t),h.loadFaceRecognitionModel(t),h.loadFaceExpressionModel(t),h.loadSsdMobilenetv1Model(t)])}GetMeanPosition(e){return e.map((e=>[e.x,e.y])).reduce(((e,t)=>[e[0]+t[0],e[1]+t[1]])).map((t=>t/e.length))}GetTop(e){return e.map((e=>e.y)).reduce(((e,t)=>Math.min(e,t)))}async ProcessImage(e){var t;t="string"==typeof e?e:URL.createObjectURL(e);const s=await h.fetchImage(t),i=new h.SsdMobilenetv1Options({minConfidence:this.MinConfident}),n=await h.detectSingleFace(s,i).withFaceLandmarks(!0).withFaceDescriptor().withFaceExpressions();var a=[];if(n){const e=this.GetMeanPosition(n.landmarks.getRightEye()),t=this.GetMeanPosition(n.landmarks.getLeftEye()),s=this.GetMeanPosition(n.landmarks.getNose()),i=this.GetMeanPosition(n.landmarks.getMouth()),r=this.GetTop(n.landmarks.getJawOutline()),h=n.landmarks.getMouth()[14].y,c=n.landmarks.getMouth()[18].y-h,u=(r-i[1])/n.detection.box.height,d=(t[0]+(e[0]-t[0])/2-s[0])/n.detection.box.width;d<-.075&&u<.02&&a.push(o.FacingLeft.toString()),d>.065&&u<.02&&a.push(o.FacingRight.toString()),n.expressions.happy>=.8&&a.push(o.Smiling.toString()),c>=15&&a.push(o.MouthOpen.toString())}return 0!=a.length&&(this.SessionQuestions.length<=this.QuestionNo&&!!a.includes(this.SessionQuestions[this.QuestionNo-1]))}SetAPIKey(e){this.ApiKey=e,this.LivenessService.SetApiKey(this.ApiKey)}GetAPIKey(){return this.ApiKey}SetPathAPI(e){this.PathAPI=e,this.LivenessService.SetPathAPI(e)}GetPathAPI(){return this.PathAPI}SetTypeCall(e){this.LivenessService.SetTypeCall(e)}GetTypeCall(){return this.LivenessService.GetTypeCall()}setCenterConfident(e){this.centerConfident=e}async DetectFace(e){var t;t="string"==typeof e?e:URL.createObjectURL(e);const s=await h.fetchImage(t),i=new h.SsdMobilenetv1Options({minConfidence:this.MinConfident}),n=await h.detectAllFaces(s,i);var o={num_faces:n.length,detect_face:n.length>0,face_left:!1,face_right:!1,face_center:!1,open_month:!1,smiling:!1,ry:0,rx:0};if(1==n.length){const e=new h.SsdMobilenetv1Options({minConfidence:this.MinConfident}),t=await h.detectSingleFace(s,e).withFaceLandmarks(!0).withFaceDescriptor().withFaceExpressions();if(t){const e=this.GetMeanPosition(t.landmarks.getRightEye()),s=this.GetMeanPosition(t.landmarks.getLeftEye()),i=this.GetMeanPosition(t.landmarks.getNose()),n=this.GetMeanPosition(t.landmarks.getMouth()),a=this.GetTop(t.landmarks.getJawOutline()),r=t.landmarks.getMouth()[14].y,h=t.landmarks.getMouth()[18].y-r,c=(a-n[1])/t.detection.box.height,u=(s[0]+(e[0]-s[0])/2-i[0])/t.detection.box.width;o.ry=u,o.rx=c;const d=Number(u.toFixed(2));u<-.08&&c<.015&&(o.face_left=!0),u>.06&&c<.015&&(o.face_right=!0),t.expressions.happy>=.8&&(o.smiling=!0),h>=15&&(o.open_month=!0);const l=t.detection.box.x,f=t.detection.box.y+t.detection.box.width,p=l,g=t.alignedRect.imageWidth-f,_=p>=g?p-g:g-p,y=t.detection.box.y,S=t.detection.box.y+t.detection.box.height,C=y,m=t.alignedRect.imageHeight-S;(C>=m?C-m:m-C)<=t.alignedRect.imageHeight*this.centerConfident&&_<=t.alignedRect.imageWidth*this.centerConfident&&d>-.06&&d<.07&&c<-.3&&(o.face_center=!0)}}return o}async Verify(e,t){var s;s={cust_uuid:e,source_image:t};try{return await this.LivenessService.Verify(s)}catch(e){throw e}}async CheckServiceStatus(e=""){const t=""!=e?e:this.Cust_UUID;try{return await this.LivenessService.CheckStatusService(t)}catch(e){throw e}}}}));