@jaak.ai/stamps 2.0.0 → 2.1.0-dev.2
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.
- package/README.md +11 -1
- package/dist/cjs/jaak-stamps-webcomponent.cjs.js +1 -1
- package/dist/cjs/jaak-stamps.cjs.entry.js +759 -623
- package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
- package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
- package/dist/cjs/loader.cjs.js +1 -1
- package/dist/collection/components/my-component/my-component.css +178 -11
- package/dist/collection/components/my-component/my-component.js +566 -250
- package/dist/collection/components/my-component/my-component.js.map +1 -1
- package/dist/collection/services/CameraService.js +156 -344
- package/dist/collection/services/CameraService.js.map +1 -1
- package/dist/collection/services/DetectionService.js +68 -38
- package/dist/collection/services/DetectionService.js.map +1 -1
- package/dist/collection/services/EventBusService.js +1 -1
- package/dist/collection/services/EventBusService.js.map +1 -1
- package/dist/collection/services/ServiceContainer.js +4 -13
- package/dist/collection/services/ServiceContainer.js.map +1 -1
- package/dist/collection/services/interfaces/ICameraService.js.map +1 -1
- package/dist/collection/types/component-types.js.map +1 -1
- package/dist/components/jaak-stamps.js +763 -626
- package/dist/components/jaak-stamps.js.map +1 -1
- package/dist/esm/jaak-stamps-webcomponent.js +1 -1
- package/dist/esm/jaak-stamps.entry.js +759 -623
- package/dist/esm/jaak-stamps.entry.js.map +1 -1
- package/dist/esm/loader.js +1 -1
- package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
- package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
- package/dist/jaak-stamps-webcomponent/p-41e88688.entry.js +2 -0
- package/dist/jaak-stamps-webcomponent/p-41e88688.entry.js.map +1 -0
- package/dist/types/components/my-component/my-component.d.ts +68 -17
- package/dist/types/components.d.ts +14 -8
- package/dist/types/services/CameraService.d.ts +12 -14
- package/dist/types/services/DetectionService.d.ts +10 -3
- package/dist/types/services/ServiceContainer.d.ts +1 -2
- package/dist/types/services/interfaces/ICameraService.d.ts +3 -12
- package/dist/types/types/component-types.d.ts +3 -0
- package/package.json +2 -2
- package/dist/collection/services/LoggerService.js +0 -40
- package/dist/collection/services/LoggerService.js.map +0 -1
- package/dist/collection/services/interfaces/ILogger.js +0 -2
- package/dist/collection/services/interfaces/ILogger.js.map +0 -1
- package/dist/jaak-stamps-webcomponent/p-2264b5b4.entry.js +0 -2
- package/dist/jaak-stamps-webcomponent/p-2264b5b4.entry.js.map +0 -1
- package/dist/types/services/LoggerService.d.ts +0 -12
- package/dist/types/services/interfaces/ILogger.d.ts +0 -8
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as t,c as e,a as i,h as s}from"./p-BP1Q4KOg.js";class a{events=new Map;on(t,e){if(!this.events.has(t)){this.events.set(t,[])}this.events.get(t).push(e)}off(t,e){const i=this.events.get(t);if(i){const t=i.indexOf(e);if(t>-1){i.splice(t,1)}}}emit(t,e){const i=this.events.get(t);if(i){i.forEach((t=>{try{t(e)}catch(t){}}))}}once(t,e){const i=s=>{e(s);this.off(t,i)};this.on(t,i)}clear(){this.events.clear()}}class o{eventBus;captureState={step:"front",isCapturing:false,isDetectionPaused:false,isVideoActive:false,isLoading:false,showFlipAnimation:false,showSuccessAnimation:false,bestScore:0,hasScreenshotTaken:false};capturedImages={front:{fullFrame:null,cropped:null},back:{fullFrame:null,cropped:null},metadata:{totalImages:0,processCompleted:false,backCaptureSkipped:false}};constructor(t){this.eventBus=t}getCaptureState(){return{...this.captureState}}updateCaptureState(t){const e={...this.captureState};this.captureState={...this.captureState,...t};this.eventBus.emit("state-changed",{previous:e,current:this.captureState,changes:t})}getCapturedImages(){return JSON.parse(JSON.stringify(this.capturedImages))}setCapturedImages(t){this.capturedImages={...this.capturedImages,...t,metadata:{...this.capturedImages.metadata,...t.metadata}};let e=0;if(this.capturedImages.front.fullFrame&&this.capturedImages.front.cropped){e+=2}if(this.capturedImages.back.fullFrame&&this.capturedImages.back.cropped){e+=2}this.capturedImages.metadata.totalImages=e}reset(){this.captureState={step:"front",isCapturing:false,isDetectionPaused:false,isVideoActive:false,isLoading:false,showFlipAnimation:false,showSuccessAnimation:false,bestScore:0,hasScreenshotTaken:false};this.capturedImages={front:{fullFrame:null,cropped:null},back:{fullFrame:null,cropped:null},metadata:{totalImages:0,processCompleted:false,backCaptureSkipped:false}};this.eventBus.emit("state-changed",{previous:null,current:this.captureState,changes:{reset:true}})}isProcessCompleted(){return this.captureState.step==="completed"}canProceedToBack(){return this.captureState.step==="front"&&this.capturedImages.front.fullFrame!==null&&this.capturedImages.front.cropped!==null}}class r{eventBus;availableCameras=[];selectedCameraId=null;deviceType="desktop";preferredCameraFacing=null;preferredCamera="auto";static cameraCapabilitiesCache=new Map;static deviceEnumerationCache=null;static CACHE_DURATION=3e4;currentStreamPromise;lastStreamConstraints;constructor(t,e="auto"){this.eventBus=t;this.preferredCamera=e}async detectDeviceType(){const t=navigator.userAgent;const e=/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(t);const i=/iPad|Android/i.test(t)&&window.innerWidth>=768;if(i){this.deviceType="tablet"}else if(e){this.deviceType="mobile"}else{this.deviceType="desktop"}return this.deviceType}async enumerateDevices(){try{const t=Date.now();if(r.deviceEnumerationCache&&t-r.deviceEnumerationCache.timestamp<r.CACHE_DURATION){this.availableCameras=r.deviceEnumerationCache.devices;await this.setInitialCameraPreference();this.eventBus.emit("camera-changed",this.selectedCameraId);return this.availableCameras}const e=await this.checkCameraPermission();if(e==="denied"){return[]}if(e==="prompt"){const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()))}const i=await navigator.mediaDevices.enumerateDevices();this.availableCameras=i.filter((t=>t.kind==="videoinput"));r.deviceEnumerationCache={devices:this.availableCameras,timestamp:t};await this.setInitialCameraPreference();this.eventBus.emit("camera-changed",this.selectedCameraId);return this.availableCameras}catch(t){this.handleCameraPermissionError(t);return[]}}getAvailableCameras(){return[...this.availableCameras]}isMultipleCamerasAvailable(){return this.availableCameras.length>1}getSelectedCameraId(){return this.selectedCameraId}async setSelectedCamera(t){const e=this.availableCameras.find((e=>e.deviceId===t));if(!e){throw new Error(`Camera with ID ${t} not found`)}this.selectedCameraId=t;this.updatePreferredFacing(e);this.eventBus.emit("camera-changed",t)}getPreferredFacing(){return this.preferredCameraFacing}async setupCamera(t){try{const e=t||await this.getMaxResolution();if(this.currentStreamPromise&&this.constraintsEqual(e,this.lastStreamConstraints)){return await this.currentStreamPromise}this.currentStreamPromise=navigator.mediaDevices.getUserMedia({video:e,audio:false});this.lastStreamConstraints=e;const i=await this.currentStreamPromise;return i}catch(t){const e={width:{ideal:1280},height:{ideal:720}};if(this.deviceType!=="desktop"&&this.preferredCameraFacing){e.facingMode=this.preferredCameraFacing}this.currentStreamPromise=navigator.mediaDevices.getUserMedia({video:e,audio:false});this.lastStreamConstraints=e;return await this.currentStreamPromise}}async switchCamera(t){const e=this.availableCameras.find((e=>e.deviceId===t));if(!e){await this.enumerateDevices();return}await this.setSelectedCamera(t)}isRearCamera(t){const e=t.getVideoTracks()[0];if(!e)return false;const i=e.getSettings();return i.facingMode==="environment"}async getCameraInfo(){const t=await Promise.all(this.availableCameras.map((async t=>{const e=await this.checkCameraAutofocus(t.deviceId);return{id:t.deviceId,label:t.label||"Unknown Camera",selected:t.deviceId===this.selectedCameraId,hasAutofocus:e}})));return{availableCameras:t,selectedCameraId:this.selectedCameraId,deviceType:this.deviceType,isMultipleCamerasAvailable:this.isMultipleCamerasAvailable(),preferredFacing:this.preferredCameraFacing}}async checkCameraPermission(){try{if(!navigator.permissions){return"prompt"}const t=await navigator.permissions.query({name:"camera"});return t.state}catch(t){return"prompt"}}handleCameraPermissionError(t){this.availableCameras=[];this.eventBus.emit("error",new Error(`Camera permission error: ${t.message}`))}async setInitialCameraPreference(){if(this.availableCameras.length===0)return;if(this.preferredCamera==="front"){await this.selectFrontCamera()}else if(this.preferredCamera==="back"){await this.selectBackCamera()}else{await this.selectAutoCamera()}}async checkCameraAutofocus(t){try{if(r.cameraCapabilitiesCache.has(t)){const e=r.cameraCapabilitiesCache.get(t);return typeof e==="boolean"?e:false}const e=await navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:t}}});const i=e.getVideoTracks()[0];const s=i.getCapabilities();e.getTracks().forEach((t=>t.stop()));const a=s.focusMode&&Array.isArray(s.focusMode)&&s.focusMode.length>0;const o=a&&(s.focusMode.includes("continuous")||s.focusMode.includes("auto"));r.cameraCapabilitiesCache.set(t,o);return o}catch(e){r.cameraCapabilitiesCache.set(t,false);return false}}async selectFrontCamera(){this.preferredCameraFacing="user";const t=this.availableCameras.filter((t=>{const e=t.label.toLowerCase();return e.includes("front")||e.includes("user")||e.includes("selfie")||e.includes("frontal")||!e.includes("back")&&!e.includes("rear")&&!e.includes("environment")}));let e=null;if(t.length>0){for(const i of t){const t=await this.checkCameraAutofocus(i.deviceId);if(t){e=i;break}}if(!e){e=t[0]}}this.selectedCameraId=e?e.deviceId:this.availableCameras[0].deviceId}async selectBackCamera(){this.preferredCameraFacing="environment";const t=this.availableCameras.filter((t=>{const e=t.label.toLowerCase();return e.includes("back")||e.includes("rear")||e.includes("environment")||e.includes("trasera")||e.includes("posterior")}));let e=null;if(t.length>0){for(const i of t){const t=await this.checkCameraAutofocus(i.deviceId);if(t){e=i;break}}if(!e){e=t[0]}}else if(this.availableCameras.length>1){const t=this.availableCameras[this.availableCameras.length-1];const i=await this.checkCameraAutofocus(t.deviceId);e=i?t:this.availableCameras[this.availableCameras.length-1]}this.selectedCameraId=e?e.deviceId:this.availableCameras[0].deviceId}async selectAutoCamera(){if(this.deviceType==="mobile"||this.deviceType==="tablet"){await this.selectBackCamera()}else{await this.selectFrontCamera()}}updatePreferredFacing(t){const e=t.label.toLowerCase().includes("back")||t.label.toLowerCase().includes("rear")||t.label.toLowerCase().includes("environment");this.preferredCameraFacing=e?"environment":"user"}async getMaxResolution(){try{if(!this.deviceType||this.deviceType==="desktop"){await this.detectDeviceType()}const t={};if(this.selectedCameraId){t.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){const e=this.deviceType==="desktop"?{ideal:this.preferredCameraFacing}:{exact:this.preferredCameraFacing};t.facingMode=e}else{if(this.preferredCamera==="front"){t.facingMode="user"}else if(this.preferredCamera==="back"){t.facingMode="environment"}else{t.facingMode=this.deviceType==="mobile"||this.deviceType==="tablet"?"environment":"user"}}let e;if(this.selectedCameraId&&r.cameraCapabilitiesCache.has(this.selectedCameraId+"_caps")){e=JSON.parse(r.cameraCapabilitiesCache.get(this.selectedCameraId+"_caps"))}else{const i=await navigator.mediaDevices.getUserMedia({video:t});const s=i.getVideoTracks()[0];e=s.getCapabilities();i.getTracks().forEach((t=>t.stop()));if(this.selectedCameraId){r.cameraCapabilitiesCache.set(this.selectedCameraId+"_caps",JSON.stringify(e))}}const i={...t};if(e.width&&e.height){const t=Math.min(e.width.max,1920);const s=Math.min(e.height.max,1080);const a=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;if(a){i.width={ideal:Math.min(t,1280)};i.height={ideal:Math.min(s,720)}}else{i.width={ideal:t};i.height={ideal:s}}}const s=e;if(s.focusMode&&Array.isArray(s.focusMode)){if(s.focusMode.includes("continuous")){i.focusMode="continuous"}else if(s.focusMode.includes("auto")){i.focusMode="auto"}}return i}catch(t){if(!this.deviceType||this.deviceType==="desktop"){await this.detectDeviceType()}const e=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const i={width:{ideal:e?1280:1920},height:{ideal:e?720:1080}};if(this.selectedCameraId){i.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){const t=this.deviceType==="desktop"?{ideal:this.preferredCameraFacing}:{exact:this.preferredCameraFacing};i.facingMode=t}else{if(this.preferredCamera==="front"){i.facingMode="user"}else if(this.preferredCamera==="back"){i.facingMode="environment"}else{i.facingMode=this.deviceType==="mobile"||this.deviceType==="tablet"?"environment":"user"}}return i}}constraintsEqual(t,e){if(!t||!e)return false;return JSON.stringify(t)===JSON.stringify(e)}static clearCaches(){r.cameraCapabilitiesCache.clear();r.deviceEnumerationCache=null}invalidateDeviceCache(){r.deviceEnumerationCache=null}}class n{getDeviceInfo(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=t.connection||t.mozConnection||t.webkitConnection;const s=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:true,isSlowConnection:s}}getSessionOptions(t){return{executionProviders:["wasm"],graphOptimizationLevel:"basic",logSeverityLevel:4,logVerbosityLevel:0,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1}}shouldUseSequentialLoading(){return true}}class c{getDeviceInfo(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=t.connection||t.mozConnection||t.webkitConnection;const s=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:false,isSlowConnection:s}}getSessionOptions(t){return{executionProviders:["webgl","wasm"],graphOptimizationLevel:"all",logSeverityLevel:t?2:4,logVerbosityLevel:0,enableCpuMemArena:true,enableMemPattern:true,executionMode:"parallel",interOpNumThreads:2,intraOpNumThreads:2}}shouldUseSequentialLoading(){return false}}class d{static createStrategy(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=e<=4;if(i){return new n}else{return new c}}}class l{debug;useDocumentClassification;useDocumentDetector;session;mobileNetSession;mobileNetClassMap;modelLoaded=false;deviceStrategy;MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v2.onnx";MOBILENET_MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/squeezenet_new_fp32.onnx";MOBILENET_CLASSES_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";INPUT_SIZE=320;CONFIDENCE_THRESHOLD=.6;preprocessCanvas;preprocessCtx;captureCanvas;static canvasPool=new Map;static MAX_POOL_SIZE=5;constructor(t=false,e=false,i=true){this.debug=t;this.useDocumentClassification=e;this.useDocumentDetector=i;this.deviceStrategy=d.createStrategy();this.initializeCanvasPool()}async loadModel(){if(this.modelLoaded||this.session){return}if(!this.useDocumentDetector){this.modelLoaded=true;return}try{const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}catch(t){if(t.message.includes("failed to allocate a buffer")){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1};this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}else{throw t}}this.modelLoaded=true}catch(t){throw t}}async loadClassificationModel(){if(!this.useDocumentClassification){return}try{try{const t=await fetch(this.MOBILENET_CLASSES_PATH);if(t.ok){this.mobileNetClassMap=await t.json()}}catch(t){this.mobileNetClassMap={0:"document",1:"id_card",2:"passport",3:"license",4:"other"}}const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}catch(t){if(t.message.includes("failed to allocate a buffer")){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1};this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}else{throw t}}}catch(t){throw t}}isModelLoaded(){if(!this.useDocumentDetector){return this.modelLoaded}return this.modelLoaded&&!!this.session}preprocess(t){if(!this.preprocessCanvas||!this.preprocessCtx){this.initializeCanvasPool()}this.preprocessCtx.clearRect(0,0,this.INPUT_SIZE,this.INPUT_SIZE);this.preprocessCtx.drawImage(t,0,0,this.INPUT_SIZE,this.INPUT_SIZE);const e=this.preprocessCtx.getImageData(0,0,this.INPUT_SIZE,this.INPUT_SIZE);const[i,s,a]=[[],[],[]];const{data:o}=e;for(let t=0;t<o.length;t+=4){i.push(o[t]/255);s.push(o[t+1]/255);a.push(o[t+2]/255)}const r=new Float32Array(i.concat(s,a));const n=new Uint16Array(r.length);for(let t=0;t<r.length;t++){n[t]=this.float32ToFloat16(r[t])}return new window.ort.Tensor("float16",n,[1,3,this.INPUT_SIZE,this.INPUT_SIZE])}async runInference(t){if(!this.useDocumentDetector){return[]}if(!this.session){throw new Error("Detection model not loaded")}const e={[this.session.inputNames[0]]:t};const i=await this.session.run(e);const s=i[this.session.outputNames[0]].data;const a=[];for(let t=0;t<s.length;t+=6){const[e,i,o,r,n,c]=s.slice(t,t+6);if(n>this.CONFIDENCE_THRESHOLD){a.push({x:e,y:i,w:o-e,h:r-i,score:n,classId:c})}}return a}async classifyDocument(t){if(!this.mobileNetSession||!this.mobileNetClassMap){return null}try{const e=this.preprocessMobileNet(t);const i={[this.mobileNetSession.inputNames[0]]:e};const s=await this.mobileNetSession.run(i);const a=s[Object.keys(s)[0]].data;const o=a.reduce(((t,e,i,s)=>e>s[t]?i:t),0);const r=a[o];const n=this.mobileNetClassMap[o.toString()]||"unknown";return{class:n,confidence:r,classIndex:o}}catch(t){return null}}checkSideAlignment(t,e){const{INPUT_SIZE:i,ID1_ASPECT_RATIO:s,shouldMirrorVideo:a,alignmentTolerance:o,maskSize:r,videoRef:n}=e;if(!n){return{top:false,right:false,bottom:false,left:false}}const c=n.videoWidth;const d=n.videoHeight;if(c===0||d===0){return{top:false,right:false,bottom:false,left:false}}const l=c/d;const h=1;let f,p;if(l>h){f=i;p=i/l}else{p=i;f=i*l}const u=p*s;let m,b;const g=r/100;if(u<=f){b=p*g;m=b*s}else{m=f*g;b=m/s}const x=m*(i/f);const y=b*(i/p);const w=i/2;const v=i/2;const k=w-x/2;const C=w+x/2;const S=v-y/2;const M=v+y/2;let z=t.x;let P=t.x+t.w;const A=t.y;const T=t.y+t.h;if(a){const t=z;const e=P;z=i-e;P=i-t}const I=o;const D=Math.abs(A-S)<=I;const F=Math.abs(P-C)<=I;const E=Math.abs(T-M)<=I;const L=Math.abs(z-k)<=I;return{top:D&&L,right:D&&F,bottom:E&&L,left:E&&F}}isCardInFrame(t){const e=t.x+t.w/2;const i=t.y+t.h/2;const s=this.INPUT_SIZE/2;const a=this.INPUT_SIZE/2;const o=40;const r=30;const n=Math.abs(e-s)<o&&Math.abs(i-a)<r;const c=t.w>150&&t.w<300&&t.h>90&&t.h<200;return n&&c}areAllSidesAligned(t){return t.top&&t.right&&t.bottom&&t.left}cleanup(){this.cleanupCanvasPool();if(this.session){this.session.release?.();this.session=undefined}if(this.mobileNetSession){this.mobileNetSession.release?.();this.mobileNetSession=undefined}this.mobileNetClassMap=undefined;this.modelLoaded=false}initializeCanvasPool(){this.preprocessCanvas=document.createElement("canvas");this.preprocessCanvas.width=this.INPUT_SIZE;this.preprocessCanvas.height=this.INPUT_SIZE;this.preprocessCtx=this.preprocessCanvas.getContext("2d",{alpha:false,willReadFrequently:true});this.captureCanvas=document.createElement("canvas")}cleanupCanvasPool(){if(this.preprocessCanvas){this.preprocessCtx=undefined;this.preprocessCanvas=undefined}if(this.captureCanvas){this.captureCanvas=undefined}}float32ToFloat16(t){const e=new ArrayBuffer(4);const i=new DataView(e);i.setFloat32(0,t,true);const s=i.getUint32(0,true);const a=s>>31&1;const o=s>>23&255;const r=s&8388607;let n=o-127+15;if(o===0){n=0}else if(o===255){n=31}else if(n>=31){n=31;return a<<15|n<<10}else if(n<=0){return a<<15}return a<<15|n<<10|r>>13}preprocessMobileNet(t){const e=this.getCanvas(224,224);const i=e.getContext("2d");i.clearRect(0,0,224,224);i.drawImage(t,0,0,224,224);const s=i.getImageData(0,0,224,224);const a=s.data;const o=224*224;const r=new Float32Array(3*o);for(let t=0;t<o;t++){r[t]=a[t*4+0]/255;r[o+t]=a[t*4+1]/255;r[2*o+t]=a[t*4+2]/255}this.returnCanvas(e);return new window.ort.Tensor("float32",r,[1,3,224,224])}getCanvas(t,e){const i=`${t}x${e}`;if(!l.canvasPool.has(i)){l.canvasPool.set(i,[])}const s=l.canvasPool.get(i);let a=s.pop();if(!a){a=document.createElement("canvas");a.width=t;a.height=e}else{const i=a.getContext("2d");i.clearRect(0,0,t,e)}return a}returnCanvas(t){const e=`${t.width}x${t.height}`;if(!l.canvasPool.has(e)){l.canvasPool.set(e,[])}const i=l.canvasPool.get(e);if(i.length<l.MAX_POOL_SIZE){i.push(t)}}static clearCanvasPools(){l.canvasPool.clear()}getPoolStats(){const t={};l.canvasPool.forEach(((e,i)=>{t[i]=e.length}));return t}}class h{services=new Map;constructor(t){this.initializeServices(t)}initializeServices(t){const e=new a;const i=new o(e);const s=new r(e,t.preferredCamera);const n=new l(t.debug,t.useDocumentClassification,t.useDocumentDetector);this.services.set("eventBus",e);this.services.set("stateManager",i);this.services.set("cameraService",s);this.services.set("detectionService",n)}get(t){const e=this.services.get(t);if(!e){throw new Error(`Service ${t} not found`)}return e}getEventBus(){return this.get("eventBus")}getStateManager(){return this.get("stateManager")}getCameraService(){return this.get("cameraService")}getDetectionService(){return this.get("detectionService")}updateConfig(t){}cleanup(){this.getDetectionService().cleanup();this.getEventBus().clear();this.services.clear()}}const f=":host{display:block;width:100%;height:100%;font-family:system-ui, -apple-system, sans-serif;color:#1a1a1a}.detector-container{display:flex;flex-direction:column;align-items:center;width:100%;height:100%}h1{font-size:24px;font-weight:500;color:#333;margin:0 0 24px 0}.video-container{position:relative;width:100%;height:100%;background:#333;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden}video,.detection-overlay{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,.detection-overlay.mirror{transform:rotateY(180deg)}.detection-overlay{z-index:1;pointer-events:none}video{z-index:0}.detection-box{transition:opacity 0.2s ease}.status{margin-top:16px;font-size:12px;color:#666}.overlay-mask{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10;display:block;pointer-events:none}.card-outline{position:absolute;top:var(--mask-center-y, 50%);left:var(--mask-center-x, 50%);transform:translate(-50%, -50%);width:var(--mask-width, 88%);height:var(--mask-height, 55%);border:none;border-radius:4px;background:transparent;opacity:0.8}.side{position:absolute;background:#999;transition:background-color 0.3s ease;border-radius:1px}.side-top.aligned{border-left-color:#28a745;border-top-color:#28a745}.side-right.aligned{border-right-color:#28a745;border-top-color:#28a745}.side-bottom.aligned{border-left-color:#28a745;border-bottom-color:#28a745}.side-left.aligned{border-right-color:#28a745;border-bottom-color:#28a745}.side-top{top:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-right{top:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-bottom{bottom:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.side-left{bottom:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);color:#ffffff;font-size:12px;font-weight:500;text-align:center;white-space:normal;padding:13px;max-width:300px;z-index:20;height:fit-content;width:fit-content;animation:slideInFromTopCentered 0.3s ease-out}.quality-indicator{position:absolute;top:20px;right:20px;display:flex;align-items:center;gap:8px;background:rgba(0, 0, 0, 0.8);padding:8px 12px;border-radius:20px;z-index:25;transition:all 0.3s ease}.quality-indicator.warning{background:rgba(255, 152, 0, 0.9)}.quality-indicator.good{background:rgba(76, 175, 80, 0.9)}.quality-score{color:#fff;font-size:12px;font-weight:600;min-width:30px;text-align:center}.quality-status{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:bold;color:#fff;transition:all 0.3s ease}.quality-status.ready{background:#4CAF50}.quality-status.not-ready{background:#f44336}.card-outline.quality-warning{animation:qualityWarning 1s ease-in-out infinite alternate}@keyframes qualityWarning{0%{box-shadow:0 0 0 3px rgba(255, 152, 0, 0.6)}100%{box-shadow:0 0 0 6px rgba(255, 152, 0, 0.3)}}.capture-animation{position:absolute;top:0;left:0;width:100%;height:100%;background:#fff;opacity:0;z-index:30;pointer-events:none;animation:captureFlash 0.6s ease-out}@keyframes captureFlash{0%{opacity:0}15%{opacity:0.8}30%{opacity:0}45%{opacity:0.4}60%{opacity:0}100%{opacity:0}}.card-outline.capturing{animation:pulseGreen 0.6s ease-out}@keyframes pulseGreen{0%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}}.flip-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showFlipInstruction 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.id-card-icon{width:80px;height:50px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:8px;position:relative;animation:flipCard 2s ease-in-out infinite;box-shadow:0 4px 12px rgba(0, 0, 0, 0.3)}.id-card-icon::before{content:'';position:absolute;top:8px;left:8px;width:16px;height:12px;background:rgba(255, 255, 255, 0.9);border-radius:2px}.id-card-icon::after{content:'';position:absolute;top:25px;left:8px;width:64px;height:3px;background:rgba(255, 255, 255, 0.7);border-radius:1px;box-shadow:0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7)}.flip-text{margin-top:12px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px}@keyframes showFlipInstruction{0%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}}@keyframes flipCard{0%{transform:rotateY(0deg)}50%{transform:rotateY(180deg)}100%{transform:rotateY(360deg)}}.success-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showSuccessMessage 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.check-icon{width:80px;height:80px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:50%;position:relative;animation:bounceSuccess 0.6s ease-out;box-shadow:0 4px 16px rgba(108, 117, 125, 0.4);display:flex;align-items:center;justify-content:center}.check-icon::before{content:'';position:absolute;width:20px;height:35px;border:4px solid #fff;border-top:none;border-left:none;transform:rotate(45deg);animation:drawCheck 0.4s ease-out 0.2s both}.success-text{margin-top:16px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;animation:fadeInUp 0.5s ease-out 0.4s both}@keyframes showSuccessMessage{0%{opacity:0;transform:translate(-50%, -50%) scale(0.5)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.9)}}@keyframes bounceSuccess{0%{transform:scale(0)}50%{transform:scale(1.1)}100%{transform:scale(1)}}@keyframes drawCheck{0%{width:0;height:0}50%{width:20px;height:0}100%{width:20px;height:35px}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.skip-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.back-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:320px}.back-capture-buttons{display:flex;gap:12px;align-items:center;justify-content:center;flex-wrap:wrap}.capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.capture-button:hover{background:#f8f9fa}.capture-button:active{background:#e9ecef;transform:translateY(1px)}.capture-button:disabled{background:#e9ecef;color:#6c757d;cursor:not-allowed;transform:none}@media (max-width: 480px){.back-capture-section{bottom:16px;max-width:300px}.back-capture-buttons{flex-direction:column;gap:8px;width:100%}.capture-button,.back-capture-buttons .skip-button{width:100%;max-width:200px;padding:10px 20px;font-size:13px}}.skip-explanation{background:rgba(0, 0, 0, 0.5);color:#ffffff;padding:10px 16px;border-radius:8px;font-size:14px;font-weight:500;text-align:center;margin-bottom:12px;box-shadow:0 2px 8px rgba(0, 0, 0, 0.2);backdrop-filter:blur(12px);border:1px solid rgba(255, 255, 255, 0.1);animation:fadeIn 0.3s ease-in-out}@keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.skip-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.skip-button:hover{background:#f8f9fa}.skip-button:active{background:#e9ecef;transform:translateY(1px)}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}.camera-selector-button{height:32px;padding:0 10px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-button:disabled,.camera-selector-button.loading{opacity:0.7;cursor:not-allowed;pointer-events:none}.camera-selector-button:disabled:hover,.camera-selector-button.loading:hover{transform:none;background:rgba(0, 0, 0, 0.6);border-color:rgba(255, 255, 255, 0.1)}.button-spinner{width:16px;height:16px;border:2px solid rgba(255, 255, 255, 0.3);border-top:2px solid #ffffff;border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;min-width:260px;max-width:300px;border:1px solid rgba(255, 255, 255, 0.1);overflow:hidden;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-8px) scale(0.95)}100%{opacity:1;transform:translateY(0) scale(1)}}@keyframes slideInFromTopCentered{0%{opacity:0;transform:translate(-50%, -50%) translateY(-8px) scale(0.95)}100%{opacity:1;transform:translate(-50%, -50%) translateY(0) scale(1)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(255, 255, 255, 0.1)}.camera-selector-header span{font-weight:500;color:#ffffff;font-size:13px;opacity:0.9}.close-selector{width:20px;height:20px;border:none;background:none;color:rgba(255, 255, 255, 0.7);font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s ease}.close-selector:hover{background:rgba(255, 255, 255, 0.1);color:#ffffff}.camera-list{padding:4px 0;max-height:240px;overflow-y:auto}.camera-option{width:100%;padding:8px 12px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:flex-start;align-items:center;gap:8px;color:rgba(255, 255, 255, 0.9)}.camera-option:hover{background:rgba(255, 255, 255, 0.08)}.camera-option.selected{background:rgba(255, 255, 255, 0.12);color:#ffffff}.camera-label{font-size:13px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:0;font-weight:400;display:flex;align-items:center;gap:6px}.camera-label .autofocus-icon{font-size:12px;color:#ffffff !important;opacity:0.8;flex-shrink:0}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9;flex-shrink:0}.device-info{padding:6px 12px;border-top:1px solid rgba(255, 255, 255, 0.1);background:rgba(255, 255, 255, 0.05)}.device-info small{color:rgba(255, 255, 255, 0.6);font-size:11px;text-transform:capitalize;font-weight:400}@media (max-width: 480px){.camera-controls{top:12px;right:12px;gap:6px}.camera-selector-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-dropdown{right:12px;top:48px;min-width:240px;max-width:calc(100vw - 24px)}.camera-selector-header{padding:6px 10px}.camera-option{padding:6px 10px}.device-info{padding:4px 10px}}.watermark{position:absolute;bottom:12px;right:12px;z-index:15;pointer-events:none;opacity:0.7}.watermark img{height:24px;width:auto;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))}.component-status{position:absolute;top:16px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);display:flex;align-items:center;gap:6px;padding:6px 10px;z-index:40;height:32px;width:fit-content;animation:slideInFromTop 0.3s ease-out}.status-spinner{width:16px;height:16px;border:1px solid rgba(255, 255, 255, 0.3);border-top:1px solid #ffffff;border-radius:50%;animation:statusSpin 1s linear infinite;flex-shrink:0}.status-content{display:flex;flex-direction:column;gap:1px}.status-message{color:#ffffff;font-size:12px;font-weight:500;margin:0}.status-description{color:rgba(255, 255, 255, 0.7);font-size:10px;line-height:1.2;margin:0}@keyframes statusSpin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@media (max-width: 480px){.component-status{top:12px;left:12px;padding:4px 8px;gap:4px;height:28px;border-radius:8px}.status-spinner{width:14px;height:14px}.status-message{font-size:11px}.status-description{font-size:9px}.guide-text{font-size:11px;padding:4px 8px;border-radius:8px}}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.85);backdrop-filter:blur(4px);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:8px}.loading-spinner{width:50px;height:50px;border:3px solid rgba(255, 255, 255, 0.15);border-top:3px solid #28a745;border-radius:50%;animation:spin 1s ease-in-out infinite;margin-bottom:16px}.loading-text{color:#ffffff;font-size:14px;font-weight:500;text-align:center;opacity:0.9;margin-bottom:4px}.loading-description{color:rgba(255, 255, 255, 0.7);font-size:12px;text-align:center;opacity:0.8}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.performance-monitor{position:absolute;top:70px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromTop 0.3s ease-out;transition:all 0.3s ease}@keyframes slideInFromLeft{0%{opacity:0;transform:translateX(-20px) scale(0.95)}100%{opacity:1;transform:translateX(0) scale(1)}}.performance-expanded{padding:6px 10px}.metrics-row{display:flex;gap:8px;margin-bottom:4px}.metrics-row:last-child{margin-bottom:0}.metric-compact{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:50px}.metric-label{font-size:9px;color:rgba(255, 255, 255, 0.6);font-weight:500;text-transform:uppercase;letter-spacing:0.3px}.metric-value{font-size:10px;font-weight:600;font-family:'Monaco', 'Menlo', 'Consolas', monospace;padding:2px 4px;border-radius:3px;text-align:center;white-space:nowrap}.metric-value.good{color:#4ade80;background:rgba(74, 222, 128, 0.1);border:1px solid rgba(74, 222, 128, 0.2)}.metric-value.warning{color:#fbbf24;background:rgba(251, 191, 36, 0.1);border:1px solid rgba(251, 191, 36, 0.2)}.metric-value.danger{color:#f87171;background:rgba(248, 113, 113, 0.1);border:1px solid rgba(248, 113, 113, 0.2)}@media (max-width: 480px){.performance-monitor{top:60px;left:12px;width:fit-content}.performance-expanded{padding:4px 8px}.metrics-row{gap:6px;margin-bottom:3px}.metric-compact{min-width:45px;gap:1px}.metric-label{font-size:8px}.metric-value{font-size:9px;padding:1px 3px}}.quality-monitor{position:absolute;top:200px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromLeft 0.3s ease-out;transition:all 0.3s ease}.quality-text{padding:6px 10px;font-size:11px;color:white;font-family:'Monaco', 'Menlo', 'Consolas', monospace;line-height:1.4}.quality-fail{color:#ff9999}@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.7}}.metric-value.danger{animation:pulse 2s infinite}@media (max-width: 480px){.quality-monitor{top:160px;left:12px}.quality-text{padding:4px 8px;font-size:10px}}.manual-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.manual-capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.manual-capture-button:hover{background:#f8f9fa}.manual-capture-button:active{background:#e9ecef;transform:translateY(1px)}.manual-capture-button:disabled{background:#e9ecef;color:#6c757d;cursor:not-allowed;transform:none}@media (max-width: 480px){.manual-capture-section{bottom:16px;max-width:280px}.manual-capture-button{padding:10px 20px;font-size:13px}}";const p=class{constructor(i){t(this,i);this.captureCompleted=e(this,"captureCompleted");this.isReady=e(this,"isReady")}get el(){return i(this)}debug=false;alignmentTolerance=15;maskSize=90;cropMargin=20;useDocumentClassification=false;useDocumentDetector=true;preferredCamera="auto";captureDelay=1500;enableBackDocumentTimer=false;backDocumentTimerDuration=20;captureCompleted;isReady;detectionBoxes=[];sideAlignment={top:false,right:false,bottom:false,left:false};isMaskReady=false;shouldMirrorVideo=true;showCameraSelector=false;isSwitchingCamera=false;hasDocumentDetected=false;cameraInfoWithAutofocus={availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null};currentStatus={message:"Preparando capturador...",description:"Configurando herramientas de captura",type:"initializing",isInitialized:false};performanceData={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0};backDocumentTimerRemaining=0;showManualCaptureButton=false;serviceContainer;eventBus;stateManager;cameraService;detectionService;videoRef;detectionContainer;videoStream;animationId;lastDetectedBox;startTime;hasScreenshotTaken=false;alignmentStartTime;alignmentTimer;backDocumentTimer;performanceMetrics={fps:0,inferenceTime:0,memoryUsage:0,cpuUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0,lastUpdateTime:0};performanceUpdateInterval;frameSkipCounter=0;BASE_FRAME_SKIP=2;MAX_FRAME_SKIP=8;consecutiveFailures=0;MAX_FAILURES=30;lastInferenceTime=0;MIN_INFERENCE_INTERVAL=50;performanceHistory=[];PERFORMANCE_HISTORY_SIZE=10;canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentDidLoad(){this.updateStatus("Preparando capturador...","Configurando herramientas de captura","initializing");await this.initializeServices();this.updateStatus("Preparando funciones...","Configurando herramientas de trabajo","initializing");await this.setupEventListeners();this.updateStatus("Configurando cámara...","Detectando dispositivos disponibles","initializing");await this.initializeComponent();if(this.debug){this.initializePerformanceMonitor()}}async initializeServices(){const t={debug:this.debug,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,cropMargin:this.cropMargin,useDocumentClassification:this.useDocumentClassification,useDocumentDetector:this.useDocumentDetector,preferredCamera:this.preferredCamera,captureDelay:this.captureDelay};this.serviceContainer=new h(t);this.eventBus=this.serviceContainer.getEventBus();this.stateManager=this.serviceContainer.getStateManager();this.cameraService=this.serviceContainer.getCameraService();this.detectionService=this.serviceContainer.getDetectionService()}async setupEventListeners(){this.eventBus.on("state-changed",(t=>{this.handleStateChange(t)}));this.eventBus.on("camera-changed",(()=>{}));this.eventBus.on("error",(()=>{}))}async initializeComponent(){this.validateProps();if(this.debug){this.stateManager.updateCaptureState({isLoading:true});await new Promise((t=>setTimeout(t,500)))}this.updateStatus("Detectando cámaras...","Buscando dispositivos de captura","initializing");await this.cameraService.detectDeviceType();await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","initializing");await this.loadOnnxRuntime();this.initializeResizeObserver()}validateProps(){if(this.maskSize<50||this.maskSize>100){this.maskSize=90}if(this.cropMargin<0||this.cropMargin>100){this.cropMargin=0}const t=["auto","front","back"];if(!t.includes(this.preferredCamera)){this.preferredCamera="auto"}if(this.captureDelay<0||this.captureDelay>1e4){this.captureDelay=1500}}async loadOnnxRuntime(){if(!window.ort){this.updateStatus("Preparando herramientas...","Configurando funciones de captura","initializing");const t=document.createElement("script");t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js";document.head.appendChild(t);await new Promise((e=>{t.onload=()=>{setTimeout((async()=>{await this.finalizeInitialization();e(undefined)}),300)}}))}else{setTimeout((async()=>{await this.finalizeInitialization()}),300)}}async finalizeInitialization(){this.stateManager.updateCaptureState({isLoading:false});const t=await this.checkCameraPermissions();if(t){this.currentStatus={message:"Listo para capturar",description:"",type:"ready",isInitialized:true}}else{this.currentStatus={message:"Permisos de cámara requeridos",description:"Por favor, otorgue permisos de cámara para continuar",type:"error",isInitialized:true}}this.emitReadyEvent()}updateStatus(t,e,i="loading"){this.currentStatus={message:t,description:e,type:i,isInitialized:this.currentStatus.isInitialized}}emitReadyEvent(){const t=!!window.ort&&this.detectionService.isModelLoaded();this.isReady.emit(t)}async checkCameraPermissions(){try{if(!navigator.permissions){try{const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()));return true}catch{return false}}const t=await navigator.permissions.query({name:"camera"});return t.state==="granted"}catch(t){return false}}handleStateChange(t){}initializeResizeObserver(){if("ResizeObserver"in window&&this.detectionContainer){const t=new ResizeObserver((()=>{this.handleResize()}));t.observe(this.detectionContainer.parentElement)}}handleResize(){if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}}getGuideText(t){if(t==="completed"){return"Proceso completado"}if(t==="front"){if(this.showManualCaptureButton){return"Posicione el frente de su documento en el marco y presione el botón para capturar"}return"Alinee su identificación con el marco"}else if(t==="back"){if(this.useDocumentDetector){return"Si tu documento no tiene lado trasero, da clic en el botón para continuar con el proceso"}else{return"Posicione el reverso de su documento en el marco y capture, o salte este paso"}}return"Alinee su identificación con el marco"}updateMaskDimensions(t){if(!this.videoRef)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;if(e===0||i===0)return;const s=e/i;const a=t.width/t.height;let o,r;let n=0,c=0;if(s>a){o=t.width;r=t.width/s;c=(t.height-r)/2}else{r=t.height;o=t.height*s;n=(t.width-o)/2}const d=85.6/53.98;const l=r*d;let h,f;const p=this.maskSize/100;if(l<=o){f=r*p;h=f*d}else{h=o*p;f=h/d}const u=h/t.width*100;const m=f/t.height*100;const b=n+o/2;const g=c+r/2;const x=b/t.width*100;const y=g/t.height*100;this.el.style.setProperty("--mask-width",`${u}%`);this.el.style.setProperty("--mask-height",`${m}%`);this.el.style.setProperty("--mask-center-x",`${x}%`);this.el.style.setProperty("--mask-center-y",`${y}%`);this.isMaskReady=true}isComponentReady(){if(!this.currentStatus.isInitialized){return{ready:false,message:"El componente aún se está inicializando",status:"initializing"}}if(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing"){return{ready:false,message:"El componente está cargando recursos",status:"loading"}}if(!this.serviceContainer||!this.stateManager||!this.cameraService||!this.detectionService){return{ready:false,message:"Los servicios del componente no están disponibles",status:"error"}}return{ready:true}}async getCapturedImages(){const t=this.isComponentReady();if(!t.ready){throw new Error(t.message)}const e=this.stateManager.getCaptureState();if(e.step!=="completed"){throw new Error("El proceso de captura no ha sido completado")}return this.stateManager.getCapturedImages()}async isProcessCompleted(){const t=this.isComponentReady();if(!t.ready){return false}return this.stateManager.isProcessCompleted()}async startCapture(){const t=this.isComponentReady();if(!t.ready){this.updateStatus(t.message,"Espere a que termine la inicialización",t.status);return{success:false,error:t.message}}try{await this.startDetection();return{success:true}}catch(t){this.updateStatus("Error al iniciar captura",t.message,"error");return{success:false,error:t.message}}}async stopCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.exitSession();return{success:true}}catch(t){return{success:false,error:t.message}}}async resetCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.resetDetection();return{success:true}}catch(t){return{success:false,error:t.message}}}async skipBackCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();if(t.step==="back"&&e.front.fullFrame){this.completeProcess(true);return{success:true}}else{return{success:false,error:"No se puede saltar el reverso en el estado actual"}}}catch(t){return{success:false,error:t.message}}}async getStatus(){const t=this.isComponentReady();if(!t.ready){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:t.status,componentMessage:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();return{isVideoActive:t.isVideoActive,captureStep:t.step,hasImages:!!(e.front.fullFrame||e.back.fullFrame),isProcessCompleted:this.stateManager.isProcessCompleted(),isModelPreloaded:this.detectionService.isModelLoaded(),componentStatus:"ready"}}catch(t){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:"error",componentMessage:t.message}}}async preloadModel(){const t=this.isComponentReady();if(!t.ready){this.updateStatus(t.message,"Espere a que termine la inicialización",t.status);return{success:false,error:t.message}}if(this.detectionService.isModelLoaded()){this.updateStatus("Reconocimiento listo","","ready");return{success:true,message:"Model already loaded"}}try{const t=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:true})}await this.detectionService.loadModel();this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");await this.detectionService.loadClassificationModel();const e=performance.now();const i=e-t;if(this.debug){this.recordOnnxPerformance(i,0)}this.updateStatus("Finalizando configuración...","Preparando herramientas para captura","loading");await new Promise((t=>setTimeout(t,300)));this.updateStatus("Reconocimiento preparado","","ready");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}this.emitReadyEvent();return{success:true,message:"Models preloaded successfully"}}catch(t){this.updateStatus("Error de configuración","No se pudieron preparar las herramientas necesarias","error");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}return{success:false,error:t.message}}}async getCameraInfo(){const t=this.isComponentReady();if(!t.ready){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}try{return await this.cameraService.getCameraInfo()}catch(t){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}}async setPreferredCamera(t){const e=this.isComponentReady();if(!e.ready){return{success:false,error:e.message,selectedCamera:null,availableCameras:0}}try{this.preferredCamera=t;this.serviceContainer.updateConfig({preferredCamera:t});await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();const e=this.stateManager.getCaptureState();if(e.isVideoActive){const t=this.cameraService.getSelectedCameraId();if(t){await this.cameraService.switchCamera(t)}}return{success:true,selectedCamera:this.cameraService.getSelectedCameraId(),availableCameras:this.cameraService.getAvailableCameras().length}}catch(t){return{success:false,error:t.message,selectedCamera:null,availableCameras:0}}}async setCaptureDelay(t){if(t<0||t>1e4){return{success:false,error:"Capture delay must be between 0 and 10000 milliseconds",captureDelay:this.captureDelay}}this.captureDelay=t;if(this.serviceContainer){this.serviceContainer.updateConfig({captureDelay:t})}return{success:true,captureDelay:this.captureDelay}}async getCaptureDelay(){return this.captureDelay}async startDetection(){try{if(!this.detectionService.isModelLoaded()){const t=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});await this.detectionService.loadModel();this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");await this.detectionService.loadClassificationModel();const e=performance.now();const i=e-t;if(this.debug){this.recordOnnxPerformance(i,0)}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");const t=await this.cameraService.setupCamera();if(this.useDocumentDetector){this.updateStatus("Captura activa","Buscando documento en el marco de captura","active")}else{this.updateStatus("Captura activa","Posicione su documento y use el botón para capturar","active")}await this.initializeVideoStream(t);if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});if(!this.useDocumentDetector){this.showManualCaptureButton=true}this.detectFrame()}catch(t){this.updateStatus("Error al iniciar","No se pudo preparar la captura","error");this.stateManager.updateCaptureState({isLoading:false})}}async initializeVideoStream(t){if(this.videoRef){this.videoRef.srcObject=t;this.videoStream=t;const e=this.cameraService.isRearCamera(t);this.shouldMirrorVideo=!e;return new Promise((t=>{this.videoRef.onloadedmetadata=async()=>{await this.videoRef.play();this.stateManager.updateCaptureState({isVideoActive:true});t()}}))}else{throw new Error("Video element not available")}}async detectFrame(){try{const t=performance.now();const e=this.stateManager.getCaptureState();if(!this.videoRef||!this.detectionContainer||!this.detectionService.isModelLoaded())return;if(!this.useDocumentDetector){this.showManualCaptureButton=true;if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}else{this.showManualCaptureButton=false}if(e.isDetectionPaused){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter++;const i=this.getAdaptiveFrameSkip();if(this.frameSkipCounter<=i){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter=0;const s=Date.now();if(s-this.lastInferenceTime<this.MIN_INFERENCE_INTERVAL){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.lastInferenceTime=s;const a=performance.now();const o=this.detectionService.preprocess(this.videoRef);const r=await this.detectionService.runInference(o);const n=performance.now()-a;if(this.debug){this.recordOnnxPerformance(0,n)}if(this.startTime&&Date.now()-this.startTime<5e3){r.forEach((t=>{const i=this.detectionService.isCardInFrame(t);const s=i?t.score*1.2:t.score;if(s>e.bestScore){this.stateManager.updateCaptureState({bestScore:s})}}))}const c=this.hasDocumentDetected;this.hasDocumentDetected=r.length>0;if(!c&&this.hasDocumentDetected&&e.step==="back"&&this.enableBackDocumentTimer){this.startBackDocumentTimer()}if(r.length===0){this.consecutiveFailures++}else{this.consecutiveFailures=0}if(this.debug){this.updateDetectionBoxes(r)}else{this.detectionBoxes=[]}this.updateMaskColor(r);if(this.debug){const e=performance.now();const i=e-t;this.recordFrameProcessing(i,r.length)}if(e.step!=="completed"){if(this.consecutiveFailures>this.MAX_FAILURES){setTimeout((()=>this.detectFrame()),200)}else{this.animationId=requestAnimationFrame((()=>this.detectFrame()))}}}catch(t){const e=this.stateManager.getCaptureState();if(e.step!=="completed"){setTimeout((()=>this.detectFrame()),100)}}}disconnectedCallback(){this.cleanup()}cleanup(){if(this.animationId){cancelAnimationFrame(this.animationId)}if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(this.performanceUpdateInterval){clearInterval(this.performanceUpdateInterval);this.performanceUpdateInterval=undefined}this.canvasPool=[];this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.serviceContainer?.cleanup()}render(){const t=this.stateManager?.getCaptureState()||{isVideoActive:false,showFlipAnimation:false,showSuccessAnimation:false,step:"front",isCapturing:false};const e=this.cameraInfoWithAutofocus;return s("div",{key:"e0b32b1b41b58e3a58b552199384080e8f2c069b",class:"detector-container"},s("div",{key:"03c77af311ff12d936994d629d58550cbaae190c",class:"video-container"},s("video",{key:"94f15b34f34367a10d17816a31cd147adb57bc90",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{display:t.isVideoActive?"block":"none"}}),s("div",{key:"982be192792dfaf644eb173bfee9b26ebd229288",ref:t=>this.detectionContainer=t,class:`detection-overlay ${this.shouldMirrorVideo?"mirror":""}`},this.debug&&this.detectionBoxes.map(((t,e)=>s("div",{key:e,class:"detection-box",style:{position:"absolute",left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,border:"2px solid #32406C",pointerEvents:"none",boxSizing:"border-box"}})))),this.isMaskReady&&s("div",{key:"f5212ff70db65d2b836a3ac456a1701701630660",class:"overlay-mask"},s("div",{key:"5080217f4962c2c7152def39cc978ba1c40a3a1c",class:"card-outline"},s("div",{key:"d37f1ca8723d79b10d1c6a3afaf54e2f2657ae79",class:"side side-top"}),s("div",{key:"c5bb4f7d646a991f43598688ffa909c04697bb06",class:"side side-right"}),s("div",{key:"4a5040b4a236367dcdf72f4e72d497b8b6dee6c0",class:"side side-bottom"}),s("div",{key:"c74ecef56eee8e92cd9491d693fa89a6c01bdbbd",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&s("div",{key:"2a2932b0c03835193ebf86ddb5f13173b1dba367",class:"guide-text"},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&s("div",{key:"41fcf2d79106d3ed928fc2842cb6a6725ba4d4f6",class:"back-capture-section"},s("div",{key:"98dbe1bbe454bad42c3e155247f25a9151aaf1f9",class:"back-capture-buttons"},!this.useDocumentDetector&&s("button",{key:"01693bc0d6915a4d02f318268020dfbcf3a70b94",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:t.isCapturing},t.isCapturing?"Capturando...":"Capturar Reverso"),s("button",{key:"0a4ba55cbbea867b936a83a16a622a3c36a225f9",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button"},this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&s("div",{key:"1db208a53dea37211bdd88254e575142b7abf91f",class:"camera-controls"},s("button",{key:"90755839358f997c3ce2f4c36a8d17d39ea5f8ad",class:`camera-selector-button ${this.isSwitchingCamera?"loading":""}`,onClick:()=>this.toggleCameraSelector(),type:"button",title:"Seleccionar cámara",disabled:this.isSwitchingCamera},this.isSwitchingCamera?s("div",{class:"button-spinner"}):"Cámaras")),this.showCameraSelector&&e.availableCameras.length>0&&s("div",{key:"ef7889ab82f9eaabcabec3e3dc3ebb7850818dd4",class:"camera-selector-dropdown"},s("div",{key:"e28fb005316a742318be3cf8582f520392b71bba",class:"camera-selector-header"},s("span",{key:"97338030b1aedb50c5f5a588ea03c0f19bcb0ddd"},"Seleccionar Cámara"),s("button",{key:"1537c907dfab17c232a256f9fc9210cbd0125cc6",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),s("div",{key:"509178119e6eed5fe0a6ea287904a53bd9fbecbc",class:"camera-list"},e.availableCameras.map((t=>s("button",{key:t.id,class:`camera-option ${e.selectedCameraId===t.id?"selected":""}`,onClick:()=>this.handleCameraSwitch(t.id),type:"button"},s("span",{class:"camera-label"},t.label||`Cámara ${e.availableCameras.indexOf(t)+1}`,t.hasAutofocus&&s("span",{class:"autofocus-icon",title:"Autofoco disponible"},"⦿")),e.selectedCameraId===t.id&&s("span",{class:"selected-indicator"},"✓"))))),s("div",{key:"485f7e1a97c43ed280a106bde3c6ee910625025c",class:"device-info"},s("small",{key:"d76edba943f4e06c14024923496555fa1fe6d845"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&s("div",{key:"c5184dd93aa41cff61b88ea2046b481efc87c1f2",class:"manual-capture-section"},s("button",{key:"6e45d9a0fec60469eb926ff353cb1a440d59f5fe",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:t.isCapturing},t.isCapturing?"Capturando...":"Capturar Frente"))),t.isCapturing&&s("div",{key:"9e296a942ba51cc1fd152e76ae406620c84ed721",class:"capture-animation"}),t.showFlipAnimation&&s("div",{key:"517db50f7273788d94d5e6db6c40f65e00e18784",class:"flip-animation"},s("div",{key:"fbf6a26c4cc0539bd16b45899d19984af3449610",class:"id-card-icon"}),s("div",{key:"fb3a201864d04531a078074458aa6e7f6580d565",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&s("div",{key:"10c694e233d26523d538ff0d2edbf6dcfb8e37c8",class:"success-animation"},s("div",{key:"87e545650825ab805e887667281ecdf8bdb34c45",class:"check-icon"}),s("div",{key:"359da71f391d68e9437b749b949ee90685b96b3f",class:"success-text"},"¡Proceso completado!")),s("div",{key:"7c5533bb875eb3d9cdcc6cfdfc20e4d5bd98d103",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&s("div",{key:"f32df46ab83279387de606eadf53cd4a4009f449",class:"status-spinner"}),s("div",{key:"dd640de5a3b64f5f99363318e2fc70e32ccbc7db",class:"status-content"},s("div",{key:"618c0ab9cb0a24b0af3f6946052beab0d660fe6d",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&s("div",{key:"e52c2a4945c7f5a190a446ac588aa1668c21f26d",class:"status-description"},this.currentStatus.description))),this.debug&&s("div",{key:"61cea10bc3438fb74aa176d71c4238b070cb0f09",class:"performance-monitor"},s("div",{key:"44f6b1accb56d99a236b22c0769f870638d9c768",class:"performance-expanded"},s("div",{key:"6febc85e319752b0aebc0a4e4050ea6d597375a7",class:"metrics-row"},s("div",{key:"96b81895ad3cd742c96308ed53a2126af76eb619",class:"metric-compact"},s("span",{key:"774a11c6fed6a87db7673b018b3cdc378c5252ef",class:"metric-label"},"FPS"),s("span",{key:"cb866dcbea661e5f715b82c4dd760f786fd5bb2a",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),s("div",{key:"a935aaadb83ea400bfaa984d1d845bdfd87becc8",class:"metric-compact"},s("span",{key:"ffacaa2cb7838403a297145b70586e255cc845c7",class:"metric-label"},"MEM"),s("span",{key:"a1d7a7abec97dc0544d50b11b372f699f750b76f",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),s("div",{key:"bb3d156a46569a8c290bc518c42ec7957bc5b94e",class:"metrics-row"},s("div",{key:"4cadd8f845e4c12120ed549e4a73e02c6cbd9257",class:"metric-compact"},s("span",{key:"1fc5661222f495b79fd7eb126e04f52eecab6fb3",class:"metric-label"},"INF"),s("span",{key:"eca1f59d1c41ab99158eec81592bc7150bfeabe1",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),s("div",{key:"f708e2757adcb03e633111d96bd6786fb6b80ea6",class:"metric-compact"},s("span",{key:"a13099ded64180996d6f65bf215483ba83daccbc",class:"metric-label"},"FRAME"),s("span",{key:"2765cd1f7c1a49df9de64639cc1b777c79f89f4c",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),s("div",{key:"13aaf85a1b4b66294c4204f02d956b64665aa766",class:"metrics-row"},s("div",{key:"40012f3f646d70c535a606ebbe581a2fe6fd2e50",class:"metric-compact"},s("span",{key:"03f8b17746fe404485820d06a50173678db2fd25",class:"metric-label"},"DET"),s("span",{key:"c4f87430f142355054d9361330d6a5d508974b70",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),s("div",{key:"cf366a41d7f7cda6046c32cc7c514eb7b46b05d1",class:"metric-compact"},s("span",{key:"925e7de15b96ba4dbbcdbf8a9f0e3173bae49573",class:"metric-label"},"RATE"),s("span",{key:"9701e60c7793f2c205f3c9ffd254b6a115b8a68c",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),s("div",{key:"636aeb9b2b8dd992d8a28a8db44b213e12514096",class:"watermark"},s("img",{key:"0407b550d962a6113e05ad75e25a1a1bbd76d9ce",src:"https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png",alt:"Powered by Jaak"}))))}updateDetectionBoxes(t){if(!this.videoRef||!this.detectionContainer)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;const s=this.detectionContainer.parentElement;const a=s.getBoundingClientRect();const o=a.width;const r=a.height;if(e===0||i===0)return;const n=e/i;const c=o/r;let d,l;let h=0,f=0;if(n>c){d=o;l=o/n;f=(r-l)/2}else{l=r;d=r*n;h=(o-d)/2}const p=320;const u=d/p;const m=l/p;this.detectionBoxes=t.map((t=>({x:t.x*u+h,y:t.y*m+f,w:t.w*u,h:t.h*m,score:t.score})))}updateMaskColor(t){const e=this.el.shadowRoot?.querySelector(".card-outline");const i=this.el.shadowRoot?.querySelectorAll(".corner");const s=this.el.shadowRoot?.querySelector(".side-top");const a=this.el.shadowRoot?.querySelector(".side-right");const o=this.el.shadowRoot?.querySelector(".side-bottom");const r=this.el.shadowRoot?.querySelector(".side-left");let n=null;let c={top:false,right:false,bottom:false,left:false};if(t.length>0){n=t.reduce(((t,e)=>e.score>t.score?e:t));const e={INPUT_SIZE:320,ID1_ASPECT_RATIO:85.6/53.98,shouldMirrorVideo:this.shouldMirrorVideo,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,videoRef:this.videoRef};c=this.detectionService.checkSideAlignment(n,e);this.sideAlignment=c}else{this.sideAlignment={top:false,right:false,bottom:false,left:false}}s?.classList.toggle("aligned",c.top);a?.classList.toggle("aligned",c.right);o?.classList.toggle("aligned",c.bottom);r?.classList.toggle("aligned",c.left);const d=this.detectionService.areAllSidesAligned(c);const l=this.stateManager.getCaptureState();if(l.step==="back"&&this.enableBackDocumentTimer&&n){const t=c.top||c.right||c.bottom||c.left;if(t){this.startBackDocumentTimer()}}if(d&&n){e?.classList.add("perfect-match");i?.forEach((t=>t.classList.add("perfect-match")));if(!this.hasScreenshotTaken){const t=Date.now();if(!this.alignmentStartTime){this.alignmentStartTime=t}const e=t-this.alignmentStartTime;if(e>=this.captureDelay){this.lastDetectedBox=n;this.takeScreenshot().catch((()=>{}));this.hasScreenshotTaken=true;this.alignmentStartTime=undefined;setTimeout((()=>{this.hasScreenshotTaken=false}),2e3)}}}else{e?.classList.remove("perfect-match");i?.forEach((t=>t.classList.remove("perfect-match")));if(this.alignmentStartTime){this.alignmentStartTime=undefined}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}}}async takeManualScreenshot(){if(!this.videoRef)return;await this.takeScreenshotWithMaskCoordinates()}async takeScreenshotWithMaskCoordinates(){if(!this.videoRef||!this.detectionContainer)return;this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const t=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const e=t.getContext("2d",{alpha:false});e.clearRect(0,0,t.width,t.height);e.drawImage(this.videoRef,0,0,t.width,t.height);const i=this.detectionContainer.parentElement;const s=i.getBoundingClientRect();const a=parseFloat(this.el.style.getPropertyValue("--mask-width").replace("%",""))||90;const o=parseFloat(this.el.style.getPropertyValue("--mask-height").replace("%",""))||56.25;const r=parseFloat(this.el.style.getPropertyValue("--mask-center-x").replace("%",""))||50;const n=parseFloat(this.el.style.getPropertyValue("--mask-center-y").replace("%",""))||50;const c=this.videoRef.videoWidth;const d=this.videoRef.videoHeight;const l=c/d;const h=s.width/s.height;let f,p;let u=0,m=0;if(l>h){f=s.width;p=s.width/l;m=(s.height-p)/2}else{p=s.height;f=s.height*l;u=(s.width-f)/2}const b=a/100*s.width;const g=o/100*s.height;const x=r/100*s.width;const y=n/100*s.height;const w=c/f;const v=d/p;const k=(x-u)*w;const C=(y-m)*v;const S=b*w;const M=g*v;const z=Math.max(0,k-S/2-this.cropMargin);const P=Math.max(0,C-M/2-this.cropMargin);const A=Math.min(S+2*this.cropMargin,c-z);const T=Math.min(M+2*this.cropMargin,d-P);const I=this.getPooledCanvas(A,T);const D=I.getContext("2d",{alpha:false});D.clearRect(0,0,I.width,I.height);D.drawImage(this.videoRef,z,P,A,T,0,0,A,T);const F=this.stateManager.getCaptureState();if(F.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/png"),cropped:I.toDataURL("image/png")}});if(this.useDocumentClassification){const e=await this.detectionService.classifyDocument(I);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(I);return}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.startBackDocumentTimer()}),3e3)}else if(F.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/png"),cropped:I.toDataURL("image/png")}});this.completeProcess(false)}this.returnCanvasToPool(t);this.returnCanvasToPool(I)}async takeScreenshot(){if(!this.videoRef||!this.lastDetectedBox)return;this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const t=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const e=t.getContext("2d",{alpha:false});e.clearRect(0,0,t.width,t.height);e.drawImage(this.videoRef,0,0,t.width,t.height);const i=320;const s=this.videoRef.videoWidth/i;const a=this.videoRef.videoHeight/i;const o=Math.max(0,this.lastDetectedBox.x*s-this.cropMargin);const r=Math.max(0,this.lastDetectedBox.y*a-this.cropMargin);const n=Math.min(this.lastDetectedBox.w*s+2*this.cropMargin,this.videoRef.videoWidth-o);const c=Math.min(this.lastDetectedBox.h*a+2*this.cropMargin,this.videoRef.videoHeight-r);const d=this.getPooledCanvas(n,c);const l=d.getContext("2d",{alpha:false});l.clearRect(0,0,d.width,d.height);l.drawImage(this.videoRef,o,r,n,c,0,0,n,c);const h=this.stateManager.getCaptureState();if(h.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/png"),cropped:d.toDataURL("image/png")}});if(this.useDocumentClassification){const t=await this.detectionService.classifyDocument(d);if(t&&t.class==="passport"){this.completeProcess(true);return}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.startBackDocumentTimer()}),3e3)}else if(h.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/png"),cropped:d.toDataURL("image/png")}});this.completeProcess(false)}this.returnCanvasToPool(t);this.returnCanvasToPool(d)}triggerCaptureAnimation(){const t=this.el.shadowRoot?.querySelector(".card-outline");t?.classList.add("capturing");setTimeout((()=>{this.stateManager.updateCaptureState({isCapturing:false});t?.classList.remove("capturing")}),600)}completeProcess(t=false){this.stateManager.updateCaptureState({step:"completed",showSuccessAnimation:true});const e=this.stateManager.getCapturedImages();e.metadata.processCompleted=true;e.metadata.backCaptureSkipped=t;this.stateManager.setCapturedImages(e);this.stopDetection();this.updateStatus("Proceso completado",`Imágenes capturadas exitosamente`,"ready");const i={...e,timestamp:(new Date).toISOString()};this.captureCompleted.emit(i);setTimeout((()=>{this.stateManager.updateCaptureState({showSuccessAnimation:false})}),3e3)}stopDetection(){if(this.animationId){cancelAnimationFrame(this.animationId);this.animationId=undefined}this.clearBackDocumentTimer();this.detectionBoxes=[]}startBackDocumentTimer(){if(!this.enableBackDocumentTimer)return;if(this.backDocumentTimer){clearInterval(this.backDocumentTimer)}this.backDocumentTimerRemaining=this.backDocumentTimerDuration;this.backDocumentTimer=window.setInterval((()=>{this.backDocumentTimerRemaining--;if(this.backDocumentTimerRemaining<=0){this.clearBackDocumentTimer();this.skipBackCapture()}}),1e3)}clearBackDocumentTimer(){if(this.backDocumentTimer){clearInterval(this.backDocumentTimer);this.backDocumentTimer=undefined}this.backDocumentTimerRemaining=0}toggleCameraSelector(){if(this.isSwitchingCamera)return;this.showCameraSelector=!this.showCameraSelector}async updateCameraInfoWithAutofocus(){try{const t=await this.cameraService.getCameraInfo();this.cameraInfoWithAutofocus=t}catch(t){}}async handleCameraSwitch(t){if(this.isSwitchingCamera)return;try{this.showCameraSelector=false;this.isSwitchingCamera=true;if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}await this.cameraService.switchCamera(t);const e=await this.cameraService.setupCamera();await this.initializeVideoStream(e);await this.updateCameraInfoWithAutofocus()}catch(t){try{const t=await this.cameraService.setupCamera();await this.initializeVideoStream(t)}catch(t){this.updateStatus("Error al cambiar cámara","No se pudo cambiar el dispositivo","error")}}finally{this.isSwitchingCamera=false}}resetDetection(){const t=this.stateManager.getCaptureState();const e=t.isVideoActive;this.stateManager.reset();if(e){this.stateManager.updateCaptureState({isVideoActive:true})}this.hasScreenshotTaken=false;this.startTime=Date.now();this.frameSkipCounter=0;this.consecutiveFailures=0;this.lastInferenceTime=0;this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(e&&this.detectionService.isModelLoaded()){this.updateStatus("Captura reiniciada","Buscando documento en el marco de captura","active");this.detectFrame()}else{this.updateStatus("Listo para capturar","","ready")}}exitSession(){if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()));this.videoStream=undefined;this.stateManager.updateCaptureState({isVideoActive:false,isLoading:false})}this.isMaskReady=false;this.updateStatus("Captura finalizada","","ready");this.detectionBoxes=[];this.cleanup()}initializePerformanceMonitor(){this.performanceMetrics.lastUpdateTime=performance.now();this.performanceUpdateInterval=window.setInterval((()=>{this.updatePerformanceMetrics()}),500)}updatePerformanceMetrics(){const t=performance.now();const e=t-this.performanceMetrics.lastUpdateTime;if(e>0){this.performanceMetrics.fps=Math.round(1e3/(e/this.frameSkipCounter||1))}if("memory"in performance){const t=performance.memory;this.performanceMetrics.memoryUsage=Math.round(t.usedJSHeapSize/1048576)}if(this.performanceMetrics.totalDetections>0){this.performanceMetrics.successfulDetections=this.performanceMetrics.successfulDetections;const t=this.performanceMetrics.successfulDetections/this.performanceMetrics.totalDetections*100;this.performanceMetrics.detectionRate=Math.round(t)}this.performanceData={fps:this.performanceMetrics.fps,inferenceTime:this.performanceMetrics.inferenceTime,memoryUsage:this.performanceMetrics.memoryUsage,onnxLoadTime:this.performanceMetrics.onnxLoadTime,frameProcessingTime:this.performanceMetrics.frameProcessingTime,totalDetections:this.performanceMetrics.totalDetections,successfulDetections:this.performanceMetrics.successfulDetections,detectionRate:this.performanceMetrics.detectionRate};this.performanceMetrics.lastUpdateTime=t}recordOnnxPerformance(t,e){this.performanceMetrics.onnxLoadTime=Math.round(t);this.performanceMetrics.inferenceTime=Math.round(e)}recordFrameProcessing(t,e){this.performanceMetrics.frameProcessingTime=Math.round(t);this.performanceMetrics.totalDetections++;if(e>0){this.performanceMetrics.successfulDetections++}this.performanceHistory.push(t);if(this.performanceHistory.length>this.PERFORMANCE_HISTORY_SIZE){this.performanceHistory.shift()}}getAdaptiveFrameSkip(){if(this.consecutiveFailures>20)return this.MAX_FRAME_SKIP;if(this.performanceMetrics.inferenceTime>200)return 6;if(this.performanceMetrics.memoryUsage>200)return 5;if(this.performanceHistory.length>0){const t=this.performanceHistory.reduce(((t,e)=>t+e),0)/this.performanceHistory.length;if(t>100)return 4;if(t>80)return 3;if(t>60)return this.BASE_FRAME_SKIP+1}if(this.performanceMetrics.memoryUsage>150)return 4;return this.BASE_FRAME_SKIP}getPooledCanvas(t,e){const i=this.canvasPool.findIndex((i=>i.width===t&&i.height===e));if(i!==-1){return this.canvasPool.splice(i,1)[0]}if(this.canvasPool.length>0){const i=this.canvasPool.pop();i.width=t;i.height=e;return i}const s=document.createElement("canvas");s.width=t;s.height=e;return s}returnCanvasToPool(t){if(this.canvasPool.length<this.MAX_CANVAS_POOL_SIZE){const e=t.getContext("2d");e.clearRect(0,0,t.width,t.height);this.canvasPool.push(t)}}};p.style=f;export{p as jaak_stamps};
|
|
2
|
+
//# sourceMappingURL=p-41e88688.entry.js.map
|