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