@jaak.ai/stamps 1.0.0-dev.9 → 2.0.0-beta.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.
Files changed (162) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +470 -390
  3. package/dist/cjs/index-DGM9-FNg.js +1402 -0
  4. package/dist/cjs/index-DGM9-FNg.js.map +1 -0
  5. package/dist/cjs/index.cjs.js +3 -0
  6. package/dist/cjs/index.cjs.js.map +1 -0
  7. package/dist/cjs/jaak-stamps-webcomponent.cjs.js +27 -0
  8. package/dist/cjs/jaak-stamps-webcomponent.cjs.js.map +1 -0
  9. package/dist/cjs/jaak-stamps.cjs.entry.js +925 -0
  10. package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -0
  11. package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -0
  12. package/dist/cjs/loader.cjs.js +8 -15
  13. package/dist/cjs/loader.cjs.js.map +1 -0
  14. package/dist/collection/collection-manifest.json +3 -22
  15. package/dist/collection/components/my-component/my-component.css +530 -0
  16. package/dist/collection/components/my-component/my-component.js +1162 -0
  17. package/dist/collection/components/my-component/my-component.js.map +1 -0
  18. package/dist/collection/index.js +2 -1
  19. package/dist/collection/index.js.map +1 -0
  20. package/dist/collection/utils/utils.js +4 -0
  21. package/dist/collection/utils/utils.js.map +1 -0
  22. package/dist/components/index.d.ts +33 -0
  23. package/dist/components/index.js +1195 -0
  24. package/dist/components/index.js.map +1 -0
  25. package/dist/components/jaak-stamps.d.ts +11 -0
  26. package/dist/components/jaak-stamps.js +971 -0
  27. package/dist/components/jaak-stamps.js.map +1 -0
  28. package/dist/esm/index-DqoVMnc7.js +1393 -0
  29. package/dist/esm/index-DqoVMnc7.js.map +1 -0
  30. package/dist/esm/index.js +3 -0
  31. package/dist/esm/index.js.map +1 -0
  32. package/dist/esm/jaak-stamps-webcomponent.js +23 -0
  33. package/dist/esm/jaak-stamps-webcomponent.js.map +1 -0
  34. package/dist/esm/jaak-stamps.entry.js +923 -0
  35. package/dist/esm/jaak-stamps.entry.js.map +1 -0
  36. package/dist/esm/loader.js +9 -14
  37. package/dist/esm/loader.js.map +1 -0
  38. package/dist/jaak-stamps-webcomponent/index.esm.js +2 -0
  39. package/dist/jaak-stamps-webcomponent/index.esm.js.map +1 -0
  40. package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +2 -0
  41. package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js.map +1 -0
  42. package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -0
  43. package/dist/jaak-stamps-webcomponent/loader.esm.js.map +1 -0
  44. package/dist/jaak-stamps-webcomponent/p-DqoVMnc7.js +3 -0
  45. package/dist/jaak-stamps-webcomponent/p-DqoVMnc7.js.map +1 -0
  46. package/dist/jaak-stamps-webcomponent/p-dd6cc14e.entry.js +2 -0
  47. package/dist/jaak-stamps-webcomponent/p-dd6cc14e.entry.js.map +1 -0
  48. package/dist/types/components/my-component/my-component.d.ts +119 -0
  49. package/dist/types/components.d.ts +50 -1353
  50. package/dist/types/index.d.ts +10 -1
  51. package/dist/types/stencil-public-runtime.d.ts +93 -28
  52. package/dist/types/utils/utils.d.ts +1 -0
  53. package/loader/cdn.js +1 -3
  54. package/loader/index.cjs.js +1 -3
  55. package/loader/index.d.ts +5 -2
  56. package/loader/index.es2017.js +1 -3
  57. package/loader/index.js +1 -3
  58. package/package.json +22 -26
  59. package/dist/cjs/document-detector_19.cjs.entry.js +0 -8540
  60. package/dist/cjs/index-5e4e5e7d.js +0 -1685
  61. package/dist/cjs/mb-tooltip.cjs.entry.js +0 -26
  62. package/dist/cjs/stamps.cjs.js +0 -23
  63. package/dist/collection/components/document-detector/document-detector.css +0 -156
  64. package/dist/collection/components/document-detector/document-detector.js +0 -416
  65. package/dist/collection/components/shared/mb-api-process-status/mb-api-process-status.css +0 -360
  66. package/dist/collection/components/shared/mb-api-process-status/mb-api-process-status.js +0 -124
  67. package/dist/collection/components/shared/mb-button/mb-button.css +0 -95
  68. package/dist/collection/components/shared/mb-button/mb-button.js +0 -201
  69. package/dist/collection/components/shared/mb-button-classic/mb-button-classic.css +0 -100
  70. package/dist/collection/components/shared/mb-button-classic/mb-button-classic.js +0 -130
  71. package/dist/collection/components/shared/mb-camera-experience/mb-camera-experience.css +0 -740
  72. package/dist/collection/components/shared/mb-camera-experience/mb-camera-experience.js +0 -827
  73. package/dist/collection/components/shared/mb-camera-experience/mb-camera-experience.utils.js +0 -55
  74. package/dist/collection/components/shared/mb-camera-selection/mb-camera-selection.css +0 -124
  75. package/dist/collection/components/shared/mb-camera-selection/mb-camera-selection.js +0 -194
  76. package/dist/collection/components/shared/mb-camera-toolbar/mb-camera-toolbar.css +0 -80
  77. package/dist/collection/components/shared/mb-camera-toolbar/mb-camera-toolbar.js +0 -275
  78. package/dist/collection/components/shared/mb-completed/mb-completed.css +0 -17
  79. package/dist/collection/components/shared/mb-completed/mb-completed.js +0 -48
  80. package/dist/collection/components/shared/mb-component/mb-component.css +0 -321
  81. package/dist/collection/components/shared/mb-component/mb-component.js +0 -2269
  82. package/dist/collection/components/shared/mb-component/mb-component.utils.js +0 -14
  83. package/dist/collection/components/shared/mb-container/mb-container.css +0 -7
  84. package/dist/collection/components/shared/mb-container/mb-container.js +0 -23
  85. package/dist/collection/components/shared/mb-feedback/mb-feedback.css +0 -36
  86. package/dist/collection/components/shared/mb-feedback/mb-feedback.js +0 -91
  87. package/dist/collection/components/shared/mb-feedback/mb-feedback.utils.js +0 -11
  88. package/dist/collection/components/shared/mb-help/mb-help.css +0 -191
  89. package/dist/collection/components/shared/mb-help/mb-help.js +0 -409
  90. package/dist/collection/components/shared/mb-help/mb-help.model.js +0 -5
  91. package/dist/collection/components/shared/mb-image-box/mb-image-box.css +0 -78
  92. package/dist/collection/components/shared/mb-image-box/mb-image-box.js +0 -150
  93. package/dist/collection/components/shared/mb-modal/mb-modal.css +0 -106
  94. package/dist/collection/components/shared/mb-modal/mb-modal.js +0 -239
  95. package/dist/collection/components/shared/mb-overlay/mb-overlay.css +0 -46
  96. package/dist/collection/components/shared/mb-overlay/mb-overlay.js +0 -76
  97. package/dist/collection/components/shared/mb-progress-tracker/mb-progress-tracker.css +0 -24
  98. package/dist/collection/components/shared/mb-progress-tracker/mb-progress-tracker.js +0 -80
  99. package/dist/collection/components/shared/mb-screen/mb-screen.css +0 -19
  100. package/dist/collection/components/shared/mb-screen/mb-screen.js +0 -48
  101. package/dist/collection/components/shared/mb-spinner/mb-spinner.css +0 -30
  102. package/dist/collection/components/shared/mb-spinner/mb-spinner.js +0 -67
  103. package/dist/collection/components/shared/mb-tooltip/mb-tooltip.css +0 -62
  104. package/dist/collection/components/shared/mb-tooltip/mb-tooltip.js +0 -150
  105. package/dist/collection/components/shared/mb-tooltip-advanced/mb-tooltip-advanced.css +0 -91
  106. package/dist/collection/components/shared/mb-tooltip-advanced/mb-tooltip-advanced.js +0 -96
  107. package/dist/collection/utils/data-structures.js +0 -189
  108. package/dist/collection/utils/device.helpers.js +0 -37
  109. package/dist/collection/utils/error-structures.js +0 -47
  110. package/dist/collection/utils/generic.helpers.js +0 -82
  111. package/dist/collection/utils/sdk.service.js +0 -943
  112. package/dist/collection/utils/state-lifter.js +0 -3
  113. package/dist/collection/utils/status.document-detector.js +0 -15
  114. package/dist/collection/utils/translation.service.js +0 -97
  115. package/dist/esm/document-detector_19.entry.js +0 -8518
  116. package/dist/esm/index-dc740acb.js +0 -1656
  117. package/dist/esm/mb-tooltip.entry.js +0 -22
  118. package/dist/esm/polyfills/core-js.js +0 -11
  119. package/dist/esm/polyfills/css-shim.js +0 -1
  120. package/dist/esm/polyfills/dom.js +0 -79
  121. package/dist/esm/polyfills/es5-html-element.js +0 -1
  122. package/dist/esm/polyfills/index.js +0 -34
  123. package/dist/esm/polyfills/system.js +0 -6
  124. package/dist/esm/stamps.js +0 -18
  125. package/dist/stamps/index.esm.js +0 -0
  126. package/dist/stamps/p-7f07a434.js +0 -2
  127. package/dist/stamps/p-ec3f5972.entry.js +0 -1
  128. package/dist/stamps/p-f4015454.entry.js +0 -9
  129. package/dist/stamps/stamps.esm.js +0 -1
  130. package/dist/types/components/document-detector/document-detector.d.ts +0 -86
  131. package/dist/types/components/shared/mb-api-process-status/mb-api-process-status.d.ts +0 -30
  132. package/dist/types/components/shared/mb-button/mb-button.d.ts +0 -41
  133. package/dist/types/components/shared/mb-button-classic/mb-button-classic.d.ts +0 -27
  134. package/dist/types/components/shared/mb-camera-experience/mb-camera-experience.d.ts +0 -141
  135. package/dist/types/components/shared/mb-camera-experience/mb-camera-experience.utils.d.ts +0 -3
  136. package/dist/types/components/shared/mb-camera-selection/mb-camera-selection.d.ts +0 -33
  137. package/dist/types/components/shared/mb-camera-toolbar/mb-camera-toolbar.d.ts +0 -54
  138. package/dist/types/components/shared/mb-completed/mb-completed.d.ts +0 -12
  139. package/dist/types/components/shared/mb-component/mb-component.d.ts +0 -308
  140. package/dist/types/components/shared/mb-component/mb-component.utils.d.ts +0 -3
  141. package/dist/types/components/shared/mb-container/mb-container.d.ts +0 -8
  142. package/dist/types/components/shared/mb-feedback/mb-feedback.d.ts +0 -19
  143. package/dist/types/components/shared/mb-feedback/mb-feedback.utils.d.ts +0 -2
  144. package/dist/types/components/shared/mb-help/mb-help.d.ts +0 -66
  145. package/dist/types/components/shared/mb-help/mb-help.model.d.ts +0 -9
  146. package/dist/types/components/shared/mb-image-box/mb-image-box.d.ts +0 -35
  147. package/dist/types/components/shared/mb-modal/mb-modal.d.ts +0 -53
  148. package/dist/types/components/shared/mb-overlay/mb-overlay.d.ts +0 -17
  149. package/dist/types/components/shared/mb-progress-tracker/mb-progress-tracker.d.ts +0 -19
  150. package/dist/types/components/shared/mb-screen/mb-screen.d.ts +0 -12
  151. package/dist/types/components/shared/mb-spinner/mb-spinner.d.ts +0 -16
  152. package/dist/types/components/shared/mb-tooltip/mb-tooltip.d.ts +0 -10
  153. package/dist/types/components/shared/mb-tooltip-advanced/mb-tooltip-advanced.d.ts +0 -7
  154. package/dist/types/utils/data-structures.d.ts +0 -264
  155. package/dist/types/utils/device.helpers.d.ts +0 -7
  156. package/dist/types/utils/error-structures.d.ts +0 -44
  157. package/dist/types/utils/generic.helpers.d.ts +0 -21
  158. package/dist/types/utils/sdk.service.d.ts +0 -52
  159. package/dist/types/utils/state-lifter.d.ts +0 -3
  160. package/dist/types/utils/status.document-detector.d.ts +0 -14
  161. package/dist/types/utils/translation.service.d.ts +0 -77
  162. package/loader/package.json +0 -11
@@ -0,0 +1,925 @@
1
+ 'use strict';
2
+
3
+ var index = require('./index-DGM9-FNg.js');
4
+
5
+ const myComponentCss = ":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,canvas{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,canvas.mirror{transform:rotateY(180deg)}canvas{z-index:1}video{z-index:0}.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;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7);opacity:0.8}.card-outline.perfect-match{box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7)}.side{position:absolute;background:#999;transition:background-color 0.3s ease}.side.aligned{background:#28a745}.side-top{top:0;left:0;width:100%;height:3px}.side-right{top:0;right:0;width:3px;height:100%}.side-bottom{bottom:0;left:0;width:100%;height:3px}.side-left{top:0;left:0;width:3px;height:100%}.corner{position:absolute;width:20px;height:20px;border:2px solid #999;z-index:12}.corner-tl{top:-10px;left:-10px;border-right:none;border-bottom:none}.corner-tr{top:-10px;right:-10px;border-left:none;border-bottom:none}.corner-bl{bottom:-10px;left:-10px;border-right:none;border-top:none}.corner-br{bottom:-10px;right:-10px;border-left:none;border-top:none}.corner.perfect-match{border-color:#28a745}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);color:#fff;font-size:14px;font-weight:600;text-align:center;white-space:normal;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;z-index:20}.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 9999px rgba(0, 0, 0, 0.7), 0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7), 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-button{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;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:translateX(-50%) translateY(0)}.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))}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.8);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:20px}.loading-spinner{width:60px;height:60px;border:4px solid rgba(255, 255, 255, 0.2);border-top:4px solid #007bff;border-radius:50%;animation:spin 1s linear infinite;margin-bottom:20px}.loading-text{color:white;font-size:16px;font-weight:500;text-align:center;opacity:0.9}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}";
6
+
7
+ const JaakStamps = class {
8
+ constructor(hostRef) {
9
+ index.registerInstance(this, hostRef);
10
+ this.captureCompleted = index.createEvent(this, "captureCompleted");
11
+ this.isReady = index.createEvent(this, "isReady");
12
+ }
13
+ get el() { return index.getElement(this); }
14
+ debug = false;
15
+ alignmentTolerance = 10; // Tolerancia en píxeles para considerar un lado alineado (escalado para 320x320)
16
+ captureCompleted;
17
+ isReady;
18
+ isVideoActive = false;
19
+ statusMessage = 'Presione el botón para activar la cámara';
20
+ statusColor = '#aaa';
21
+ bestScore = 0;
22
+ capturedFullFrame = null;
23
+ capturedCroppedId = null;
24
+ capturedBackFullFrame = null;
25
+ capturedBackCroppedId = null;
26
+ captureStep = 'front';
27
+ isCapturing = false;
28
+ showFlipAnimation = false;
29
+ showSuccessAnimation = false;
30
+ shouldMirrorVideo = true;
31
+ sideAlignment = {
32
+ top: false,
33
+ right: false,
34
+ bottom: false,
35
+ left: false
36
+ };
37
+ isDetectionPaused = false;
38
+ isLoading = false;
39
+ isModelPreloaded = false;
40
+ isMaskReady = false;
41
+ videoRef;
42
+ canvasRef;
43
+ session;
44
+ startTime;
45
+ videoStream;
46
+ animationId;
47
+ hasScreenshotTaken = false;
48
+ lastDetectedBox;
49
+ // Performance optimization properties
50
+ frameSkipCounter = 0;
51
+ FRAME_SKIP = 2; // Process every 3rd frame (reduces CPU by ~66%)
52
+ consecutiveFailures = 0;
53
+ MAX_FAILURES = 30; // 0.5 seconds without detection
54
+ lastInferenceTime = 0;
55
+ MIN_INFERENCE_INTERVAL = 50; // Minimum 50ms between inferences
56
+ // Canvas pooling for memory optimization
57
+ preprocessCanvas;
58
+ preprocessCtx;
59
+ captureCanvas;
60
+ captureCtx;
61
+ MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/detector-nano.onnx";
62
+ INPUT_SIZE = 320;
63
+ CONFIDENCE_THRESHOLD = 0.6;
64
+ // ISO/IEC 7810 ID-1 standard dimensions (85.60mm x 53.98mm)
65
+ ID1_ASPECT_RATIO = 85.60 / 53.98; // 1.5863320574...
66
+ debugLog(...args) {
67
+ if (this.debug) {
68
+ console.log(...args);
69
+ }
70
+ }
71
+ emitReadyEvent() {
72
+ const isDocumentReady = !!window.ort && this.isModelPreloaded;
73
+ this.isReady.emit(isDocumentReady);
74
+ this.debugLog('🟢 isReady event emitted:', isDocumentReady);
75
+ }
76
+ isRearCamera(stream) {
77
+ const videoTrack = stream.getVideoTracks()[0];
78
+ if (!videoTrack)
79
+ return false;
80
+ const settings = videoTrack.getSettings();
81
+ return settings.facingMode === 'environment';
82
+ }
83
+ async componentDidLoad() {
84
+ if (!window.ort) {
85
+ const script = document.createElement('script');
86
+ script.src = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js';
87
+ document.head.appendChild(script);
88
+ // Wait for ONNX runtime to load before emitting ready event
89
+ script.onload = () => {
90
+ this.emitReadyEvent();
91
+ };
92
+ }
93
+ else {
94
+ // ONNX runtime already loaded
95
+ this.emitReadyEvent();
96
+ }
97
+ // Initialize canvas pool for better performance
98
+ this.initializeCanvasPool();
99
+ this.setupResizeObserver();
100
+ }
101
+ setupResizeObserver() {
102
+ if ('ResizeObserver' in window && this.canvasRef) {
103
+ const resizeObserver = new ResizeObserver(() => {
104
+ this.handleResize();
105
+ });
106
+ resizeObserver.observe(this.canvasRef.parentElement);
107
+ }
108
+ }
109
+ handleResize() {
110
+ if (this.canvasRef) {
111
+ const container = this.canvasRef.parentElement;
112
+ const rect = container.getBoundingClientRect();
113
+ // Set canvas size to match container
114
+ this.canvasRef.width = rect.width;
115
+ this.canvasRef.height = rect.height;
116
+ // Update mask positioning based on container and video dimensions
117
+ this.updateMaskDimensions(rect);
118
+ this.debugLog('📐 Canvas resized:', { width: rect.width, height: rect.height });
119
+ }
120
+ }
121
+ updateMaskDimensions(containerRect) {
122
+ if (!this.videoRef)
123
+ return;
124
+ const videoWidth = this.videoRef.videoWidth;
125
+ const videoHeight = this.videoRef.videoHeight;
126
+ if (videoWidth === 0 || videoHeight === 0)
127
+ return;
128
+ // Calculate video aspect ratio and container aspect ratio
129
+ const videoAspectRatio = videoWidth / videoHeight;
130
+ const containerAspectRatio = containerRect.width / containerRect.height;
131
+ // Determine how video fits in container (letterboxed or pillarboxed)
132
+ let displayedVideoWidth, displayedVideoHeight;
133
+ let videoOffsetX = 0, videoOffsetY = 0;
134
+ if (videoAspectRatio > containerAspectRatio) {
135
+ // Video is wider - letterboxed (black bars top/bottom)
136
+ displayedVideoWidth = containerRect.width;
137
+ displayedVideoHeight = containerRect.width / videoAspectRatio;
138
+ videoOffsetY = (containerRect.height - displayedVideoHeight) / 2;
139
+ }
140
+ else {
141
+ // Video is taller - pillarboxed (black bars left/right)
142
+ displayedVideoHeight = containerRect.height;
143
+ displayedVideoWidth = containerRect.height * videoAspectRatio;
144
+ videoOffsetX = (containerRect.width - displayedVideoWidth) / 2;
145
+ }
146
+ // Calculate maximum possible mask size while preserving exact ID-1 aspect ratio
147
+ // Determine the limiting dimension based on video orientation and ID-1 proportions
148
+ // Calculate what would be the max width if limited by video height
149
+ const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
150
+ let maskWidthInVideo, maskHeightInVideo;
151
+ if (maxWidthByHeight <= displayedVideoWidth) {
152
+ // Video height is the limiting factor
153
+ maskHeightInVideo = displayedVideoHeight * 0.9; // Use 90% of available height
154
+ maskWidthInVideo = maskHeightInVideo * this.ID1_ASPECT_RATIO;
155
+ }
156
+ else {
157
+ // Video width is the limiting factor
158
+ maskWidthInVideo = displayedVideoWidth * 0.9; // Use 90% of available width
159
+ maskHeightInVideo = maskWidthInVideo / this.ID1_ASPECT_RATIO;
160
+ }
161
+ // Convert to percentages of the container
162
+ const maskWidthPercent = (maskWidthInVideo / containerRect.width) * 100;
163
+ const maskHeightPercent = (maskHeightInVideo / containerRect.height) * 100;
164
+ // Calculate the center position of the displayed video area
165
+ const videoCenterX = videoOffsetX + (displayedVideoWidth / 2);
166
+ const videoCenterY = videoOffsetY + (displayedVideoHeight / 2);
167
+ // Convert to percentages of the container
168
+ const videoCenterXPercent = (videoCenterX / containerRect.width) * 100;
169
+ const videoCenterYPercent = (videoCenterY / containerRect.height) * 100;
170
+ // Update CSS custom properties for mask sizing and positioning
171
+ this.el.style.setProperty('--mask-width', `${maskWidthPercent}%`);
172
+ this.el.style.setProperty('--mask-height', `${maskHeightPercent}%`);
173
+ this.el.style.setProperty('--mask-center-x', `${videoCenterXPercent}%`);
174
+ this.el.style.setProperty('--mask-center-y', `${videoCenterYPercent}%`);
175
+ // Mark mask as ready now that dimensions are calculated
176
+ this.isMaskReady = true;
177
+ this.debugLog('🎯 Mask dimensions updated:', {
178
+ video: { width: videoWidth, height: videoHeight },
179
+ displayed: { width: displayedVideoWidth, height: displayedVideoHeight },
180
+ mask: { widthPercent: maskWidthPercent, heightPercent: maskHeightPercent },
181
+ center: { x: videoCenterXPercent, y: videoCenterYPercent },
182
+ offset: { x: videoOffsetX, y: videoOffsetY }
183
+ });
184
+ }
185
+ initializeCanvasPool() {
186
+ // Preprocess canvas - reused for every inference
187
+ this.preprocessCanvas = document.createElement('canvas');
188
+ this.preprocessCanvas.width = this.INPUT_SIZE;
189
+ this.preprocessCanvas.height = this.INPUT_SIZE;
190
+ this.preprocessCtx = this.preprocessCanvas.getContext('2d', {
191
+ alpha: false, // No transparency needed
192
+ willReadFrequently: true // Optimize for frequent getImageData calls
193
+ });
194
+ // Capture canvas - reused for screenshots
195
+ this.captureCanvas = document.createElement('canvas');
196
+ this.captureCtx = this.captureCanvas.getContext('2d', {
197
+ alpha: false
198
+ });
199
+ this.debugLog('🎨 Canvas pool initialized for performance');
200
+ }
201
+ disconnectedCallback() {
202
+ this.cleanup();
203
+ }
204
+ async getCapturedImages() {
205
+ if (this.captureStep !== 'completed') {
206
+ throw new Error('El proceso de captura no ha sido completado');
207
+ }
208
+ return {
209
+ front: {
210
+ fullFrame: this.capturedFullFrame,
211
+ cropped: this.capturedCroppedId
212
+ },
213
+ back: {
214
+ fullFrame: this.capturedBackFullFrame,
215
+ cropped: this.capturedBackCroppedId
216
+ },
217
+ metadata: {
218
+ hasBackCapture: !!(this.capturedBackFullFrame && this.capturedBackCroppedId),
219
+ totalImages: (this.capturedBackFullFrame && this.capturedBackCroppedId) ? 4 : 2
220
+ }
221
+ };
222
+ }
223
+ async isProcessCompleted() {
224
+ return this.captureStep === 'completed';
225
+ }
226
+ async startCapture() {
227
+ await this.startDetection();
228
+ }
229
+ async stopCapture() {
230
+ this.exitSession();
231
+ }
232
+ async resetCapture() {
233
+ this.resetDetection();
234
+ }
235
+ async getStatus() {
236
+ return {
237
+ isVideoActive: this.isVideoActive,
238
+ captureStep: this.captureStep,
239
+ statusMessage: this.statusMessage,
240
+ hasImages: !!(this.capturedFullFrame || this.capturedBackFullFrame),
241
+ isProcessCompleted: this.captureStep === 'completed',
242
+ isModelPreloaded: this.isModelPreloaded
243
+ };
244
+ }
245
+ async preloadModel() {
246
+ if (this.isModelPreloaded || this.session) {
247
+ this.debugLog('🚀 Model already preloaded or session exists');
248
+ return { success: true, message: 'Model already loaded' };
249
+ }
250
+ try {
251
+ this.isLoading = true;
252
+ this.statusMessage = "Precargando modelo de detección...";
253
+ this.statusColor = "#007bff";
254
+ const modelPath = this.MODEL_PATH;
255
+ this.debugLog('🤖 Preloading model:', modelPath);
256
+ // Configure ONNX Runtime with device-specific optimizations
257
+ const sessionOptions = this.getSessionOptions();
258
+ this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
259
+ this.isModelPreloaded = true;
260
+ this.isLoading = false;
261
+ this.statusMessage = "Modelo precargado. Listo para comenzar detección";
262
+ this.statusColor = "#28a745";
263
+ this.emitReadyEvent();
264
+ this.debugLog('✅ Model preloaded successfully');
265
+ return { success: true, message: 'Model preloaded successfully' };
266
+ }
267
+ catch (error) {
268
+ this.debugLog('❌ Error preloading model:', error);
269
+ this.isLoading = false;
270
+ this.statusMessage = "Error al precargar el modelo";
271
+ this.statusColor = "#ff6b6b";
272
+ return { success: false, error: error.message };
273
+ }
274
+ }
275
+ async skipBackCapture() {
276
+ if (this.captureStep === 'back' && this.capturedFullFrame) {
277
+ this.completeProcess(true);
278
+ }
279
+ }
280
+ cleanup() {
281
+ if (this.animationId) {
282
+ cancelAnimationFrame(this.animationId);
283
+ }
284
+ if (this.videoStream) {
285
+ this.videoStream.getTracks().forEach(track => track.stop());
286
+ }
287
+ // Limpiar canvas en cleanup general
288
+ if (this.canvasRef) {
289
+ const ctx = this.canvasRef.getContext("2d");
290
+ if (ctx) {
291
+ ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
292
+ }
293
+ }
294
+ // OPTIMIZATION: Clean up canvas pool
295
+ this.cleanupCanvasPool();
296
+ }
297
+ cleanupCanvasPool() {
298
+ // Release canvas references for garbage collection
299
+ if (this.preprocessCanvas) {
300
+ this.preprocessCtx = undefined;
301
+ this.preprocessCanvas = undefined;
302
+ }
303
+ if (this.captureCanvas) {
304
+ this.captureCtx = undefined;
305
+ this.captureCanvas = undefined;
306
+ }
307
+ // Disposed ONNX session
308
+ if (this.session) {
309
+ this.session.release?.();
310
+ this.session = undefined;
311
+ }
312
+ this.isModelPreloaded = false;
313
+ this.debugLog('🧹 Canvas pool cleaned up');
314
+ }
315
+ async getMaxResolution() {
316
+ try {
317
+ // Primero obtén un stream básico para acceder a las capacidades
318
+ const tempStream = await navigator.mediaDevices.getUserMedia({
319
+ video: { facingMode: "environment" }
320
+ });
321
+ const videoTrack = tempStream.getVideoTracks()[0];
322
+ const capabilities = videoTrack.getCapabilities();
323
+ // Detener el stream temporal
324
+ tempStream.getTracks().forEach(track => track.stop());
325
+ // Construir restricciones con resolución optimizada para tablets
326
+ const constraints = {
327
+ facingMode: "environment"
328
+ };
329
+ if (capabilities.width && capabilities.height) {
330
+ // Limitar resolución máxima para tablets para evitar problemas de rendimiento
331
+ const maxWidth = Math.min(capabilities.width.max, 1920);
332
+ const maxHeight = Math.min(capabilities.height.max, 1080);
333
+ // Para tablets, usar resolución moderada en lugar de máxima
334
+ const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
335
+ if (isTablet) {
336
+ constraints.width = { ideal: Math.min(maxWidth, 1280) };
337
+ constraints.height = { ideal: Math.min(maxHeight, 720) };
338
+ }
339
+ else {
340
+ constraints.width = { ideal: maxWidth };
341
+ constraints.height = { ideal: maxHeight };
342
+ }
343
+ this.debugLog('📐 Resolution capabilities:', {
344
+ maxWidth: capabilities.width.max,
345
+ maxHeight: capabilities.height.max,
346
+ selectedWidth: constraints.width.ideal,
347
+ selectedHeight: constraints.height.ideal,
348
+ isTablet
349
+ });
350
+ }
351
+ return constraints;
352
+ }
353
+ catch (err) {
354
+ this.debugLog('⚠️ Could not get capabilities, using fallback');
355
+ // Fallback optimizado para tablets
356
+ const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
357
+ return {
358
+ facingMode: "environment",
359
+ width: { ideal: isTablet ? 1280 : 1920 },
360
+ height: { ideal: isTablet ? 720 : 1080 }
361
+ };
362
+ }
363
+ }
364
+ async setupCamera() {
365
+ try {
366
+ const constraints = await this.getMaxResolution();
367
+ const stream = await navigator.mediaDevices.getUserMedia({
368
+ video: constraints,
369
+ audio: false
370
+ });
371
+ if (this.videoRef) {
372
+ this.videoRef.srcObject = stream;
373
+ this.videoStream = stream;
374
+ // Determine if video should be mirrored
375
+ const isRear = this.isRearCamera(stream);
376
+ this.shouldMirrorVideo = !isRear;
377
+ this.debugLog('📹 Rear camera:', isRear);
378
+ this.debugLog('🪞 Should mirror video:', this.shouldMirrorVideo);
379
+ return new Promise((resolve) => {
380
+ this.videoRef.onloadedmetadata = async () => {
381
+ await this.videoRef.play();
382
+ this.isVideoActive = true;
383
+ // Update mask dimensions once video is loaded
384
+ if (this.canvasRef) {
385
+ const container = this.canvasRef.parentElement;
386
+ const rect = container.getBoundingClientRect();
387
+ this.updateMaskDimensions(rect);
388
+ }
389
+ resolve();
390
+ };
391
+ });
392
+ }
393
+ }
394
+ catch (err) {
395
+ this.debugLog("❌ No se pudo acceder a la cámara:", err);
396
+ this.statusMessage = "Error: No se pudo acceder a la cámara.";
397
+ this.statusColor = "#ff6b6b";
398
+ }
399
+ }
400
+ preprocess(video) {
401
+ // OPTIMIZATION: Reuse canvas instead of creating new ones
402
+ if (!this.preprocessCanvas || !this.preprocessCtx) {
403
+ this.initializeCanvasPool();
404
+ }
405
+ // Clear and redraw on reused canvas
406
+ this.preprocessCtx.clearRect(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
407
+ this.preprocessCtx.drawImage(video, 0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
408
+ const imageData = this.preprocessCtx.getImageData(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
409
+ const [R, G, B] = [[], [], []];
410
+ const { data } = imageData;
411
+ // Optimized pixel processing
412
+ for (let i = 0; i < data.length; i += 4) {
413
+ R.push(data[i] / 255);
414
+ G.push(data[i + 1] / 255);
415
+ B.push(data[i + 2] / 255);
416
+ }
417
+ const transposedData = new Float32Array(R.concat(G, B));
418
+ return new window.ort.Tensor("float32", transposedData, [1, 3, this.INPUT_SIZE, this.INPUT_SIZE]);
419
+ }
420
+ getSessionOptions() {
421
+ return {
422
+ executionProviders: [
423
+ // Try WebGL first for GPU acceleration, fallback to WASM
424
+ 'webgl',
425
+ 'wasm'
426
+ ],
427
+ graphOptimizationLevel: 'all', // Maximum optimization
428
+ logSeverityLevel: this.debug ? 2 : 4, // Reduce logging overhead in production
429
+ logVerbosityLevel: 0,
430
+ enableCpuMemArena: true,
431
+ enableMemPattern: true,
432
+ executionMode: 'parallel',
433
+ interOpNumThreads: 2,
434
+ intraOpNumThreads: 2,
435
+ };
436
+ }
437
+ async startDetection() {
438
+ try {
439
+ // Check if model is already preloaded
440
+ if (!this.session) {
441
+ this.isLoading = true;
442
+ this.statusMessage = "Cargando modelo de detección...";
443
+ this.statusColor = "#007bff";
444
+ const modelPath = this.MODEL_PATH;
445
+ this.debugLog('🤖 Loading model:', modelPath);
446
+ const sessionOptions = this.getSessionOptions();
447
+ this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
448
+ this.isModelPreloaded = true;
449
+ this.emitReadyEvent();
450
+ }
451
+ else {
452
+ this.debugLog('🚀 Using preloaded model');
453
+ this.statusMessage = "Usando modelo precargado...";
454
+ this.statusColor = "#007bff";
455
+ }
456
+ this.statusMessage = "Configurando cámara...";
457
+ await this.setupCamera();
458
+ this.startTime = Date.now();
459
+ this.isLoading = false;
460
+ this.detectFrame();
461
+ }
462
+ catch (err) {
463
+ this.debugLog("Error al inicializar:", err);
464
+ this.statusMessage = "Error al inicializar el detector";
465
+ this.statusColor = "#ff6b6b";
466
+ this.isLoading = false;
467
+ }
468
+ }
469
+ async detectFrame() {
470
+ try {
471
+ if (!this.videoRef || !this.canvasRef || !this.session)
472
+ return;
473
+ // Pausar detección si está marcado como pausado
474
+ if (this.isDetectionPaused) {
475
+ // Solo continuar el bucle sin procesar detección
476
+ if (this.captureStep !== 'completed') {
477
+ this.animationId = requestAnimationFrame(() => this.detectFrame());
478
+ }
479
+ return;
480
+ }
481
+ // OPTIMIZATION 1: Frame skipping for performance
482
+ this.frameSkipCounter++;
483
+ if (this.frameSkipCounter <= this.FRAME_SKIP) {
484
+ if (this.captureStep !== 'completed') {
485
+ this.animationId = requestAnimationFrame(() => this.detectFrame());
486
+ }
487
+ return;
488
+ }
489
+ this.frameSkipCounter = 0;
490
+ // OPTIMIZATION 2: Throttle inference based on time
491
+ const currentTime = Date.now();
492
+ if (currentTime - this.lastInferenceTime < this.MIN_INFERENCE_INTERVAL) {
493
+ if (this.captureStep !== 'completed') {
494
+ this.animationId = requestAnimationFrame(() => this.detectFrame());
495
+ }
496
+ return;
497
+ }
498
+ this.lastInferenceTime = currentTime;
499
+ const ctx = this.canvasRef.getContext("2d");
500
+ const inputTensor = this.preprocess(this.videoRef);
501
+ const feeds = { [this.session.inputNames[0]]: inputTensor };
502
+ const results = await this.session.run(feeds);
503
+ const output = results[this.session.outputNames[0]].data;
504
+ const finalBoxes = [];
505
+ for (let i = 0; i < output.length; i += 6) {
506
+ const [x1, y1, x2, y2, score, classId] = output.slice(i, i + 6);
507
+ if (score > this.CONFIDENCE_THRESHOLD) {
508
+ finalBoxes.push({ x: x1, y: y1, w: x2 - x1, h: y2 - y1, score, classId });
509
+ if (this.startTime && Date.now() - this.startTime < 5000) {
510
+ const currentBox = { x: x1, y: y1, w: x2 - x1, h: y2 - y1, score };
511
+ const isWellPositioned = this.isCardInFrame(currentBox);
512
+ const effectiveScore = isWellPositioned ? score * 1.2 : score;
513
+ if (effectiveScore > this.bestScore) {
514
+ this.bestScore = effectiveScore;
515
+ }
516
+ }
517
+ }
518
+ }
519
+ // OPTIMIZATION 3: Adaptive frame rate based on detection success
520
+ if (finalBoxes.length === 0) {
521
+ this.consecutiveFailures++;
522
+ }
523
+ else {
524
+ this.consecutiveFailures = 0;
525
+ }
526
+ ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
527
+ if (this.debug) {
528
+ this.drawDetections(ctx, finalBoxes);
529
+ }
530
+ this.updateGuidanceStatus(finalBoxes);
531
+ this.updateMaskColor(finalBoxes);
532
+ // Solo continuar si no hemos completado el proceso
533
+ if (this.captureStep !== 'completed') {
534
+ // OPTIMIZATION 4: Reduce frame rate when no detection for better battery life
535
+ if (this.consecutiveFailures > this.MAX_FAILURES) {
536
+ // Reduce to ~5fps when no detection for 0.5 seconds
537
+ setTimeout(() => this.detectFrame(), 200);
538
+ }
539
+ else {
540
+ this.animationId = requestAnimationFrame(() => this.detectFrame());
541
+ }
542
+ }
543
+ }
544
+ catch (e) {
545
+ this.debugLog("Error en inferencia:", e);
546
+ // Solo continuar si no hemos completado el proceso
547
+ if (this.captureStep !== 'completed') {
548
+ // On error, wait longer before retrying
549
+ setTimeout(() => this.detectFrame(), 100);
550
+ }
551
+ }
552
+ }
553
+ isCardInFrame(box) {
554
+ const cardCenterX = box.x + box.w / 2;
555
+ const cardCenterY = box.y + box.h / 2;
556
+ const frameCenterX = this.INPUT_SIZE / 2;
557
+ const frameCenterY = this.INPUT_SIZE / 2;
558
+ const toleranceX = 40;
559
+ const toleranceY = 30;
560
+ const isCentered = Math.abs(cardCenterX - frameCenterX) < toleranceX &&
561
+ Math.abs(cardCenterY - frameCenterY) < toleranceY;
562
+ const isGoodSize = box.w > 150 && box.w < 300 && box.h > 90 && box.h < 200;
563
+ return isCentered && isGoodSize;
564
+ }
565
+ checkSideAlignment(box) {
566
+ if (!this.videoRef)
567
+ return { top: false, right: false, bottom: false, left: false };
568
+ // Get video dimensions to calculate actual mask boundaries in model space
569
+ const videoWidth = this.videoRef.videoWidth;
570
+ const videoHeight = this.videoRef.videoHeight;
571
+ if (videoWidth === 0 || videoHeight === 0) {
572
+ return { top: false, right: false, bottom: false, left: false };
573
+ }
574
+ // Calculate video aspect ratio
575
+ const videoAspectRatio = videoWidth / videoHeight;
576
+ // The model sees video stretched to 320x320, but we need to calculate where
577
+ // the mask should be in this distorted space to match the visual mask
578
+ // In the visual display, we calculate mask size based on the limiting dimension
579
+ // We need to replicate this logic but account for the distortion in model space
580
+ // Calculate the "display" dimensions (what the visual mask calculations use)
581
+ const containerAspectRatio = 1; // Assume square container for simplicity
582
+ let displayedVideoWidth, displayedVideoHeight;
583
+ if (videoAspectRatio > containerAspectRatio) {
584
+ // Video is wider - letterboxed in display
585
+ displayedVideoWidth = this.INPUT_SIZE;
586
+ displayedVideoHeight = this.INPUT_SIZE / videoAspectRatio;
587
+ }
588
+ else {
589
+ // Video is taller - pillarboxed in display
590
+ displayedVideoHeight = this.INPUT_SIZE;
591
+ displayedVideoWidth = this.INPUT_SIZE * videoAspectRatio;
592
+ }
593
+ // Calculate mask dimensions using the same logic as updateMaskDimensions
594
+ const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
595
+ let visualMaskWidth, visualMaskHeight;
596
+ if (maxWidthByHeight <= displayedVideoWidth) {
597
+ // Video height is the limiting factor
598
+ visualMaskHeight = displayedVideoHeight * 0.9;
599
+ visualMaskWidth = visualMaskHeight * this.ID1_ASPECT_RATIO;
600
+ }
601
+ else {
602
+ // Video width is the limiting factor
603
+ visualMaskWidth = displayedVideoWidth * 0.9;
604
+ visualMaskHeight = visualMaskWidth / this.ID1_ASPECT_RATIO;
605
+ }
606
+ // Now map these visual mask dimensions to the distorted model space
607
+ // The model stretches video to 320x320, so we need to apply the inverse transformation
608
+ const modelMaskWidth = visualMaskWidth * (this.INPUT_SIZE / displayedVideoWidth);
609
+ const modelMaskHeight = visualMaskHeight * (this.INPUT_SIZE / displayedVideoHeight);
610
+ // Calculate mask boundaries in model coordinate system (always centered in 320x320)
611
+ const maskCenterX = this.INPUT_SIZE / 2;
612
+ const maskCenterY = this.INPUT_SIZE / 2;
613
+ const maskLeft = maskCenterX - (modelMaskWidth / 2);
614
+ const maskRight = maskCenterX + (modelMaskWidth / 2);
615
+ const maskTop = maskCenterY - (modelMaskHeight / 2);
616
+ const maskBottom = maskCenterY + (modelMaskHeight / 2);
617
+ // Obtener las coordenadas del documento detectado
618
+ let docLeft = box.x;
619
+ let docRight = box.x + box.w;
620
+ const docTop = box.y;
621
+ const docBottom = box.y + box.h;
622
+ // Si el video está en modo mirror, invertir las coordenadas horizontales
623
+ if (this.shouldMirrorVideo) {
624
+ const originalDocLeft = docLeft;
625
+ const originalDocRight = docRight;
626
+ docLeft = this.INPUT_SIZE - originalDocRight;
627
+ docRight = this.INPUT_SIZE - originalDocLeft;
628
+ }
629
+ // Tolerancia para considerar que un lado está alineado (en píxeles)
630
+ const tolerance = this.alignmentTolerance;
631
+ return {
632
+ top: Math.abs(docTop - maskTop) <= tolerance,
633
+ right: Math.abs(docRight - maskRight) <= tolerance,
634
+ bottom: Math.abs(docBottom - maskBottom) <= tolerance,
635
+ left: Math.abs(docLeft - maskLeft) <= tolerance
636
+ };
637
+ }
638
+ areAllSidesAligned(alignment) {
639
+ return alignment.top && alignment.right && alignment.bottom && alignment.left;
640
+ }
641
+ updateMaskColor(boxes) {
642
+ const cardOutline = this.el.shadowRoot?.querySelector('.card-outline');
643
+ const corners = this.el.shadowRoot?.querySelectorAll('.corner');
644
+ const topSide = this.el.shadowRoot?.querySelector('.side-top');
645
+ const rightSide = this.el.shadowRoot?.querySelector('.side-right');
646
+ const bottomSide = this.el.shadowRoot?.querySelector('.side-bottom');
647
+ const leftSide = this.el.shadowRoot?.querySelector('.side-left');
648
+ let bestBox = null;
649
+ let currentAlignment = { top: false, right: false, bottom: false, left: false };
650
+ if (boxes.length > 0) {
651
+ bestBox = boxes.reduce((best, current) => current.score > best.score ? current : best);
652
+ currentAlignment = this.checkSideAlignment(bestBox);
653
+ this.sideAlignment = currentAlignment;
654
+ }
655
+ else {
656
+ // Reset alignment when no detection
657
+ this.sideAlignment = { top: false, right: false, bottom: false, left: false };
658
+ }
659
+ // Actualizar colores de cada lado individualmente
660
+ topSide?.classList.toggle('aligned', currentAlignment.top);
661
+ rightSide?.classList.toggle('aligned', currentAlignment.right);
662
+ bottomSide?.classList.toggle('aligned', currentAlignment.bottom);
663
+ leftSide?.classList.toggle('aligned', currentAlignment.left);
664
+ // Verificar si todos los lados están alineados
665
+ const allSidesAligned = this.areAllSidesAligned(currentAlignment);
666
+ if (allSidesAligned && bestBox) {
667
+ cardOutline?.classList.add('perfect-match');
668
+ corners?.forEach(corner => corner.classList.add('perfect-match'));
669
+ if (!this.hasScreenshotTaken) {
670
+ this.lastDetectedBox = bestBox;
671
+ this.takeScreenshot();
672
+ this.hasScreenshotTaken = true;
673
+ // Reset para permitir segunda captura
674
+ setTimeout(() => {
675
+ this.hasScreenshotTaken = false;
676
+ }, 2000);
677
+ }
678
+ }
679
+ else {
680
+ cardOutline?.classList.remove('perfect-match');
681
+ corners?.forEach(corner => corner.classList.remove('perfect-match'));
682
+ }
683
+ }
684
+ updateGuidanceStatus(boxes) {
685
+ if (boxes.length === 0) {
686
+ this.statusMessage = "Posicione la identificación dentro del marco";
687
+ this.statusColor = "#ff6b6b";
688
+ }
689
+ else {
690
+ const bestBox = boxes.reduce((best, current) => current.score > best.score ? current : best);
691
+ const alignment = this.checkSideAlignment(bestBox);
692
+ const alignedSides = [alignment.top, alignment.right, alignment.bottom, alignment.left].filter(Boolean).length;
693
+ const allSidesAligned = this.areAllSidesAligned(alignment);
694
+ if (allSidesAligned) {
695
+ this.statusMessage = "Identificación perfectamente alineada. Mantenga inmóvil";
696
+ this.statusColor = "#00ff00";
697
+ }
698
+ else if (alignedSides > 0) {
699
+ this.statusMessage = `Alinee los lados restantes (${alignedSides}/4 lados correctos)`;
700
+ this.statusColor = "#ffb366";
701
+ }
702
+ else if (bestBox.w < 150) {
703
+ this.statusMessage = "Identificación detectada. Acerque al marco";
704
+ this.statusColor = "#ffb366";
705
+ }
706
+ else {
707
+ this.statusMessage = "Identificación detectada. Alinee con el marco";
708
+ this.statusColor = "#ffb366";
709
+ }
710
+ }
711
+ }
712
+ drawDetections(ctx, boxes) {
713
+ if (!this.videoRef)
714
+ return;
715
+ // Get video and container dimensions
716
+ const videoWidth = this.videoRef.videoWidth;
717
+ const videoHeight = this.videoRef.videoHeight;
718
+ const containerWidth = this.canvasRef.width;
719
+ const containerHeight = this.canvasRef.height;
720
+ if (videoWidth === 0 || videoHeight === 0)
721
+ return;
722
+ // Calculate video aspect ratio and container aspect ratio
723
+ const videoAspectRatio = videoWidth / videoHeight;
724
+ const containerAspectRatio = containerWidth / containerHeight;
725
+ // Determine how video fits in container (same logic as updateMaskDimensions)
726
+ let displayedVideoWidth, displayedVideoHeight;
727
+ let videoOffsetX = 0, videoOffsetY = 0;
728
+ if (videoAspectRatio > containerAspectRatio) {
729
+ // Video is wider - letterboxed (black bars top/bottom)
730
+ displayedVideoWidth = containerWidth;
731
+ displayedVideoHeight = containerWidth / videoAspectRatio;
732
+ videoOffsetY = (containerHeight - displayedVideoHeight) / 2;
733
+ }
734
+ else {
735
+ // Video is taller - pillarboxed (black bars left/right)
736
+ displayedVideoHeight = containerHeight;
737
+ displayedVideoWidth = containerHeight * videoAspectRatio;
738
+ videoOffsetX = (containerWidth - displayedVideoWidth) / 2;
739
+ }
740
+ // Scale factor from model coordinates (320x320) to displayed video area
741
+ const scaleX = displayedVideoWidth / this.INPUT_SIZE;
742
+ const scaleY = displayedVideoHeight / this.INPUT_SIZE;
743
+ boxes.forEach(det => {
744
+ // Convert model coordinates to displayed video coordinates
745
+ const x = det.x * scaleX + videoOffsetX;
746
+ const y = det.y * scaleY + videoOffsetY;
747
+ const w = det.w * scaleX;
748
+ const h = det.h * scaleY;
749
+ ctx.strokeStyle = "#32406C";
750
+ ctx.lineWidth = 2;
751
+ ctx.strokeRect(x, y, w, h);
752
+ });
753
+ }
754
+ takeScreenshot() {
755
+ if (!this.videoRef || !this.lastDetectedBox)
756
+ return;
757
+ // Activar animación
758
+ this.triggerCaptureAnimation();
759
+ // OPTIMIZATION: Reuse capture canvas for full frame
760
+ if (!this.captureCanvas || !this.captureCtx) {
761
+ this.initializeCanvasPool();
762
+ }
763
+ // Resize reused canvas for full frame
764
+ this.captureCanvas.width = this.videoRef.videoWidth;
765
+ this.captureCanvas.height = this.videoRef.videoHeight;
766
+ this.captureCtx.drawImage(this.videoRef, 0, 0, this.captureCanvas.width, this.captureCanvas.height);
767
+ // Calcular las coordenadas de recorte basadas en la detección
768
+ const scaleX = this.videoRef.videoWidth / this.INPUT_SIZE;
769
+ const scaleY = this.videoRef.videoHeight / this.INPUT_SIZE;
770
+ const cropX = Math.max(0, this.lastDetectedBox.x * scaleX);
771
+ const cropY = Math.max(0, this.lastDetectedBox.y * scaleY);
772
+ const cropWidth = Math.min(this.lastDetectedBox.w * scaleX, this.videoRef.videoWidth - cropX);
773
+ const cropHeight = Math.min(this.lastDetectedBox.h * scaleY, this.videoRef.videoHeight - cropY);
774
+ // OPTIMIZATION: Create temporary canvas only for cropped version
775
+ // (We reuse main capture canvas for full frame)
776
+ const croppedCanvas = document.createElement('canvas');
777
+ croppedCanvas.width = cropWidth;
778
+ croppedCanvas.height = cropHeight;
779
+ const croppedCtx = croppedCanvas.getContext('2d', { alpha: false });
780
+ // Recortar la identificación del frame completo
781
+ croppedCtx.drawImage(this.videoRef, cropX, cropY, cropWidth, cropHeight, // Área de origen
782
+ 0, 0, cropWidth, cropHeight // Área de destino
783
+ );
784
+ if (this.captureStep === 'front') {
785
+ // Captura del frente usando canvas reutilizado
786
+ this.capturedFullFrame = this.captureCanvas.toDataURL('image/png');
787
+ this.capturedCroppedId = croppedCanvas.toDataURL('image/png');
788
+ this.captureStep = 'back';
789
+ this.statusMessage = "Voltee la identificación y muestre la parte trasera";
790
+ this.statusColor = "#007bff";
791
+ // Pausar detección durante la animación de giro
792
+ this.isDetectionPaused = true;
793
+ // Mostrar animación de giro después de la captura
794
+ setTimeout(() => {
795
+ this.showFlipAnimation = true;
796
+ setTimeout(() => {
797
+ this.showFlipAnimation = false;
798
+ // Reanudar detección después de que termine la animación
799
+ this.isDetectionPaused = false;
800
+ }, 3000);
801
+ }, 800);
802
+ this.debugLog('📸 FRENTE capturado. Esperando trasera...');
803
+ }
804
+ else if (this.captureStep === 'back') {
805
+ // Captura de la trasera usando canvas reutilizado
806
+ this.capturedBackFullFrame = this.captureCanvas.toDataURL('image/png');
807
+ this.capturedBackCroppedId = croppedCanvas.toDataURL('image/png');
808
+ this.completeProcess(false);
809
+ this.debugLog('📸 TRASERA capturada. Proceso completado. Detector detenido. Imágenes emitidas.');
810
+ }
811
+ }
812
+ triggerCaptureAnimation() {
813
+ this.isCapturing = true;
814
+ // Agregar clase de animación al marco
815
+ const cardOutline = this.el.shadowRoot?.querySelector('.card-outline');
816
+ cardOutline?.classList.add('capturing');
817
+ // Limpiar animación después de que termine
818
+ setTimeout(() => {
819
+ this.isCapturing = false;
820
+ cardOutline?.classList.remove('capturing');
821
+ }, 600);
822
+ }
823
+ stopDetection() {
824
+ if (this.animationId) {
825
+ cancelAnimationFrame(this.animationId);
826
+ this.animationId = undefined;
827
+ }
828
+ // Limpiar canvas para eliminar cualquier detección visual residual
829
+ if (this.canvasRef) {
830
+ const ctx = this.canvasRef.getContext("2d");
831
+ ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
832
+ }
833
+ this.debugLog('🛑 Detector de identificación detenido');
834
+ }
835
+ resetDetection() {
836
+ this.bestScore = 0;
837
+ this.startTime = Date.now();
838
+ this.statusMessage = "Sistema reiniciado. Posicione la identificación";
839
+ this.statusColor = "#aaa";
840
+ this.hasScreenshotTaken = false;
841
+ this.capturedFullFrame = null;
842
+ this.capturedCroppedId = null;
843
+ this.capturedBackFullFrame = null;
844
+ this.capturedBackCroppedId = null;
845
+ this.captureStep = 'front';
846
+ this.isCapturing = false;
847
+ this.showFlipAnimation = false;
848
+ this.showSuccessAnimation = false;
849
+ this.isDetectionPaused = false;
850
+ this.isLoading = false;
851
+ this.lastDetectedBox = undefined;
852
+ this.isModelPreloaded = false;
853
+ // Reset performance counters
854
+ this.frameSkipCounter = 0;
855
+ this.consecutiveFailures = 0;
856
+ this.lastInferenceTime = 0;
857
+ if (this.canvasRef) {
858
+ const ctx = this.canvasRef.getContext("2d");
859
+ ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
860
+ }
861
+ // Reiniciar el detector si estaba funcionando
862
+ if (this.isVideoActive && this.session) {
863
+ this.detectFrame();
864
+ }
865
+ }
866
+ completeProcess(skippedBack = false) {
867
+ this.captureStep = 'completed';
868
+ this.statusMessage = skippedBack ?
869
+ "Proceso completado (solo frente capturado)" :
870
+ "Proceso de captura completado exitosamente";
871
+ this.statusColor = "#28a745";
872
+ // Detener el detector
873
+ this.stopDetection();
874
+ // Emitir evento con las imágenes capturadas
875
+ const capturedImages = {
876
+ front: {
877
+ fullFrame: this.capturedFullFrame,
878
+ cropped: this.capturedCroppedId
879
+ },
880
+ back: {
881
+ fullFrame: this.capturedBackFullFrame,
882
+ cropped: this.capturedBackCroppedId
883
+ },
884
+ timestamp: new Date().toISOString(),
885
+ metadata: {
886
+ totalImages: skippedBack ? 2 : 4,
887
+ processCompleted: true,
888
+ backCaptureSkipped: skippedBack
889
+ }
890
+ };
891
+ this.captureCompleted.emit(capturedImages);
892
+ // Mostrar animación de éxito después de la captura
893
+ setTimeout(() => {
894
+ this.showSuccessAnimation = true;
895
+ setTimeout(() => {
896
+ this.showSuccessAnimation = false;
897
+ }, 3000);
898
+ }, 800);
899
+ }
900
+ exitSession() {
901
+ if (this.videoStream) {
902
+ this.videoStream.getTracks().forEach(track => track.stop());
903
+ this.videoStream = undefined;
904
+ this.isVideoActive = false;
905
+ this.statusMessage = "Sesión finalizada.";
906
+ this.statusColor = "#aaa";
907
+ }
908
+ this.isLoading = false;
909
+ // Limpiar canvas al finalizar sesión
910
+ if (this.canvasRef) {
911
+ const ctx = this.canvasRef.getContext("2d");
912
+ ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
913
+ }
914
+ this.cleanup();
915
+ }
916
+ render() {
917
+ return (index.h("div", { key: 'b63a5966ee08d4de7b5d8a10dbf248150e8620ec', class: "detector-container" }, index.h("div", { key: '1c62d540a1802a758b90a543edfdc364123ae950', class: "video-container" }, index.h("video", { key: '18e066e0005c3b287983ebb29c9e4aa147eaaf8d', ref: el => this.videoRef = el, autoplay: true, muted: true, playsinline: true, class: this.shouldMirrorVideo ? 'mirror' : '', style: { display: this.isVideoActive ? 'block' : 'none' } }), index.h("canvas", { key: '43cd238e38a5a2ff9c140800ac686580a7ca33b9', ref: el => this.canvasRef = el, class: this.shouldMirrorVideo ? 'mirror' : '' }), this.isMaskReady && (index.h("div", { key: 'f43db67b9d1ef47264092694c3ab8afa9925e258', class: "overlay-mask" }, index.h("div", { key: 'ac60d94edc4cfa6ccf91ba6e04d2be6e4368be97', class: "card-outline" }, index.h("div", { key: 'de6aca9bbfe778890adf4c69e8525a114c37f6d4', class: "side side-top" }), index.h("div", { key: '7ce7b1e2215b01ea5d714b8ecc988361e384b6f7', class: "side side-right" }), index.h("div", { key: 'b79a68f68facb42ca139d6a2bc8e1e6d7133872d', class: "side side-bottom" }), index.h("div", { key: '81d90c4a08cfc2267cec195a3b342c87bb1d07d0', class: "side side-left" }), index.h("div", { key: 'c93c83abb8e17a5cb9c1bd53b2e1239ef50c7bf4', class: "corner corner-tl" }), index.h("div", { key: '81ca7cf2aab7026e851bd226843a6db5807315d5', class: "corner corner-tr" }), index.h("div", { key: 'c451fe226ac15023ee9799443060f1da620cb3b3', class: "corner corner-bl" }), index.h("div", { key: '7c3e2b2a21bd37144fe6b4d5df67df625dc12103', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("div", { key: '74ab171b64bdf0e1269845b4fcd9bf8e2caf891d', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("button", { key: '2b2b9387ce8b023acf0d65c7f7b3480211f7cb2d', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")))), this.isCapturing && (index.h("div", { key: 'eabd88499f52098f79e434afcce73acb2727c411', class: "capture-animation" })), this.showFlipAnimation && (index.h("div", { key: '9affe6040a39260747db98db2b68a103fb719fbb', class: "flip-animation" }, index.h("div", { key: '8b25f3688a16f4b070664237a093122a6720edfb', class: "id-card-icon" }), index.h("div", { key: '805b11cfb4d06a25e02370b06f6cf15f0f0cf6b5', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (index.h("div", { key: 'cba337b6fef8b919425566c0c9c5de797d42c4c8', class: "success-animation" }, index.h("div", { key: '4a88df3f9285757b489b030ba985d720a8a3badf', class: "check-icon" }), index.h("div", { key: 'a0bdd89c2c6274330ba66a6b6bba86ab6c725979', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (index.h("div", { key: '564fc1333b0fb69102e26ac1da4e77786a9bc7a3', class: "loading-overlay" }, index.h("div", { key: '283e4a6315a39b26203e19a13f35389bc1870a0f', class: "loading-spinner" }), index.h("div", { key: '7e4f00a1fcee1bbf29d74c8be35a72aba2c1041a', class: "loading-text" }, this.statusMessage))), index.h("div", { key: '6cbe1fea1c4a7d3cb25cd34ee04becb5fa538dfd', class: "watermark" }, index.h("img", { key: '1bd4157b7f74753570ddf48682acf419a6de03ea', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
918
+ }
919
+ };
920
+ JaakStamps.style = myComponentCss;
921
+
922
+ exports.jaak_stamps = JaakStamps;
923
+ //# sourceMappingURL=jaak-stamps.entry.cjs.js.map
924
+
925
+ //# sourceMappingURL=jaak-stamps.cjs.entry.js.map