face-validator-sdk 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see face-validator-sdk.umd.js.LICENSE.txt */
2
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("mediapipe"),require("React")):"function"==typeof define&&define.amd?define(["mediapipe","React"],t):"object"==typeof exports?exports.FaceValidator=t(require("mediapipe"),require("React")):e.FaceValidator=t(e.mediapipe,e.React)}(this,(e,t)=>(()=>{"use strict";var n={20(e,t,n){var a=n(883),i=Symbol.for("react.element"),o=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function c(e,t,n){var a,o={},c=null,d=null;for(a in void 0!==n&&(c=""+n),void 0!==t.key&&(c=""+t.key),void 0!==t.ref&&(d=t.ref),t)r.call(t,a)&&!l.hasOwnProperty(a)&&(o[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===o[a]&&(o[a]=t[a]);return{$$typeof:i,type:e,key:c,ref:d,props:o,_owner:s.current}}t.Fragment=o,t.jsx=c,t.jsxs=c},848(e,t,n){e.exports=n(20)},883(e){e.exports=t},80(t){t.exports=e}},a={};function i(e){var t=a[e];if(void 0!==t)return t.exports;var o=a[e]={exports:{}};return n[e](o,o.exports,i),o.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};i.r(o),i.d(o,{FaceValidator:()=>T,ReactSelfieCapture:()=>C,ValidationStatus:()=>r,default:()=>R,getLoadingModelsMessage:()=>h,getMessage:()=>u,getValidationMessages:()=>d});var r,s=i(80);!function(e){e.INITIALIZING="INITIALIZING",e.NO_FACE_DETECTED="NO_FACE_DETECTED",e.FACE_DETECTED="FACE_DETECTED",e.TOO_CLOSE="TOO_CLOSE",e.TOO_FAR="TOO_FAR",e.OFF_CENTER="OFF_CENTER",e.FACE_OBSTRUCTED="FACE_OBSTRUCTED",e.HEAD_NOT_STRAIGHT="HEAD_NOT_STRAIGHT",e.MULTIPLE_FACES="MULTIPLE_FACES",e.POOR_ILLUMINATION="POOR_ILLUMINATION",e.NOT_NEUTRAL_EXPRESSION="NOT_NEUTRAL_EXPRESSION",e.DARK_GLASSES="DARK_GLASSES",e.STAY_STILL="STAY_STILL",e.CAPTURING="CAPTURING",e.SUCCESS="SUCCESS",e.ERROR="ERROR"}(r||(r={}));const l={"pt-BR":{[r.INITIALIZING]:"Inicializando câmera e detector...",[r.NO_FACE_DETECTED]:"Posicione seu rosto no centro do oval.",[r.FACE_DETECTED]:"Analisando...",[r.TOO_CLOSE]:"Afaste-se um pouco",[r.TOO_FAR]:"Aproxime-se da câmera",[r.OFF_CENTER]:"Centralize o rosto no centro do oval",[r.FACE_OBSTRUCTED]:"Mantenha o rosto totalmente visível. Remova as mãos do rosto.",[r.HEAD_NOT_STRAIGHT]:"Olhe diretamente para a câmera e mantenha a cabeça reta.",[r.MULTIPLE_FACES]:"Mantenha apenas uma pessoa no quadro.",[r.POOR_ILLUMINATION]:"Procure um ambiente com boa iluminação.",[r.NOT_NEUTRAL_EXPRESSION]:"Mantenha expressão neutra: boca fechada, sem sorrir e olhos abertos.",[r.DARK_GLASSES]:"Remova os óculos escuros. Óculos de grau são permitidos.",[r.STAY_STILL]:"Fique imóvel para capturar a foto",[r.CAPTURING]:"Capturando...",[r.SUCCESS]:"Captura realizada!",[r.ERROR]:"Ocorreu um erro."},en:{[r.INITIALIZING]:"Initializing camera and detector...",[r.NO_FACE_DETECTED]:"Position your face in the center of the oval.",[r.FACE_DETECTED]:"Analyzing...",[r.TOO_CLOSE]:"Move back a little",[r.TOO_FAR]:"Move closer to the camera",[r.OFF_CENTER]:"Center your face in the center of the oval",[r.FACE_OBSTRUCTED]:"Keep your face fully visible. Remove your hands from your face.",[r.HEAD_NOT_STRAIGHT]:"Look directly at the camera and keep your head straight.",[r.MULTIPLE_FACES]:"Keep only one person in the frame.",[r.POOR_ILLUMINATION]:"Find a well-lit environment and center your face in the oval.",[r.NOT_NEUTRAL_EXPRESSION]:"Keep a neutral expression: mouth closed, no smiling, and eyes open.",[r.DARK_GLASSES]:"Remove sunglasses. Prescription glasses are allowed.",[r.STAY_STILL]:"Stay still to capture the photo",[r.CAPTURING]:"Capturing...",[r.SUCCESS]:"Capture complete!",[r.ERROR]:"An error occurred."},es:{[r.INITIALIZING]:"Inicializando cámara y detector...",[r.NO_FACE_DETECTED]:"Coloque su rostro en el centro del óvalo.",[r.FACE_DETECTED]:"Analizando...",[r.TOO_CLOSE]:"Aléjese un poco",[r.TOO_FAR]:"Acérquese a la cámara",[r.OFF_CENTER]:"Centre el rostro en el centro del óvalo",[r.FACE_OBSTRUCTED]:"Mantenga el rostro totalmente visible. Quite las manos del rostro.",[r.HEAD_NOT_STRAIGHT]:"Mire directamente a la cámara y mantenga la cabeza recta.",[r.MULTIPLE_FACES]:"Mantenga solo una persona en el encuadre.",[r.POOR_ILLUMINATION]:"Busque un ambiente con buena iluminación y centre su rostro en el óvalo.",[r.NOT_NEUTRAL_EXPRESSION]:"Mantenga expresión neutra: boca cerrada, sin sonreír y ojos abiertos.",[r.DARK_GLASSES]:"Quite las gafas de sol. Las gafas graduadas están permitidas.",[r.STAY_STILL]:"Permanezca quieto para capturar la foto",[r.CAPTURING]:"Capturando...",[r.SUCCESS]:"¡Captura realizada!",[r.ERROR]:"Ocurrió un error."}},c={"pt-BR":"Status desconhecido.",en:"Unknown status.",es:"Estado desconhecido."};function d(e){return Object.assign({},l[e])}function u(e,t){var n;return null!==(n=l[t][e])&&void 0!==n?n:c[t]}function h(e){return{"pt-BR":"Carregando...",en:"Loading...",es:"Cargando..."}[e]}function m(e){const t=e.data;let n=0;for(let e=0;e<t.length;e+=4)n+=.2126*t[e]+.7152*t[e+1]+.0722*t[e+2];return n/(t.length/4)}const f=[33,133,159,145],g=[263,362,386,374],p=[61,291,0,17,39,269,270,409],E=.34;var S=function(e,t,n,a){return new(n||(n=Promise))(function(i,o){function r(e){try{l(a.next(e))}catch(e){o(e)}}function s(e){try{l(a.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,s)}l((a=a.apply(e,t||[])).next())})};const y={overlayCanvasElement:void 0,videoWidth:512,videoHeight:384,minDetectionConfidence:.4,minIlluminationThreshold:50,minFaceSizeFactor:.15,maxFaceSizeFactor:.75,stabilizationTimeThreshold:1e3,stabilityMovementThreshold:5,minFaceVisibilityScore:.4,maxHeadTiltDegrees:30,maxHandFaceDistance:.15,debugMode:!1,locale:"en",customMessages:{}};class T{constructor(e){this.faceLandmarker=null,this.handLandmarker=null,this.animationFrameId=null,this.lastDetection=null,this.stableSince=null,this.isCapturing=!1,this.options=this.resolveOptions(e),this.setStatus(r.INITIALIZING),this.init()}resolveOptions(e){const t=e.modelPath||"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm";return Object.assign(Object.assign(Object.assign({},y),e),{modelPath:t,locale:e.locale||"en",customMessages:e.customMessages||{}})}init(){return S(this,void 0,void 0,function*(){try{const e=h(this.options.locale);this.setStatus(r.INITIALIZING,void 0,e);const t=yield s.FilesetResolver.forVisionTasks(this.options.modelPath);this.faceLandmarker=yield s.FaceLandmarker.createFromOptions(t,{baseOptions:{modelAssetPath:"https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",delegate:"GPU"},runningMode:"VIDEO",numFaces:2,minFaceDetectionConfidence:this.options.minDetectionConfidence,minFacePresenceConfidence:this.options.minFaceVisibilityScore,minTrackingConfidence:this.options.minFaceVisibilityScore}),this.handLandmarker=yield s.HandLandmarker.createFromOptions(t,{baseOptions:{modelAssetPath:"https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task",delegate:"GPU"},runningMode:"VIDEO",numHands:2,minHandDetectionConfidence:.5,minHandPresenceConfidence:.5,minTrackingConfidence:.5}),this.startDetectionLoop()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.setStatus(r.ERROR,t)}})}getMessageForStatus(e,t){return t||(this.options.customMessages[e]?this.options.customMessages[e]:u(e,this.options.locale))}setStatus(e,t,n){const a=this.getMessageForStatus(e,n);this.options.onStatusUpdate(e,a),e===r.ERROR&&t&&this.options.onError(e,t)}startDetectionLoop(){const e=this.options.videoElement,t=this.options.videoWidth||640,n=this.options.videoHeight||480,a=()=>S(this,void 0,void 0,function*(){var i;if(this.faceLandmarker&&this.handLandmarker&&e.videoWidth){try{const a=performance.now();let o=r.NO_FACE_DETECTED,s=null,l=[];const c=this.faceLandmarker.detectForVideo(e,a),d=this.handLandmarker.detectForVideo(e,a);if(d.landmarks&&d.landmarks.length>0&&(l=d.landmarks.map((e,t)=>{var n,a,i;return{landmarks:e,handedness:(null===(i=null===(a=null===(n=d.handednesses)||void 0===n?void 0:n[t])||void 0===a?void 0:a[0])||void 0===i?void 0:i.categoryName)||"Unknown"}})),c.faceLandmarks&&c.faceLandmarks.length>1){o=r.MULTIPLE_FACES,this.stableSince=null;const e=c.faceLandmarks[0],t=(null===(i=c.faceBlendshapes)||void 0===i?void 0:i[0])?this.estimateBoundingBox(e):null;t&&(s={boundingBox:t,landmarks:e,timestamp:a})}else if(c.faceLandmarks&&1===c.faceLandmarks.length){const i=c.faceLandmarks[0],d=this.estimateBoundingBox(i);s={boundingBox:d,landmarks:i,timestamp:a};const u=function(e,t=.18,n=.7){const a=e.width;return a<t?"TOO_FAR":a>n?"TOO_CLOSE":"OK"}(d,this.options.minFaceSizeFactor,this.options.maxFaceSizeFactor);if("OK"!==u)o="TOO_CLOSE"===u?r.TOO_CLOSE:r.TOO_FAR,this.stableSince=null;else{const c=i[4],u=function(e,t,n,a){const i=(e*n-n/2)/(.2*n),o=(t*a-a/2)/(a*E);return i*i+o*o<=.6}(c.x,c.y,t,n),h=function(e,t,n){const a=t/2,i=n/2,o=.2*t,r=n*E,s=e.xMin*t,l=(e.xMin+e.width)*t,c=e.yMin*n,d=(e.yMin+e.height)*n,u=((s+l)/2-a)/o,h=((c+d)/2-i)/r;if(u*u+h*h>1)return!1;const m=[{x:s,y:c},{x:l,y:c},{x:s,y:d},{x:l,y:d}];let f=0;for(const e of m){const t=(e.x-a)/o,n=(e.y-i)/r;t*t+n*n>1&&f++}return 0===f}(d,t,n);if(u&&h)if(function(e,t){if(e.length<478)return!1;const n=e[4],a=p.map(t=>e[t]),i=a.reduce((e,t)=>e+t.y,0)/a.length,o=Math.min(...a.map(e=>e.y)),r=Math.max(...a.map(e=>e.y))-o,s=t.height;return!(i<n.y-.01||i-n.y<.06*s||r<.02*s)}(i,d))if(function(e,t=25){if(e.length<478)return!1;const n=e[f[0]],a=e[g[0]],i=e[4],o=e[13],r=e[14],s=e[152],l=e[10],c=Math.abs(n.y-a.y),d=Math.abs(n.x-a.x);if(d<.01)return!1;const u=c/d;if(Math.atan(u)*(180/Math.PI)>t)return!1;const h=(n.x+a.x)/2,m=i.x-h,p=Math.abs(n.x-a.x);if(p<.01)return!1;const E=Math.abs(m)/p;if(Math.atan(E)*(180/Math.PI)>t)return!1;if(!function(e){if(e.length<478)return!1;const t=e[234],n=e[454],a=e[4],i=Math.abs(t.x-a.x),o=Math.abs(n.x-a.x);return!((i>.01&&o>.01?Math.max(i,o)/Math.min(i,o):1)>1.4||void 0!==t.z&&void 0!==n.z&&Math.abs(t.z-n.z)>.05)}(e))return!1;const S=(n.y+a.y)/2,y=(o.y+r.y)/2,T=s.y-l.y;if(T<.1)return!1;if(l.y>S+.02)return!1;if(S>i.y+.02)return!1;if(i.y>y+.02)return!1;if(y>=s.y)return!1;const b=(S-l.y)/T,O=(i.y-S)/T,v=(y-i.y)/T,I=(s.y-y)/T;return!(b<.06||b>.38||O<.03||O>.3||v<.02||v>.25||I<.04||I>.38)}(i,this.options.maxHeadTiltDegrees))if(l.length>0&&function(e,t,n=.15){const a=t.xMin+t.width/2,i=t.yMin+t.height/2;for(const t of e.landmarks){const e=t.x-a,o=t.y-i;if(Math.sqrt(e*e+o*o)<n)return!0}return!1}(l[0],d,this.options.maxHandFaceDistance))o=r.FACE_OBSTRUCTED,this.stableSince=null;else if(function(e){if(e.length<478)return!1;const t=e[159],n=e[144],a=e[386],i=e[373],o=Math.abs(t.y-n.y),r=Math.abs(a.y-i.y);if(o<.01||r<.01)return!1;const s=e[13],l=e[14];if(Math.abs(s.y-l.y)>.025)return!1;const c=e[61],d=e[291],u=e[4];return!((c.y+d.y)/2-u.y<.05)}(i))if(function(e,t){if(t.length<478)return!1;try{const n=document.createElement("canvas"),a=n.getContext("2d");if(!a)return!1;const i=e.videoWidth,o=e.videoHeight,r=[t[33],t[133],t[159],t[144],t[145]],s=[t[263],t[362],t[386],t[373],t[374]],l=e=>{const t=e.map(e=>e.x*i),n=e.map(e=>e.y*o),a=Math.max(0,Math.min(...t)-5),r=Math.min(i,Math.max(...t)+5),s=Math.max(0,Math.min(...n)-5);return{x:a,y:s,width:r-a,height:Math.min(o,Math.max(...n)+5)-s}},c=t=>(n.width=t.width,n.height=t.height,a.drawImage(e,t.x,t.y,t.width,t.height,0,0,t.width,t.height),m(a.getImageData(0,0,t.width,t.height))),d=l(r),u=l(s);return(c(d)+c(u))/2<35}catch(e){return console.warn("Erro ao detectar óculos escuros:",e),!1}}(e,i))o=r.DARK_GLASSES,this.stableSince=null;else{const i=document.createElement("canvas"),l=d.xMin*e.videoWidth,c=d.yMin*e.videoHeight,u=d.width*e.videoWidth,h=d.height*e.videoHeight;i.width=u,i.height=h;const f=i.getContext("2d",{willReadFrequently:!0});if(f){f.drawImage(e,l,c,u,h,0,0,u,h);m(f.getImageData(0,0,i.width,i.height))<this.options.minIlluminationThreshold?(o=r.POOR_ILLUMINATION,this.stableSince=null):function(e,t,n=5,a=512,i=384){if(!e||!t)return!1;const o=(e.boundingBox.xMin+e.boundingBox.width/2)*a,r=(e.boundingBox.yMin+e.boundingBox.height/2)*i,s=(t.boundingBox.xMin+t.boundingBox.width/2)*a,l=(t.boundingBox.yMin+t.boundingBox.height/2)*i,c=Math.abs(o-s),d=Math.abs(r-l),u=Math.abs(e.boundingBox.width-t.boundingBox.width)*a,h=Math.abs(e.boundingBox.height-t.boundingBox.height)*i;return c<=n&&d<=n&&u<=2*n&&h<=2*n}(s,this.lastDetection,this.options.stabilityMovementThreshold,t,n)?(this.stableSince||(this.stableSince=a),o=a-this.stableSince>=this.options.stabilizationTimeThreshold?r.CAPTURING:r.STAY_STILL):(this.stableSince=null,o=r.STAY_STILL)}else o=r.FACE_DETECTED,this.stableSince=null}else o=r.NOT_NEUTRAL_EXPRESSION,this.stableSince=null;else o=r.HEAD_NOT_STRAIGHT,this.stableSince=null;else o=r.FACE_OBSTRUCTED,this.stableSince=null;else o=r.OFF_CENTER,this.stableSince=null}}else this.lastDetection=null,this.stableSince=null;if(this.lastDetection=s,this.setStatus(o),this.options.overlayCanvasElement&&function(e,t,n,a,i){const o=e.getContext("2d");if(!o)return;const s=e.width,l=e.height,c=s/2,d=l/2;o.clearRect(0,0,s,l);const u=.2*s,h=l*E;if(o.fillStyle="rgba(255, 255, 255, 0.35)",o.fillRect(0,0,s,l),o.save(),o.beginPath(),o.ellipse(c,d,u,h,0,0,2*Math.PI),o.closePath(),o.globalCompositeOperation="destination-out",o.fill(),o.restore(),o.strokeStyle="rgba(255, 255, 255, 0.9)",o.lineWidth=3,o.beginPath(),o.ellipse(c,d,u,h,0,0,2*Math.PI),o.stroke(),o.strokeStyle="rgba(255, 255, 255, 0.45)",o.lineWidth=1,o.beginPath(),o.moveTo(c-6,d),o.lineTo(c+6,d),o.moveTo(c,d-6),o.lineTo(c,d+6),o.stroke(),t&&a){const e=a.landmarks;if(e.length>=478){const t=e[10],a=e[152],i=e[234],c=e[454],d=e.map(e=>e.x),u=e.map(e=>e.y),h=Math.min(...d),m=Math.max(...d),p=Math.min(...u),E=m-h,S=Math.max(...u)-p,y=.08,T=(h-E*y)*s,b=(p-S*y)*l,O=E*(1+2*y)*s,v=S*(1+2*y)*l;let I="red";n===r.STAY_STILL||n===r.CAPTURING?I="lime":n===r.FACE_DETECTED&&(I="yellow"),o.strokeStyle=I,o.lineWidth=3,o.strokeRect(T,b,O,v);const C=e[4];e[f[0]],e[g[0]],o.fillStyle="cyan",o.beginPath(),o.arc(C.x*s,C.y*l,5,0,2*Math.PI),o.fill(),o.fillStyle="magenta",o.beginPath(),o.arc(t.x*s,t.y*l,4,0,2*Math.PI),o.fill(),o.fillStyle="lime",o.beginPath(),o.arc(a.x*s,a.y*l,4,0,2*Math.PI),o.fill(),o.fillStyle="yellow",[e[33],e[133],e[159],e[144],e[145]].forEach(e=>{o.beginPath(),o.arc(e.x*s,e.y*l,3,0,2*Math.PI),o.fill()}),o.fillStyle="yellow",[e[263],e[362],e[386],e[373],e[374]].forEach(e=>{o.beginPath(),o.arc(e.x*s,e.y*l,3,0,2*Math.PI),o.fill()}),o.fillStyle="purple",o.beginPath(),o.arc(i.x*s,i.y*l,3,0,2*Math.PI),o.fill(),o.beginPath(),o.arc(c.x*s,c.y*l,3,0,2*Math.PI),o.fill()}}t&&i&&i.length>0&&i.forEach(e=>{o.fillStyle="orange",e.landmarks.forEach(e=>{o.beginPath(),o.arc(e.x*s,e.y*l,3,0,2*Math.PI),o.fill()})})}(this.options.overlayCanvasElement,this.options.debugMode||!1,o,s||void 0,l.length>0?l:void 0),o===r.CAPTURING&&!this.isCapturing)return this.isCapturing=!0,yield this.captureImage(),this.setStatus(r.SUCCESS),void this.stop()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.setStatus(r.ERROR,t)}this.animationFrameId=requestAnimationFrame(a)}else this.animationFrameId=requestAnimationFrame(a)});this.animationFrameId=requestAnimationFrame(a)}estimateBoundingBox(e){const t=e.map(e=>e.x),n=e.map(e=>e.y),a=Math.min(...t),i=Math.max(...t),o=Math.min(...n);return{xMin:a,yMin:o,width:i-a,height:Math.max(...n)-o}}captureImage(){return S(this,void 0,void 0,function*(){const e=this.options.videoElement,t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const n=t.getContext("2d");n?(n.drawImage(e,0,0,t.width,t.height),t.toBlob(e=>{e?this.options.onCaptureSuccess(e):this.setStatus(r.ERROR,new Error("Failed to generate image blob"))},"image/jpeg",.95)):this.setStatus(r.ERROR,new Error("Failed to get canvas context"))})}stop(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.faceLandmarker&&this.faceLandmarker.close(),this.handLandmarker&&this.handLandmarker.close()}}var b=i(848),O=i(883);const v=[r.SUCCESS,r.ERROR,r.CAPTURING,r.INITIALIZING],I={"pt-BR":{previewQuestion:"O que você achou?",savePhoto:"Salvar foto",tryAgain:"Tentar novamente",cancel:"Cancelar"},en:{previewQuestion:"What do you think?",savePhoto:"Save photo",tryAgain:"Try again",cancel:"Cancel"},es:{previewQuestion:"¿Qué te pareció?",savePhoto:"Guardar foto",tryAgain:"Intentar de nuevo",cancel:"Cancelar"}},C=({onCapture:e,onDismiss:t,locale:n,videoWidth:a=512,videoHeight:i=384,debugMode:o=!1,modelPath:s,styles:l,labels:c})=>{const d=(e=>{if(!e)return"pt-BR";const t=e.toLowerCase();return t.startsWith("en")?"en":t.startsWith("es")?"es":"pt-BR"})(n),h=I[d],m=Object.assign(Object.assign({},h),null!=c?c:{}),f=(0,O.useRef)(null),g=(0,O.useRef)(null),p=(0,O.useRef)(null),E=(0,O.useRef)(null),S=(0,O.useRef)(0),y=(0,O.useRef)(""),[C,R]=(0,O.useState)(r.INITIALIZING),[x,_]=(0,O.useState)(u(r.INITIALIZING,d)),[A,M]=(0,O.useState)(u(r.INITIALIZING,d)),[L,F]=(0,O.useState)(!0),[N,P]=(0,O.useState)(null),k=(0,O.useCallback)((e,t)=>{R(e),_(t)},[]);(0,O.useEffect)(()=>{if(y.current=x,x===A)return;if(v.includes(C))return E.current&&(clearTimeout(E.current),E.current=null),M(x),void(S.current=Date.now());const e=Date.now(),t=e-S.current;if(t>=1500)return M(x),void(S.current=e);if(E.current)return;const n=1500-t;E.current=setTimeout(()=>{M(y.current),S.current=Date.now(),E.current=null},n)},[x,C,A]);const w=(0,O.useCallback)(e=>{var t;R(r.SUCCESS),_(u(r.SUCCESS,d)),(t=e,new Promise((e,n)=>{const a=new FileReader;a.onloadend=()=>e(a.result),a.onerror=n,a.readAsDataURL(t)})).then(e=>{P(e),F(!1)})},[d]),D=(0,O.useCallback)(()=>{e(null!=N?N:null),null==t||t()},[e,t,N]),j=(0,O.useCallback)(()=>{P(null),R(r.INITIALIZING),_(u(r.INITIALIZING,d)),F(!0)},[d]),U=(0,O.useCallback)((e,t)=>{_(t.message),R(r.ERROR)},[]);(0,O.useEffect)(()=>{const e=f.current;if(!L)return p.current&&(p.current.stop(),p.current=null),void(e&&e.srcObject&&(e.srcObject.getTracks().forEach(e=>e.stop()),e.srcObject=null));if(!e)return;let t=!1;return(n=void 0,l=void 0,c=void 0,u=function*(){var n;try{if(!e.srcObject){const n=yield navigator.mediaDevices.getUserMedia({video:{width:a,height:i}});if(t)return;e.srcObject=n,yield e.play()}const r=g.current;if(r){const t=e.videoWidth||a,n=e.videoHeight||i;r.width=t,r.height=n}if(p.current||t)return;const l={videoElement:e,overlayCanvasElement:null!==(n=g.current)&&void 0!==n?n:void 0,locale:d,debugMode:o,onStatusUpdate:k,onCaptureSuccess:w,onError:U,videoWidth:a,videoHeight:i};s&&(l.modelPath=s);const c=new T(l);p.current=c}catch(e){if(t)return;_(e.message),R(r.ERROR)}},new(c||(c=Promise))(function(e,t){function a(e){try{o(u.next(e))}catch(e){t(e)}}function i(e){try{o(u.throw(e))}catch(e){t(e)}}function o(t){var n;t.done?e(t.value):(n=t.value,n instanceof c?n:new c(function(e){e(n)})).then(a,i)}o((u=u.apply(n,l||[])).next())})).catch(()=>{}),()=>{t=!0,p.current&&(p.current.stop(),p.current=null),e&&e.srcObject&&(e.srcObject.getTracks().forEach(e=>e.stop()),e.srcObject=null)};var n,l,c,u},[L,d,a,i,o,s,k,w,U]);const B=!L&&Boolean(N),G=L,H=Object.assign({width:"100%",maxWidth:640,boxSizing:"border-box"},null==l?void 0:l.container),z=Object.assign({textAlign:"center",display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,padding:"10px 12px",marginBottom:10,borderRadius:10,fontWeight:600,marginTop:30,height:52,boxSizing:"border-box",transition:"all 0.4s ease-in-out"},null==l?void 0:l.messageBanner),W=Object.assign(Object.assign({},z),{backgroundColor:"#fff7df",color:"#b67219"});G&&(C===r.SUCCESS?(W.backgroundColor="#e0ffdf",W.color="#26c026"):C===r.ERROR&&(W.backgroundColor="#ffdfdf",W.color="#c02626"));const q=Object.assign({width:"100%",maxWidth:512,height:384,margin:"0 auto",borderRadius:10,overflow:"hidden",position:"relative",backgroundColor:"#1a1a1a"},null==l?void 0:l.media),V={display:"block",width:"100%",padding:"8px 12px",borderRadius:4,border:"1px solid #d9d9d9",backgroundColor:"#ffffff",cursor:"pointer",fontSize:14},Z=Object.assign(Object.assign(Object.assign({},V),{backgroundColor:"#1dbe32",color:"#ffffff",borderColor:"#1dbe32"}),null==l?void 0:l.primaryButton),K=Object.assign(Object.assign({},V),null==l?void 0:l.secondaryButton);return(0,b.jsxs)("div",{style:H,children:[(0,b.jsx)("div",{style:W,children:B?m.previewQuestion:A}),(0,b.jsx)("div",{style:q,children:G?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("video",{ref:f,autoPlay:!0,playsInline:!0,muted:!0,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"}}),(0,b.jsx)("canvas",{ref:g,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",transform:"scaleX(-1)"}})]}):B&&N?(0,b.jsx)("img",{src:N,alt:"Selfie preview",style:{display:"block",width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)",backgroundColor:"transparent",border:"none"}}):(0,b.jsx)("div",{"aria-hidden":!0})}),(0,b.jsx)("div",{style:{marginTop:10},children:B?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("button",{type:"button",onClick:j,style:K,children:m.tryAgain}),(0,b.jsx)("div",{style:{height:8}}),(0,b.jsx)("button",{type:"button",onClick:D,disabled:!N,style:Object.assign(Object.assign({},Z),{opacity:N?1:.6,cursor:N?"pointer":"not-allowed"}),children:m.savePhoto})]}):(0,b.jsx)("button",{type:"button",onClick:()=>{null==t||t(),e(null),F(!1)},style:K,children:m.cancel})})]})},R=T;return o})());
2
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("mediapipe"),require("React")):"function"==typeof define&&define.amd?define(["mediapipe","React"],t):"object"==typeof exports?exports.FaceValidator=t(require("mediapipe"),require("React")):e.FaceValidator=t(e.mediapipe,e.React)}(this,(e,t)=>(()=>{"use strict";var n={20(e,t,n){var a=n(883),i=Symbol.for("react.element"),o=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,r=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function d(e,t,n){var a,o={},d=null,c=null;for(a in void 0!==n&&(d=""+n),void 0!==t.key&&(d=""+t.key),void 0!==t.ref&&(c=t.ref),t)s.call(t,a)&&!l.hasOwnProperty(a)&&(o[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===o[a]&&(o[a]=t[a]);return{$$typeof:i,type:e,key:d,ref:c,props:o,_owner:r.current}}t.Fragment=o,t.jsx=d,t.jsxs=d},848(e,t,n){e.exports=n(20)},883(e){e.exports=t},80(t){t.exports=e}},a={};function i(e){var t=a[e];if(void 0!==t)return t.exports;var o=a[e]={exports:{}};return n[e](o,o.exports,i),o.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};i.r(o),i.d(o,{FaceValidator:()=>y,ReactSelfieCapture:()=>I,ValidationStatus:()=>s,default:()=>R,getLoadingModelsMessage:()=>h,getMessage:()=>u,getValidationMessages:()=>c});var s,r=i(80);!function(e){e.INITIALIZING="INITIALIZING",e.NO_FACE_DETECTED="NO_FACE_DETECTED",e.FACE_DETECTED="FACE_DETECTED",e.TOO_CLOSE="TOO_CLOSE",e.TOO_FAR="TOO_FAR",e.OFF_CENTER="OFF_CENTER",e.FACE_OBSTRUCTED="FACE_OBSTRUCTED",e.HEAD_NOT_STRAIGHT="HEAD_NOT_STRAIGHT",e.MULTIPLE_FACES="MULTIPLE_FACES",e.POOR_ILLUMINATION="POOR_ILLUMINATION",e.NOT_NEUTRAL_EXPRESSION="NOT_NEUTRAL_EXPRESSION",e.DARK_GLASSES="DARK_GLASSES",e.STAY_STILL="STAY_STILL",e.CAPTURING="CAPTURING",e.SUCCESS="SUCCESS",e.ERROR="ERROR"}(s||(s={}));const l={"pt-BR":{[s.INITIALIZING]:"Inicializando câmera e detector...",[s.NO_FACE_DETECTED]:"Posicione seu rosto no centro do oval.",[s.FACE_DETECTED]:"Analisando...",[s.TOO_CLOSE]:"Afaste-se um pouco",[s.TOO_FAR]:"Aproxime-se da câmera",[s.OFF_CENTER]:"Centralize o rosto no centro do oval",[s.FACE_OBSTRUCTED]:"Mantenha o rosto totalmente visível. Remova as mãos do rosto.",[s.HEAD_NOT_STRAIGHT]:"Olhe diretamente para a câmera e mantenha a cabeça reta.",[s.MULTIPLE_FACES]:"Mantenha apenas uma pessoa no quadro.",[s.POOR_ILLUMINATION]:"Procure um ambiente com boa iluminação.",[s.NOT_NEUTRAL_EXPRESSION]:"Mantenha expressão neutra: boca fechada, sem sorrir e olhos abertos.",[s.DARK_GLASSES]:"Remova os óculos escuros. Óculos de grau são permitidos.",[s.STAY_STILL]:"Fique imóvel para capturar a foto",[s.CAPTURING]:"Capturando...",[s.SUCCESS]:"Captura realizada!",[s.ERROR]:"Ocorreu um erro."},en:{[s.INITIALIZING]:"Initializing camera and detector...",[s.NO_FACE_DETECTED]:"Position your face in the center of the oval.",[s.FACE_DETECTED]:"Analyzing...",[s.TOO_CLOSE]:"Move back a little",[s.TOO_FAR]:"Move closer to the camera",[s.OFF_CENTER]:"Center your face in the center of the oval",[s.FACE_OBSTRUCTED]:"Keep your face fully visible. Remove your hands from your face.",[s.HEAD_NOT_STRAIGHT]:"Look directly at the camera and keep your head straight.",[s.MULTIPLE_FACES]:"Keep only one person in the frame.",[s.POOR_ILLUMINATION]:"Find a well-lit environment and center your face in the oval.",[s.NOT_NEUTRAL_EXPRESSION]:"Keep a neutral expression: mouth closed, no smiling, and eyes open.",[s.DARK_GLASSES]:"Remove sunglasses. Prescription glasses are allowed.",[s.STAY_STILL]:"Stay still to capture the photo",[s.CAPTURING]:"Capturing...",[s.SUCCESS]:"Capture complete!",[s.ERROR]:"An error occurred."},es:{[s.INITIALIZING]:"Inicializando cámara y detector...",[s.NO_FACE_DETECTED]:"Coloque su rostro en el centro del óvalo.",[s.FACE_DETECTED]:"Analizando...",[s.TOO_CLOSE]:"Aléjese un poco",[s.TOO_FAR]:"Acérquese a la cámara",[s.OFF_CENTER]:"Centre el rostro en el centro del óvalo",[s.FACE_OBSTRUCTED]:"Mantenga el rostro totalmente visible. Quite las manos del rostro.",[s.HEAD_NOT_STRAIGHT]:"Mire directamente a la cámara y mantenga la cabeza recta.",[s.MULTIPLE_FACES]:"Mantenga solo una persona en el encuadre.",[s.POOR_ILLUMINATION]:"Busque un ambiente con buena iluminación y centre su rostro en el óvalo.",[s.NOT_NEUTRAL_EXPRESSION]:"Mantenga expresión neutra: boca cerrada, sin sonreír y ojos abiertos.",[s.DARK_GLASSES]:"Quite las gafas de sol. Las gafas graduadas están permitidas.",[s.STAY_STILL]:"Permanezca quieto para capturar la foto",[s.CAPTURING]:"Capturando...",[s.SUCCESS]:"¡Captura realizada!",[s.ERROR]:"Ocurrió un error."}},d={"pt-BR":"Status desconhecido.",en:"Unknown status.",es:"Estado desconhecido."};function c(e){return Object.assign({},l[e])}function u(e,t){var n;return null!==(n=l[t][e])&&void 0!==n?n:d[t]}function h(e){return{"pt-BR":"Carregando...",en:"Loading...",es:"Cargando..."}[e]}function m(e){const t=e.data;let n=0;for(let e=0;e<t.length;e+=4)n+=.2126*t[e]+.7152*t[e+1]+.0722*t[e+2];return n/(t.length/4)}const f=[33,133,159,145],E=[263,362,386,374],p=[61,291,0,17,39,269,270,409],g=.34;var v=function(e,t,n,a){return new(n||(n=Promise))(function(i,o){function s(e){try{l(a.next(e))}catch(e){o(e)}}function r(e){try{l(a.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,r)}l((a=a.apply(e,t||[])).next())})};const S={container:void 0,ui:"default",autoStart:!0,mirror:!0,videoConstraints:void 0,overlayCanvasElement:void 0,videoWidth:512,videoHeight:384,minDetectionConfidence:.4,minIlluminationThreshold:50,minFaceSizeFactor:.15,maxFaceSizeFactor:.75,stabilizationTimeThreshold:1e3,stabilityMovementThreshold:5,minFaceVisibilityScore:.4,maxHeadTiltDegrees:30,maxHandFaceDistance:.15,debugMode:!1,locale:"en",customMessages:{},onStatusUpdate:void 0,onCaptureSuccess:void 0,onError:void 0};class y{constructor(e){this.faceLandmarker=null,this.handLandmarker=null,this.animationFrameId=null,this.lastDetection=null,this.stableSince=null,this.isCapturing=!1,this.containerElement=null,this.statusElement=null,this.uiRootElement=null,this.cameraStream=null,this.cameraReadyPromise=null,this.managedElements=!1,this.managedCamera=!1,this.injectedStyleElement=null,this.options=this.resolveOptions(e),this.setupElements(),this.setStatus(s.INITIALIZING),this.cameraReadyPromise=this.options.autoStart?this.initCamera():Promise.resolve(),this.init()}resolveOptions(e){const t=e.modelPath||"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm";return Object.assign(Object.assign(Object.assign({},S),e),{modelPath:t,locale:e.locale||"en",customMessages:e.customMessages||{},onStatusUpdate:e.onStatusUpdate||(()=>{}),onCaptureSuccess:e.onCaptureSuccess||(()=>{}),onError:e.onError||(()=>{}),videoConstraints:e.videoConstraints||{width:{ideal:e.videoWidth||S.videoWidth},height:{ideal:e.videoHeight||S.videoHeight},facingMode:"user"}})}setupElements(){const e=this.resolveContainer(this.options.container);if(this.containerElement=e,"default"===this.options.ui&&e&&this.ensureDefaultUI(e),this.options.videoElement){if(!this.options.overlayCanvasElement&&e){const t=document.createElement("canvas");t.className="fv-sdk-canvas",this.attachMediaElements(e,this.options.videoElement,t),this.options.overlayCanvasElement=t,this.managedElements=!0}}else{if(!e)throw new Error("FaceValidator requires either videoElement or container.");const t=document.createElement("video");t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.className="fv-sdk-video";const n=document.createElement("canvas");n.className="fv-sdk-canvas",this.attachMediaElements(e,t,n),this.options.videoElement=t,this.options.overlayCanvasElement=n,this.managedElements=!0}this.options.mirror&&this.applyMirrorStyles()}resolveContainer(e){return e?"string"==typeof e?document.querySelector(e):e:null}ensureDefaultUI(e){e.innerHTML="",e.classList.add("fv-sdk-root");const t=document.createElement("div");t.className="fv-sdk-media",e.appendChild(t);const n=document.createElement("div");n.className="fv-sdk-status",e.appendChild(n),this.statusElement=n,this.uiRootElement=e,this.injectDefaultStyles()}attachMediaElements(e,t,n){const a=e.querySelector(".fv-sdk-media");if(a)return a.appendChild(t),void a.appendChild(n);const i=document.createElement("div");i.className="fv-sdk-media",i.appendChild(t),i.appendChild(n),e.appendChild(i)}injectDefaultStyles(){if(this.injectedStyleElement||document.querySelector('style[data-fv-sdk="true"]'))return;const e=document.createElement("style");e.setAttribute("data-fv-sdk","true"),e.textContent="\n .fv-sdk-root { display: flex; flex-direction: column; gap: 12px; width: 100%; }\n .fv-sdk-media { position: relative; width: 100%; max-width: 512px; height: 384px; margin: 0 auto; background: #000; border-radius: 10px; overflow: hidden; }\n .fv-sdk-video, .fv-sdk-canvas { width: 100%; height: 100%; display: block; object-fit: contain; }\n .fv-sdk-canvas { position: absolute; top: 0; left: 0; }\n .fv-sdk-status { text-align: center; display: flex; align-items: center; justify-content: center; font-size: 14px; padding: 10px 12px; border-radius: 8px; font-weight: 600; background: #f8f9fa; color: #555; }\n .fv-sdk-status.success { background: #d4edda; color: #155724; }\n .fv-sdk-status.error { background: #f8d7da; color: #721c24; }\n .fv-sdk-status.warning { background: #fff3cd; color: #856404; }\n ",document.head.appendChild(e),this.injectedStyleElement=e}applyMirrorStyles(){const e=this.options.videoElement,t=this.options.overlayCanvasElement;e&&(e.style.transform="scaleX(-1)"),t&&(t.style.transform="scaleX(-1)")}init(){return v(this,void 0,void 0,function*(){try{const e=h(this.options.locale);this.setStatus(s.INITIALIZING,void 0,e);const t=yield r.FilesetResolver.forVisionTasks(this.options.modelPath);this.faceLandmarker=yield r.FaceLandmarker.createFromOptions(t,{baseOptions:{modelAssetPath:"https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",delegate:"GPU"},runningMode:"VIDEO",numFaces:2,minFaceDetectionConfidence:this.options.minDetectionConfidence,minFacePresenceConfidence:this.options.minFaceVisibilityScore,minTrackingConfidence:this.options.minFaceVisibilityScore}),this.handLandmarker=yield r.HandLandmarker.createFromOptions(t,{baseOptions:{modelAssetPath:"https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task",delegate:"GPU"},runningMode:"VIDEO",numHands:2,minHandDetectionConfidence:.5,minHandPresenceConfidence:.5,minTrackingConfidence:.5}),this.cameraReadyPromise&&(yield this.cameraReadyPromise),this.startDetectionLoop()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.setStatus(s.ERROR,t)}})}getMessageForStatus(e,t){return t||(this.options.customMessages[e]?this.options.customMessages[e]:u(e,this.options.locale))}setStatus(e,t,n){const a=this.getMessageForStatus(e,n);this.updateStatusUI(e,a),this.options.onStatusUpdate(e,a),e===s.ERROR&&t&&this.options.onError(e,t)}updateStatusUI(e,t){if(!this.statusElement)return;this.statusElement.textContent=t,this.statusElement.classList.remove("success","warning","error");const n=this.getStatusClass(e);n&&this.statusElement.classList.add(n)}getStatusClass(e){return e===s.SUCCESS?"success":e===s.ERROR?"error":[s.NO_FACE_DETECTED,s.MULTIPLE_FACES,s.TOO_CLOSE,s.TOO_FAR,s.OFF_CENTER,s.HEAD_NOT_STRAIGHT,s.FACE_OBSTRUCTED,s.POOR_ILLUMINATION,s.NOT_NEUTRAL_EXPRESSION,s.DARK_GLASSES,s.STAY_STILL,s.CAPTURING].includes(e)?"warning":""}initCamera(){return v(this,void 0,void 0,function*(){const e=this.options.videoElement;if(e&&!e.srcObject)try{const t=yield navigator.mediaDevices.getUserMedia({video:this.options.videoConstraints});this.cameraStream=t,this.managedCamera=!0,e.srcObject=t,yield this.waitForVideoReady(e),yield e.play();const n=this.options.overlayCanvasElement;n&&(n.width=e.videoWidth||this.options.videoWidth||S.videoWidth,n.height=e.videoHeight||this.options.videoHeight||S.videoHeight)}catch(e){const t=e instanceof Error?e:new Error(String(e));this.setStatus(s.ERROR,t)}})}waitForVideoReady(e){return v(this,void 0,void 0,function*(){e.readyState>=2||(yield new Promise((t,n)=>{const a=()=>{e.removeEventListener("loadedmetadata",a),t()},i=t=>{e.removeEventListener("error",i),n(t)};e.addEventListener("loadedmetadata",a),e.addEventListener("error",i),setTimeout(()=>{e.removeEventListener("loadedmetadata",a),e.removeEventListener("error",i),t()},5e3)}))})}startDetectionLoop(){const e=this.getVideoElement(),t=this.options.videoWidth||640,n=this.options.videoHeight||480,a=()=>v(this,void 0,void 0,function*(){var i;if(this.faceLandmarker&&this.handLandmarker&&e.videoWidth){try{const a=performance.now();let o=s.NO_FACE_DETECTED,r=null,l=[];const d=this.faceLandmarker.detectForVideo(e,a),c=this.handLandmarker.detectForVideo(e,a);if(c.landmarks&&c.landmarks.length>0&&(l=c.landmarks.map((e,t)=>{var n,a,i;return{landmarks:e,handedness:(null===(i=null===(a=null===(n=c.handednesses)||void 0===n?void 0:n[t])||void 0===a?void 0:a[0])||void 0===i?void 0:i.categoryName)||"Unknown"}})),d.faceLandmarks&&d.faceLandmarks.length>1){o=s.MULTIPLE_FACES,this.stableSince=null;const e=d.faceLandmarks[0],t=(null===(i=d.faceBlendshapes)||void 0===i?void 0:i[0])?this.estimateBoundingBox(e):null;t&&(r={boundingBox:t,landmarks:e,timestamp:a})}else if(d.faceLandmarks&&1===d.faceLandmarks.length){const i=d.faceLandmarks[0],c=this.estimateBoundingBox(i);r={boundingBox:c,landmarks:i,timestamp:a};const u=function(e,t=.18,n=.7){const a=e.width;return a<t?"TOO_FAR":a>n?"TOO_CLOSE":"OK"}(c,this.options.minFaceSizeFactor,this.options.maxFaceSizeFactor);if("OK"!==u)o="TOO_CLOSE"===u?s.TOO_CLOSE:s.TOO_FAR,this.stableSince=null;else{const d=i[4],u=function(e,t,n,a){const i=(e*n-n/2)/(.2*n),o=(t*a-a/2)/(a*g);return i*i+o*o<=.6}(d.x,d.y,t,n),h=function(e,t,n){const a=t/2,i=n/2,o=.2*t,s=n*g,r=e.xMin*t,l=(e.xMin+e.width)*t,d=e.yMin*n,c=(e.yMin+e.height)*n,u=((r+l)/2-a)/o,h=((d+c)/2-i)/s;if(u*u+h*h>1)return!1;const m=[{x:r,y:d},{x:l,y:d},{x:r,y:c},{x:l,y:c}];let f=0;for(const e of m){const t=(e.x-a)/o,n=(e.y-i)/s;t*t+n*n>1&&f++}return 0===f}(c,t,n);if(u&&h)if(function(e,t){if(e.length<478)return!1;const n=e[4],a=p.map(t=>e[t]),i=a.reduce((e,t)=>e+t.y,0)/a.length,o=Math.min(...a.map(e=>e.y)),s=Math.max(...a.map(e=>e.y))-o,r=t.height;return!(i<n.y-.01||i-n.y<.06*r||s<.02*r)}(i,c))if(function(e,t=25){if(e.length<478)return!1;const n=e[f[0]],a=e[E[0]],i=e[4],o=e[13],s=e[14],r=e[152],l=e[10],d=Math.abs(n.y-a.y),c=Math.abs(n.x-a.x);if(c<.01)return!1;const u=d/c;if(Math.atan(u)*(180/Math.PI)>t)return!1;const h=(n.x+a.x)/2,m=i.x-h,p=Math.abs(n.x-a.x);if(p<.01)return!1;const g=Math.abs(m)/p;if(Math.atan(g)*(180/Math.PI)>t)return!1;if(!function(e){if(e.length<478)return!1;const t=e[234],n=e[454],a=e[4],i=Math.abs(t.x-a.x),o=Math.abs(n.x-a.x);return!((i>.01&&o>.01?Math.max(i,o)/Math.min(i,o):1)>1.4||void 0!==t.z&&void 0!==n.z&&Math.abs(t.z-n.z)>.05)}(e))return!1;const v=(n.y+a.y)/2,S=(o.y+s.y)/2,y=r.y-l.y;if(y<.1)return!1;if(l.y>v+.02)return!1;if(v>i.y+.02)return!1;if(i.y>S+.02)return!1;if(S>=r.y)return!1;const C=(v-l.y)/y,T=(i.y-v)/y,b=(S-i.y)/y,O=(r.y-S)/y;return!(C<.06||C>.38||T<.03||T>.3||b<.02||b>.25||O<.04||O>.38)}(i,this.options.maxHeadTiltDegrees))if(l.length>0&&function(e,t,n=.15){const a=t.xMin+t.width/2,i=t.yMin+t.height/2;for(const t of e.landmarks){const e=t.x-a,o=t.y-i;if(Math.sqrt(e*e+o*o)<n)return!0}return!1}(l[0],c,this.options.maxHandFaceDistance))o=s.FACE_OBSTRUCTED,this.stableSince=null;else if(function(e){if(e.length<478)return!1;const t=e[159],n=e[144],a=e[386],i=e[373],o=Math.abs(t.y-n.y),s=Math.abs(a.y-i.y);if(o<.01||s<.01)return!1;const r=e[13],l=e[14];if(Math.abs(r.y-l.y)>.025)return!1;const d=e[61],c=e[291],u=e[4];return!((d.y+c.y)/2-u.y<.05)}(i))if(function(e,t){if(t.length<478)return!1;try{const n=document.createElement("canvas"),a=n.getContext("2d");if(!a)return!1;const i=e.videoWidth,o=e.videoHeight,s=[t[33],t[133],t[159],t[144],t[145]],r=[t[263],t[362],t[386],t[373],t[374]],l=e=>{const t=e.map(e=>e.x*i),n=e.map(e=>e.y*o),a=Math.max(0,Math.min(...t)-5),s=Math.min(i,Math.max(...t)+5),r=Math.max(0,Math.min(...n)-5);return{x:a,y:r,width:s-a,height:Math.min(o,Math.max(...n)+5)-r}},d=t=>(n.width=t.width,n.height=t.height,a.drawImage(e,t.x,t.y,t.width,t.height,0,0,t.width,t.height),m(a.getImageData(0,0,t.width,t.height))),c=l(s),u=l(r);return(d(c)+d(u))/2<35}catch(e){return console.warn("Erro ao detectar óculos escuros:",e),!1}}(e,i))o=s.DARK_GLASSES,this.stableSince=null;else{const i=document.createElement("canvas"),l=c.xMin*e.videoWidth,d=c.yMin*e.videoHeight,u=c.width*e.videoWidth,h=c.height*e.videoHeight;i.width=u,i.height=h;const f=i.getContext("2d",{willReadFrequently:!0});if(f){f.drawImage(e,l,d,u,h,0,0,u,h);m(f.getImageData(0,0,i.width,i.height))<this.options.minIlluminationThreshold?(o=s.POOR_ILLUMINATION,this.stableSince=null):function(e,t,n=5,a=512,i=384){if(!e||!t)return!1;const o=(e.boundingBox.xMin+e.boundingBox.width/2)*a,s=(e.boundingBox.yMin+e.boundingBox.height/2)*i,r=(t.boundingBox.xMin+t.boundingBox.width/2)*a,l=(t.boundingBox.yMin+t.boundingBox.height/2)*i,d=Math.abs(o-r),c=Math.abs(s-l),u=Math.abs(e.boundingBox.width-t.boundingBox.width)*a,h=Math.abs(e.boundingBox.height-t.boundingBox.height)*i;return d<=n&&c<=n&&u<=2*n&&h<=2*n}(r,this.lastDetection,this.options.stabilityMovementThreshold,t,n)?(this.stableSince||(this.stableSince=a),o=a-this.stableSince>=this.options.stabilizationTimeThreshold?s.CAPTURING:s.STAY_STILL):(this.stableSince=null,o=s.STAY_STILL)}else o=s.FACE_DETECTED,this.stableSince=null}else o=s.NOT_NEUTRAL_EXPRESSION,this.stableSince=null;else o=s.HEAD_NOT_STRAIGHT,this.stableSince=null;else o=s.FACE_OBSTRUCTED,this.stableSince=null;else o=s.OFF_CENTER,this.stableSince=null}}else this.lastDetection=null,this.stableSince=null;if(this.lastDetection=r,this.setStatus(o),this.options.overlayCanvasElement&&function(e,t,n,a,i){const o=e.getContext("2d");if(!o)return;const r=e.width,l=e.height,d=r/2,c=l/2;o.clearRect(0,0,r,l);const u=.2*r,h=l*g;if(o.fillStyle="rgba(255, 255, 255, 0.35)",o.fillRect(0,0,r,l),o.save(),o.beginPath(),o.ellipse(d,c,u,h,0,0,2*Math.PI),o.closePath(),o.globalCompositeOperation="destination-out",o.fill(),o.restore(),o.strokeStyle="rgba(255, 255, 255, 0.9)",o.lineWidth=3,o.beginPath(),o.ellipse(d,c,u,h,0,0,2*Math.PI),o.stroke(),o.strokeStyle="rgba(255, 255, 255, 0.45)",o.lineWidth=1,o.beginPath(),o.moveTo(d-6,c),o.lineTo(d+6,c),o.moveTo(d,c-6),o.lineTo(d,c+6),o.stroke(),t&&a){const e=a.landmarks;if(e.length>=478){const t=e[10],a=e[152],i=e[234],d=e[454],c=e.map(e=>e.x),u=e.map(e=>e.y),h=Math.min(...c),m=Math.max(...c),p=Math.min(...u),g=m-h,v=Math.max(...u)-p,S=.08,y=(h-g*S)*r,C=(p-v*S)*l,T=g*(1+2*S)*r,b=v*(1+2*S)*l;let O="red";n===s.STAY_STILL||n===s.CAPTURING?O="lime":n===s.FACE_DETECTED&&(O="yellow"),o.strokeStyle=O,o.lineWidth=3,o.strokeRect(y,C,T,b);const I=e[4];e[f[0]],e[E[0]],o.fillStyle="cyan",o.beginPath(),o.arc(I.x*r,I.y*l,5,0,2*Math.PI),o.fill(),o.fillStyle="magenta",o.beginPath(),o.arc(t.x*r,t.y*l,4,0,2*Math.PI),o.fill(),o.fillStyle="lime",o.beginPath(),o.arc(a.x*r,a.y*l,4,0,2*Math.PI),o.fill(),o.fillStyle="yellow",[e[33],e[133],e[159],e[144],e[145]].forEach(e=>{o.beginPath(),o.arc(e.x*r,e.y*l,3,0,2*Math.PI),o.fill()}),o.fillStyle="yellow",[e[263],e[362],e[386],e[373],e[374]].forEach(e=>{o.beginPath(),o.arc(e.x*r,e.y*l,3,0,2*Math.PI),o.fill()}),o.fillStyle="purple",o.beginPath(),o.arc(i.x*r,i.y*l,3,0,2*Math.PI),o.fill(),o.beginPath(),o.arc(d.x*r,d.y*l,3,0,2*Math.PI),o.fill()}}t&&i&&i.length>0&&i.forEach(e=>{o.fillStyle="orange",e.landmarks.forEach(e=>{o.beginPath(),o.arc(e.x*r,e.y*l,3,0,2*Math.PI),o.fill()})})}(this.options.overlayCanvasElement,this.options.debugMode||!1,o,r||void 0,l.length>0?l:void 0),o===s.CAPTURING&&!this.isCapturing)return this.isCapturing=!0,yield this.captureImage(),this.setStatus(s.SUCCESS),void this.stop()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.setStatus(s.ERROR,t)}this.animationFrameId=requestAnimationFrame(a)}else this.animationFrameId=requestAnimationFrame(a)});this.animationFrameId=requestAnimationFrame(a)}estimateBoundingBox(e){const t=e.map(e=>e.x),n=e.map(e=>e.y),a=Math.min(...t),i=Math.max(...t),o=Math.min(...n);return{xMin:a,yMin:o,width:i-a,height:Math.max(...n)-o}}captureImage(){return v(this,void 0,void 0,function*(){const e=this.getVideoElement(),t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;const n=t.getContext("2d");n?(n.drawImage(e,0,0,t.width,t.height),t.toBlob(e=>{e?this.options.onCaptureSuccess(e):this.setStatus(s.ERROR,new Error("Failed to generate image blob"))},"image/jpeg",.95)):this.setStatus(s.ERROR,new Error("Failed to get canvas context"))})}stop(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.faceLandmarker&&this.faceLandmarker.close(),this.handLandmarker&&this.handLandmarker.close(),this.managedCamera&&this.stopCamera()}destroy(){this.stop(),this.managedElements&&this.containerElement&&(this.containerElement.innerHTML=""),this.statusElement=null,this.uiRootElement=null}stopCamera(){this.cameraStream&&(this.cameraStream.getTracks().forEach(e=>e.stop()),this.cameraStream=null)}getVideoElement(){if(!this.options.videoElement)throw new Error("Video element is not available. Provide videoElement or container.");return this.options.videoElement}}var C=i(848),T=i(883);const b=[s.SUCCESS,s.ERROR,s.CAPTURING,s.INITIALIZING],O={"pt-BR":{previewQuestion:"O que você achou?",savePhoto:"Salvar foto",tryAgain:"Tentar novamente",cancel:"Cancelar"},en:{previewQuestion:"What do you think?",savePhoto:"Save photo",tryAgain:"Try again",cancel:"Cancel"},es:{previewQuestion:"¿Qué te pareció?",savePhoto:"Guardar foto",tryAgain:"Intentar de nuevo",cancel:"Cancelar"}},I=({onCapture:e,onDismiss:t,locale:n,videoWidth:a=512,videoHeight:i=384,debugMode:o=!1,modelPath:r,styles:l,labels:d})=>{const c=(e=>{if(!e)return"pt-BR";const t=e.toLowerCase();return t.startsWith("en")?"en":t.startsWith("es")?"es":"pt-BR"})(n),h=O[c],m=Object.assign(Object.assign({},h),null!=d?d:{}),f=(0,T.useRef)(null),E=(0,T.useRef)(null),p=(0,T.useRef)(null),g=(0,T.useRef)(null),v=(0,T.useRef)(0),S=(0,T.useRef)(""),[I,R]=(0,T.useState)(s.INITIALIZING),[x,_]=(0,T.useState)(u(s.INITIALIZING,c)),[A,L]=(0,T.useState)(u(s.INITIALIZING,c)),[M,F]=(0,T.useState)(!0),[N,k]=(0,T.useState)(null),P=(0,T.useCallback)((e,t)=>{R(e),_(t)},[]);(0,T.useEffect)(()=>{if(S.current=x,x===A)return;if(b.includes(I))return g.current&&(clearTimeout(g.current),g.current=null),L(x),void(v.current=Date.now());const e=Date.now(),t=e-v.current;if(t>=1500)return L(x),void(v.current=e);if(g.current)return;const n=1500-t;g.current=setTimeout(()=>{L(S.current),v.current=Date.now(),g.current=null},n)},[x,I,A]);const w=(0,T.useCallback)(e=>{var t;R(s.SUCCESS),_(u(s.SUCCESS,c)),(t=e,new Promise((e,n)=>{const a=new FileReader;a.onloadend=()=>e(a.result),a.onerror=n,a.readAsDataURL(t)})).then(e=>{k(e),F(!1)})},[c]),D=(0,T.useCallback)(()=>{e(null!=N?N:null),null==t||t()},[e,t,N]),U=(0,T.useCallback)(()=>{k(null),R(s.INITIALIZING),_(u(s.INITIALIZING,c)),F(!0)},[c]),j=(0,T.useCallback)((e,t)=>{_(t.message),R(s.ERROR)},[]);(0,T.useEffect)(()=>{const e=f.current;if(!M)return void(p.current&&(p.current.destroy(),p.current=null));if(!e)return;let t=!1;return(n=void 0,l=void 0,d=void 0,u=function*(){var n;try{const s=E.current;if(s&&!s.width&&(s.width=a,s.height=i),p.current||t)return;const l={videoElement:e,overlayCanvasElement:null!==(n=E.current)&&void 0!==n?n:void 0,locale:c,debugMode:o,onStatusUpdate:P,onCaptureSuccess:w,onError:j,videoWidth:a,videoHeight:i,ui:"none",autoStart:!0,mirror:!0};r&&(l.modelPath=r);const d=new y(l);p.current=d}catch(e){if(t)return;_(e.message),R(s.ERROR)}},new(d||(d=Promise))(function(e,t){function a(e){try{o(u.next(e))}catch(e){t(e)}}function i(e){try{o(u.throw(e))}catch(e){t(e)}}function o(t){var n;t.done?e(t.value):(n=t.value,n instanceof d?n:new d(function(e){e(n)})).then(a,i)}o((u=u.apply(n,l||[])).next())})).catch(()=>{}),()=>{t=!0,p.current&&(p.current.destroy(),p.current=null)};var n,l,d,u},[M,c,a,i,o,r,P,w,j]);const B=!M&&Boolean(N),G=M,H=Object.assign({width:"100%",maxWidth:640,boxSizing:"border-box"},null==l?void 0:l.container),z=Object.assign({textAlign:"center",display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,padding:"10px 12px",marginBottom:10,borderRadius:10,fontWeight:600,marginTop:30,height:52,boxSizing:"border-box",transition:"all 0.4s ease-in-out"},null==l?void 0:l.messageBanner),W=Object.assign(Object.assign({},z),{backgroundColor:"#fff7df",color:"#b67219"});G&&(I===s.SUCCESS?(W.backgroundColor="#e0ffdf",W.color="#26c026"):I===s.ERROR&&(W.backgroundColor="#ffdfdf",W.color="#c02626"));const q=Object.assign({width:"100%",maxWidth:512,height:384,margin:"0 auto",borderRadius:10,overflow:"hidden",position:"relative",backgroundColor:"#1a1a1a"},null==l?void 0:l.media),V={display:"block",width:"100%",padding:"8px 12px",borderRadius:4,border:"1px solid #d9d9d9",backgroundColor:"#ffffff",cursor:"pointer",fontSize:14},Z=Object.assign(Object.assign(Object.assign({},V),{backgroundColor:"#1dbe32",color:"#ffffff",borderColor:"#1dbe32"}),null==l?void 0:l.primaryButton),K=Object.assign(Object.assign({},V),null==l?void 0:l.secondaryButton);return(0,C.jsxs)("div",{style:H,children:[(0,C.jsx)("div",{style:W,children:B?m.previewQuestion:A}),(0,C.jsx)("div",{style:q,children:G?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)("video",{ref:f,autoPlay:!0,playsInline:!0,muted:!0,style:{width:"100%",height:"100%",objectFit:"cover"}}),(0,C.jsx)("canvas",{ref:E,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",transform:"scaleX(-1)"}})]}):B&&N?(0,C.jsx)("img",{src:N,alt:"Selfie preview",style:{display:"block",width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)",backgroundColor:"transparent",border:"none"}}):(0,C.jsx)("div",{"aria-hidden":!0})}),(0,C.jsx)("div",{style:{marginTop:10},children:B?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)("button",{type:"button",onClick:U,style:K,children:m.tryAgain}),(0,C.jsx)("div",{style:{height:8}}),(0,C.jsx)("button",{type:"button",onClick:D,disabled:!N,style:Object.assign(Object.assign({},Z),{opacity:N?1:.6,cursor:N?"pointer":"not-allowed"}),children:m.savePhoto})]}):(0,C.jsx)("button",{type:"button",onClick:()=>{null==t||t(),e(null),F(!1)},style:K,children:m.cancel})})]})},R=y;return o})());
3
3
  //# sourceMappingURL=face-validator-sdk.umd.js.map