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