@jaak.ai/stamps 2.0.0-beta.2 → 2.0.0-dev.17

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.
@@ -3,11 +3,7 @@ export class JaakStamps {
3
3
  el;
4
4
  debug = false;
5
5
  alignmentTolerance = 10; // Tolerancia en píxeles para considerar un lado alineado (escalado para 320x320)
6
- maskSize = 90; // Porcentaje del video que ocupará la máscara (default 90%)
7
- cropMargin = 0; // Margen en píxeles para el recorte del documento (default 0)
8
- useDocumentClassification = false; // Habilita la clasificación automática de documentos para determinar si solicitar reverso
9
6
  captureCompleted;
10
- isReady;
11
7
  isVideoActive = false;
12
8
  statusMessage = 'Presione el botón para activar la cámara';
13
9
  statusColor = '#aaa';
@@ -30,7 +26,6 @@ export class JaakStamps {
30
26
  isDetectionPaused = false;
31
27
  isLoading = false;
32
28
  isModelPreloaded = false;
33
- isMaskReady = false;
34
29
  videoRef;
35
30
  canvasRef;
36
31
  session;
@@ -39,8 +34,6 @@ export class JaakStamps {
39
34
  animationId;
40
35
  hasScreenshotTaken = false;
41
36
  lastDetectedBox;
42
- mobileNetSession;
43
- mobileNetClassMap;
44
37
  // Performance optimization properties
45
38
  frameSkipCounter = 0;
46
39
  FRAME_SKIP = 2; // Process every 3rd frame (reduces CPU by ~66%)
@@ -53,35 +46,16 @@ export class JaakStamps {
53
46
  preprocessCtx;
54
47
  captureCanvas;
55
48
  captureCtx;
56
- MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v1.onnx";
57
- MOBILENET_MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx";
58
- MOBILENET_CLASSES_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";
49
+ MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/detector-nano.onnx";
59
50
  INPUT_SIZE = 320;
60
51
  CONFIDENCE_THRESHOLD = 0.6;
61
- // ISO/IEC 7810 ID-1 standard dimensions (85.60mm x 53.98mm)
62
- ID1_ASPECT_RATIO = 85.60 / 53.98; // 1.5863320574...
52
+ MASK_WIDTH = 280;
53
+ MASK_HEIGHT = 176;
63
54
  debugLog(...args) {
64
55
  if (this.debug) {
65
56
  console.log(...args);
66
57
  }
67
58
  }
68
- validateMaskSize() {
69
- if (this.maskSize < 50 || this.maskSize > 100) {
70
- console.warn(`maskSize debe estar entre 50 y 100. Valor actual: ${this.maskSize}. Usando valor por defecto: 90`);
71
- this.maskSize = 90;
72
- }
73
- }
74
- validateCropMargin() {
75
- if (this.cropMargin < 0 || this.cropMargin > 100) {
76
- console.warn(`cropMargin debe estar entre 0 y 100. Valor actual: ${this.cropMargin}. Usando valor por defecto: 0`);
77
- this.cropMargin = 0;
78
- }
79
- }
80
- emitReadyEvent() {
81
- const isDocumentReady = !!window.ort && this.isModelPreloaded;
82
- this.isReady.emit(isDocumentReady);
83
- this.debugLog('🟢 isReady event emitted:', isDocumentReady);
84
- }
85
59
  isRearCamera(stream) {
86
60
  const videoTrack = stream.getVideoTracks()[0];
87
61
  if (!videoTrack)
@@ -90,109 +64,13 @@ export class JaakStamps {
90
64
  return settings.facingMode === 'environment';
91
65
  }
92
66
  async componentDidLoad() {
93
- this.validateMaskSize();
94
- this.validateCropMargin();
95
67
  if (!window.ort) {
96
68
  const script = document.createElement('script');
97
69
  script.src = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js';
98
70
  document.head.appendChild(script);
99
- // Wait for ONNX runtime to load before emitting ready event
100
- script.onload = () => {
101
- this.emitReadyEvent();
102
- };
103
- }
104
- else {
105
- // ONNX runtime already loaded
106
- this.emitReadyEvent();
107
71
  }
108
72
  // Initialize canvas pool for better performance
109
73
  this.initializeCanvasPool();
110
- this.setupResizeObserver();
111
- }
112
- setupResizeObserver() {
113
- if ('ResizeObserver' in window && this.canvasRef) {
114
- const resizeObserver = new ResizeObserver(() => {
115
- this.handleResize();
116
- });
117
- resizeObserver.observe(this.canvasRef.parentElement);
118
- }
119
- }
120
- handleResize() {
121
- if (this.canvasRef) {
122
- const container = this.canvasRef.parentElement;
123
- const rect = container.getBoundingClientRect();
124
- // Set canvas size to match container
125
- this.canvasRef.width = rect.width;
126
- this.canvasRef.height = rect.height;
127
- // Update mask positioning based on container and video dimensions
128
- this.updateMaskDimensions(rect);
129
- this.debugLog('📐 Canvas resized:', { width: rect.width, height: rect.height });
130
- }
131
- }
132
- updateMaskDimensions(containerRect) {
133
- if (!this.videoRef)
134
- return;
135
- const videoWidth = this.videoRef.videoWidth;
136
- const videoHeight = this.videoRef.videoHeight;
137
- if (videoWidth === 0 || videoHeight === 0)
138
- return;
139
- // Calculate video aspect ratio and container aspect ratio
140
- const videoAspectRatio = videoWidth / videoHeight;
141
- const containerAspectRatio = containerRect.width / containerRect.height;
142
- // Determine how video fits in container (letterboxed or pillarboxed)
143
- let displayedVideoWidth, displayedVideoHeight;
144
- let videoOffsetX = 0, videoOffsetY = 0;
145
- if (videoAspectRatio > containerAspectRatio) {
146
- // Video is wider - letterboxed (black bars top/bottom)
147
- displayedVideoWidth = containerRect.width;
148
- displayedVideoHeight = containerRect.width / videoAspectRatio;
149
- videoOffsetY = (containerRect.height - displayedVideoHeight) / 2;
150
- }
151
- else {
152
- // Video is taller - pillarboxed (black bars left/right)
153
- displayedVideoHeight = containerRect.height;
154
- displayedVideoWidth = containerRect.height * videoAspectRatio;
155
- videoOffsetX = (containerRect.width - displayedVideoWidth) / 2;
156
- }
157
- // Calculate maximum possible mask size while preserving exact ID-1 aspect ratio
158
- // Determine the limiting dimension based on video orientation and ID-1 proportions
159
- // Calculate what would be the max width if limited by video height
160
- const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
161
- let maskWidthInVideo, maskHeightInVideo;
162
- const sizeRatio = this.maskSize / 100;
163
- if (maxWidthByHeight <= displayedVideoWidth) {
164
- // Video height is the limiting factor
165
- maskHeightInVideo = displayedVideoHeight * sizeRatio;
166
- maskWidthInVideo = maskHeightInVideo * this.ID1_ASPECT_RATIO;
167
- }
168
- else {
169
- // Video width is the limiting factor
170
- maskWidthInVideo = displayedVideoWidth * sizeRatio;
171
- maskHeightInVideo = maskWidthInVideo / this.ID1_ASPECT_RATIO;
172
- }
173
- // Convert to percentages of the container
174
- const maskWidthPercent = (maskWidthInVideo / containerRect.width) * 100;
175
- const maskHeightPercent = (maskHeightInVideo / containerRect.height) * 100;
176
- // Calculate the center position of the displayed video area
177
- const videoCenterX = videoOffsetX + (displayedVideoWidth / 2);
178
- const videoCenterY = videoOffsetY + (displayedVideoHeight / 2);
179
- // Convert to percentages of the container
180
- const videoCenterXPercent = (videoCenterX / containerRect.width) * 100;
181
- const videoCenterYPercent = (videoCenterY / containerRect.height) * 100;
182
- // Update CSS custom properties for mask sizing and positioning
183
- this.el.style.setProperty('--mask-width', `${maskWidthPercent}%`);
184
- this.el.style.setProperty('--mask-height', `${maskHeightPercent}%`);
185
- this.el.style.setProperty('--mask-center-x', `${videoCenterXPercent}%`);
186
- this.el.style.setProperty('--mask-center-y', `${videoCenterYPercent}%`);
187
- // Mark mask as ready now that dimensions are calculated
188
- this.isMaskReady = true;
189
- this.debugLog('🎯 Mask dimensions updated:', {
190
- video: { width: videoWidth, height: videoHeight },
191
- displayed: { width: displayedVideoWidth, height: displayedVideoHeight },
192
- mask: { widthPercent: maskWidthPercent, heightPercent: maskHeightPercent },
193
- center: { x: videoCenterXPercent, y: videoCenterYPercent },
194
- offset: { x: videoOffsetX, y: videoOffsetY }
195
- });
196
74
  }
197
75
  initializeCanvasPool() {
198
76
  // Preprocess canvas - reused for every inference
@@ -261,29 +139,24 @@ export class JaakStamps {
261
139
  }
262
140
  try {
263
141
  this.isLoading = true;
264
- this.statusMessage = "Precargando modelos...";
142
+ this.statusMessage = "Precargando modelo de detección...";
265
143
  this.statusColor = "#007bff";
266
144
  const modelPath = this.MODEL_PATH;
267
- this.debugLog('🤖 Preloading detection model:', modelPath);
145
+ this.debugLog('🤖 Preloading model:', modelPath);
268
146
  // Configure ONNX Runtime with device-specific optimizations
269
147
  const sessionOptions = this.getSessionOptions();
270
148
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
271
- // Preload MobileNet model and classes only if classification is enabled
272
- if (this.useDocumentClassification) {
273
- await this.loadMobileNetModel();
274
- }
275
149
  this.isModelPreloaded = true;
276
150
  this.isLoading = false;
277
- this.statusMessage = "Modelos precargados. Listo para comenzar detección";
151
+ this.statusMessage = "Modelo precargado. Listo para comenzar detección";
278
152
  this.statusColor = "#28a745";
279
- this.emitReadyEvent();
280
- this.debugLog(' Models preloaded successfully');
281
- return { success: true, message: 'Models preloaded successfully' };
153
+ this.debugLog('✅ Model preloaded successfully');
154
+ return { success: true, message: 'Model preloaded successfully' };
282
155
  }
283
156
  catch (error) {
284
- this.debugLog('❌ Error preloading models:', error);
157
+ this.debugLog('❌ Error preloading model:', error);
285
158
  this.isLoading = false;
286
- this.statusMessage = "Error al precargar los modelos";
159
+ this.statusMessage = "Error al precargar el modelo";
287
160
  this.statusColor = "#ff6b6b";
288
161
  return { success: false, error: error.message };
289
162
  }
@@ -293,80 +166,6 @@ export class JaakStamps {
293
166
  this.completeProcess(true);
294
167
  }
295
168
  }
296
- async loadMobileNetModel() {
297
- try {
298
- this.debugLog('🤖 Loading MobileNet model...');
299
- // Load class map
300
- const classResponse = await fetch(this.MOBILENET_CLASSES_PATH);
301
- if (!classResponse.ok) {
302
- throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`);
303
- }
304
- this.mobileNetClassMap = await classResponse.json();
305
- this.debugLog('📋 MobileNet classes loaded:', this.mobileNetClassMap);
306
- // Load model
307
- const sessionOptions = this.getSessionOptions();
308
- this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, sessionOptions);
309
- this.debugLog('✅ MobileNet model loaded successfully');
310
- }
311
- catch (error) {
312
- this.debugLog('❌ Error loading MobileNet model:', error);
313
- throw error;
314
- }
315
- }
316
- preprocessMobileNet(canvas) {
317
- // Create a temporary canvas for MobileNet preprocessing (224x224)
318
- const tempCanvas = document.createElement('canvas');
319
- tempCanvas.width = 224;
320
- tempCanvas.height = 224;
321
- const tempCtx = tempCanvas.getContext('2d');
322
- // Draw the cropped image onto the 224x224 canvas
323
- tempCtx.drawImage(canvas, 0, 0, 224, 224);
324
- // Get image data and preprocess for MobileNet
325
- const imageData = tempCtx.getImageData(0, 0, 224, 224);
326
- const data = imageData.data;
327
- const hw = 224 * 224;
328
- const arr = new Float32Array(3 * hw);
329
- // Normalize pixels: (pixel/255 - 0.5) / 0.5 = (pixel - 127.5) / 127.5
330
- for (let i = 0; i < hw; i++) {
331
- arr[i] = (data[i * 4 + 0] / 255 - 0.5) / 0.5; // R
332
- arr[hw + i] = (data[i * 4 + 1] / 255 - 0.5) / 0.5; // G
333
- arr[2 * hw + i] = (data[i * 4 + 2] / 255 - 0.5) / 0.5; // B
334
- }
335
- return new window.ort.Tensor('float32', arr, [1, 3, 224, 224]);
336
- }
337
- async classifyDocument(canvas) {
338
- if (!this.mobileNetSession || !this.mobileNetClassMap) {
339
- this.debugLog('⚠️ MobileNet model not loaded');
340
- return null;
341
- }
342
- try {
343
- this.debugLog('🔍 Classifying document...');
344
- // Preprocess image for MobileNet
345
- const inputTensor = this.preprocessMobileNet(canvas);
346
- // Run inference
347
- const feeds = { input: inputTensor };
348
- const results = await this.mobileNetSession.run(feeds);
349
- const output = results[Object.keys(results)[0]].data;
350
- // Find the class with highest confidence
351
- const maxIdx = output.reduce((bestIdx, val, idx, arr) => val > arr[bestIdx] ? idx : bestIdx, 0);
352
- const confidence = output[maxIdx];
353
- const className = this.mobileNetClassMap[maxIdx.toString()] || "unknown";
354
- this.debugLog('📄 Document classification result:', {
355
- class: className,
356
- confidence: confidence.toFixed(3),
357
- classIndex: maxIdx
358
- });
359
- return {
360
- class: className,
361
- confidence: confidence,
362
- classIndex: maxIdx
363
- };
364
- }
365
- catch (error) {
366
- this.debugLog('❌ Error classifying document:', error);
367
- return null;
368
- }
369
- }
370
169
  cleanup() {
371
170
  if (this.animationId) {
372
171
  cancelAnimationFrame(this.animationId);
@@ -394,73 +193,22 @@ export class JaakStamps {
394
193
  this.captureCtx = undefined;
395
194
  this.captureCanvas = undefined;
396
195
  }
397
- // Disposed ONNX sessions
196
+ // Disposed ONNX session
398
197
  if (this.session) {
399
198
  this.session.release?.();
400
199
  this.session = undefined;
401
200
  }
402
- if (this.mobileNetSession) {
403
- this.mobileNetSession.release?.();
404
- this.mobileNetSession = undefined;
405
- }
406
- this.mobileNetClassMap = undefined;
407
201
  this.isModelPreloaded = false;
408
202
  this.debugLog('🧹 Canvas pool cleaned up');
409
203
  }
410
- async getMaxResolution() {
411
- try {
412
- // Primero obtén un stream básico para acceder a las capacidades
413
- const tempStream = await navigator.mediaDevices.getUserMedia({
414
- video: { facingMode: "environment" }
415
- });
416
- const videoTrack = tempStream.getVideoTracks()[0];
417
- const capabilities = videoTrack.getCapabilities();
418
- // Detener el stream temporal
419
- tempStream.getTracks().forEach(track => track.stop());
420
- // Construir restricciones con resolución optimizada para tablets
421
- const constraints = {
422
- facingMode: "environment"
423
- };
424
- if (capabilities.width && capabilities.height) {
425
- // Limitar resolución máxima para tablets para evitar problemas de rendimiento
426
- const maxWidth = Math.min(capabilities.width.max, 1920);
427
- const maxHeight = Math.min(capabilities.height.max, 1080);
428
- // Para tablets, usar resolución moderada en lugar de máxima
429
- const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
430
- if (isTablet) {
431
- constraints.width = { ideal: Math.min(maxWidth, 1280) };
432
- constraints.height = { ideal: Math.min(maxHeight, 720) };
433
- }
434
- else {
435
- constraints.width = { ideal: maxWidth };
436
- constraints.height = { ideal: maxHeight };
437
- }
438
- this.debugLog('📐 Resolution capabilities:', {
439
- maxWidth: capabilities.width.max,
440
- maxHeight: capabilities.height.max,
441
- selectedWidth: constraints.width.ideal,
442
- selectedHeight: constraints.height.ideal,
443
- isTablet
444
- });
445
- }
446
- return constraints;
447
- }
448
- catch (err) {
449
- this.debugLog('⚠️ Could not get capabilities, using fallback');
450
- // Fallback optimizado para tablets
451
- const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
452
- return {
453
- facingMode: "environment",
454
- width: { ideal: isTablet ? 1280 : 1920 },
455
- height: { ideal: isTablet ? 720 : 1080 }
456
- };
457
- }
458
- }
459
204
  async setupCamera() {
460
205
  try {
461
- const constraints = await this.getMaxResolution();
462
206
  const stream = await navigator.mediaDevices.getUserMedia({
463
- video: constraints,
207
+ video: {
208
+ width: { exact: 640 },
209
+ height: { exact: 640 },
210
+ facingMode: "environment"
211
+ },
464
212
  audio: false
465
213
  });
466
214
  if (this.videoRef) {
@@ -475,12 +223,6 @@ export class JaakStamps {
475
223
  this.videoRef.onloadedmetadata = async () => {
476
224
  await this.videoRef.play();
477
225
  this.isVideoActive = true;
478
- // Update mask dimensions once video is loaded
479
- if (this.canvasRef) {
480
- const container = this.canvasRef.parentElement;
481
- const rect = container.getBoundingClientRect();
482
- this.updateMaskDimensions(rect);
483
- }
484
226
  resolve();
485
227
  };
486
228
  });
@@ -534,22 +276,17 @@ export class JaakStamps {
534
276
  // Check if model is already preloaded
535
277
  if (!this.session) {
536
278
  this.isLoading = true;
537
- this.statusMessage = "Cargando modelos...";
279
+ this.statusMessage = "Cargando modelo de detección...";
538
280
  this.statusColor = "#007bff";
539
281
  const modelPath = this.MODEL_PATH;
540
- this.debugLog('🤖 Loading detection model:', modelPath);
282
+ this.debugLog('🤖 Loading model:', modelPath);
541
283
  const sessionOptions = this.getSessionOptions();
542
284
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
543
- // Load MobileNet model if classification is enabled and not already loaded
544
- if (this.useDocumentClassification && !this.mobileNetSession) {
545
- await this.loadMobileNetModel();
546
- }
547
285
  this.isModelPreloaded = true;
548
- this.emitReadyEvent();
549
286
  }
550
287
  else {
551
- this.debugLog('🚀 Using preloaded models');
552
- this.statusMessage = "Usando modelos precargados...";
288
+ this.debugLog('🚀 Using preloaded model');
289
+ this.statusMessage = "Usando modelo precargado...";
553
290
  this.statusColor = "#007bff";
554
291
  }
555
292
  this.statusMessage = "Configurando cámara...";
@@ -662,58 +399,13 @@ export class JaakStamps {
662
399
  return isCentered && isGoodSize;
663
400
  }
664
401
  checkSideAlignment(box) {
665
- if (!this.videoRef)
666
- return { top: false, right: false, bottom: false, left: false };
667
- // Get video dimensions to calculate actual mask boundaries in model space
668
- const videoWidth = this.videoRef.videoWidth;
669
- const videoHeight = this.videoRef.videoHeight;
670
- if (videoWidth === 0 || videoHeight === 0) {
671
- return { top: false, right: false, bottom: false, left: false };
672
- }
673
- // Calculate video aspect ratio
674
- const videoAspectRatio = videoWidth / videoHeight;
675
- // The model sees video stretched to 320x320, but we need to calculate where
676
- // the mask should be in this distorted space to match the visual mask
677
- // In the visual display, we calculate mask size based on the limiting dimension
678
- // We need to replicate this logic but account for the distortion in model space
679
- // Calculate the "display" dimensions (what the visual mask calculations use)
680
- const containerAspectRatio = 1; // Assume square container for simplicity
681
- let displayedVideoWidth, displayedVideoHeight;
682
- if (videoAspectRatio > containerAspectRatio) {
683
- // Video is wider - letterboxed in display
684
- displayedVideoWidth = this.INPUT_SIZE;
685
- displayedVideoHeight = this.INPUT_SIZE / videoAspectRatio;
686
- }
687
- else {
688
- // Video is taller - pillarboxed in display
689
- displayedVideoHeight = this.INPUT_SIZE;
690
- displayedVideoWidth = this.INPUT_SIZE * videoAspectRatio;
691
- }
692
- // Calculate mask dimensions using the same logic as updateMaskDimensions
693
- const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
694
- let visualMaskWidth, visualMaskHeight;
695
- const sizeRatio = this.maskSize / 100;
696
- if (maxWidthByHeight <= displayedVideoWidth) {
697
- // Video height is the limiting factor
698
- visualMaskHeight = displayedVideoHeight * sizeRatio;
699
- visualMaskWidth = visualMaskHeight * this.ID1_ASPECT_RATIO;
700
- }
701
- else {
702
- // Video width is the limiting factor
703
- visualMaskWidth = displayedVideoWidth * sizeRatio;
704
- visualMaskHeight = visualMaskWidth / this.ID1_ASPECT_RATIO;
705
- }
706
- // Now map these visual mask dimensions to the distorted model space
707
- // The model stretches video to 320x320, so we need to apply the inverse transformation
708
- const modelMaskWidth = visualMaskWidth * (this.INPUT_SIZE / displayedVideoWidth);
709
- const modelMaskHeight = visualMaskHeight * (this.INPUT_SIZE / displayedVideoHeight);
710
- // Calculate mask boundaries in model coordinate system (always centered in 320x320)
402
+ // Obtener las coordenadas del marco de referencia (máscara)
711
403
  const maskCenterX = this.INPUT_SIZE / 2;
712
404
  const maskCenterY = this.INPUT_SIZE / 2;
713
- const maskLeft = maskCenterX - (modelMaskWidth / 2);
714
- const maskRight = maskCenterX + (modelMaskWidth / 2);
715
- const maskTop = maskCenterY - (modelMaskHeight / 2);
716
- const maskBottom = maskCenterY + (modelMaskHeight / 2);
405
+ const maskLeft = maskCenterX - (this.MASK_WIDTH / 2);
406
+ const maskRight = maskCenterX + (this.MASK_WIDTH / 2);
407
+ const maskTop = maskCenterY - (this.MASK_HEIGHT / 2);
408
+ const maskBottom = maskCenterY + (this.MASK_HEIGHT / 2);
717
409
  // Obtener las coordenadas del documento detectado
718
410
  let docLeft = box.x;
719
411
  let docRight = box.x + box.w;
@@ -768,9 +460,7 @@ export class JaakStamps {
768
460
  corners?.forEach(corner => corner.classList.add('perfect-match'));
769
461
  if (!this.hasScreenshotTaken) {
770
462
  this.lastDetectedBox = bestBox;
771
- this.takeScreenshot().catch(error => {
772
- this.debugLog('❌ Error taking screenshot:', error);
773
- });
463
+ this.takeScreenshot();
774
464
  this.hasScreenshotTaken = true;
775
465
  // Reset para permitir segunda captura
776
466
  setTimeout(() => {
@@ -812,48 +502,15 @@ export class JaakStamps {
812
502
  }
813
503
  }
814
504
  drawDetections(ctx, boxes) {
815
- if (!this.videoRef)
816
- return;
817
- // Get video and container dimensions
818
- const videoWidth = this.videoRef.videoWidth;
819
- const videoHeight = this.videoRef.videoHeight;
820
- const containerWidth = this.canvasRef.width;
821
- const containerHeight = this.canvasRef.height;
822
- if (videoWidth === 0 || videoHeight === 0)
823
- return;
824
- // Calculate video aspect ratio and container aspect ratio
825
- const videoAspectRatio = videoWidth / videoHeight;
826
- const containerAspectRatio = containerWidth / containerHeight;
827
- // Determine how video fits in container (same logic as updateMaskDimensions)
828
- let displayedVideoWidth, displayedVideoHeight;
829
- let videoOffsetX = 0, videoOffsetY = 0;
830
- if (videoAspectRatio > containerAspectRatio) {
831
- // Video is wider - letterboxed (black bars top/bottom)
832
- displayedVideoWidth = containerWidth;
833
- displayedVideoHeight = containerWidth / videoAspectRatio;
834
- videoOffsetY = (containerHeight - displayedVideoHeight) / 2;
835
- }
836
- else {
837
- // Video is taller - pillarboxed (black bars left/right)
838
- displayedVideoHeight = containerHeight;
839
- displayedVideoWidth = containerHeight * videoAspectRatio;
840
- videoOffsetX = (containerWidth - displayedVideoWidth) / 2;
841
- }
842
- // Scale factor from model coordinates (320x320) to displayed video area
843
- const scaleX = displayedVideoWidth / this.INPUT_SIZE;
844
- const scaleY = displayedVideoHeight / this.INPUT_SIZE;
505
+ // Scale factor to convert from model coordinates (320x320) to canvas coordinates (640x640)
506
+ const scale = this.canvasRef.width / this.INPUT_SIZE;
845
507
  boxes.forEach(det => {
846
- // Convert model coordinates to displayed video coordinates
847
- const x = det.x * scaleX + videoOffsetX;
848
- const y = det.y * scaleY + videoOffsetY;
849
- const w = det.w * scaleX;
850
- const h = det.h * scaleY;
851
508
  ctx.strokeStyle = "#32406C";
852
509
  ctx.lineWidth = 2;
853
- ctx.strokeRect(x, y, w, h);
510
+ ctx.strokeRect(det.x * scale, det.y * scale, det.w * scale, det.h * scale);
854
511
  });
855
512
  }
856
- async takeScreenshot() {
513
+ takeScreenshot() {
857
514
  if (!this.videoRef || !this.lastDetectedBox)
858
515
  return;
859
516
  // Activar animación
@@ -869,10 +526,10 @@ export class JaakStamps {
869
526
  // Calcular las coordenadas de recorte basadas en la detección
870
527
  const scaleX = this.videoRef.videoWidth / this.INPUT_SIZE;
871
528
  const scaleY = this.videoRef.videoHeight / this.INPUT_SIZE;
872
- const cropX = Math.max(0, (this.lastDetectedBox.x * scaleX) - this.cropMargin);
873
- const cropY = Math.max(0, (this.lastDetectedBox.y * scaleY) - this.cropMargin);
874
- const cropWidth = Math.min((this.lastDetectedBox.w * scaleX) + (2 * this.cropMargin), this.videoRef.videoWidth - cropX);
875
- const cropHeight = Math.min((this.lastDetectedBox.h * scaleY) + (2 * this.cropMargin), this.videoRef.videoHeight - cropY);
529
+ const cropX = Math.max(0, this.lastDetectedBox.x * scaleX);
530
+ const cropY = Math.max(0, this.lastDetectedBox.y * scaleY);
531
+ const cropWidth = Math.min(this.lastDetectedBox.w * scaleX, this.videoRef.videoWidth - cropX);
532
+ const cropHeight = Math.min(this.lastDetectedBox.h * scaleY, this.videoRef.videoHeight - cropY);
876
533
  // OPTIMIZATION: Create temporary canvas only for cropped version
877
534
  // (We reuse main capture canvas for full frame)
878
535
  const croppedCanvas = document.createElement('canvas');
@@ -887,29 +544,6 @@ export class JaakStamps {
887
544
  // Captura del frente usando canvas reutilizado
888
545
  this.capturedFullFrame = this.captureCanvas.toDataURL('image/png');
889
546
  this.capturedCroppedId = croppedCanvas.toDataURL('image/png');
890
- // Check if document classification is enabled
891
- if (this.useDocumentClassification) {
892
- // Load MobileNet model if not loaded yet (lazy loading)
893
- if (!this.mobileNetSession) {
894
- try {
895
- await this.loadMobileNetModel();
896
- }
897
- catch (error) {
898
- this.debugLog('⚠️ Failed to load classification model, continuing without classification:', error);
899
- }
900
- }
901
- // Classify the cropped document if model is available
902
- if (this.mobileNetSession) {
903
- const classification = await this.classifyDocument(croppedCanvas);
904
- if (classification && classification.class === 'passport') {
905
- // If it's a passport, skip back capture since passports don't have a back side
906
- this.debugLog('📄 Passport detected - skipping back capture');
907
- this.completeProcess(true);
908
- return;
909
- }
910
- }
911
- }
912
- // For other IDs, continue with normal flow (back capture)
913
547
  this.captureStep = 'back';
914
548
  this.statusMessage = "Voltee la identificación y muestre la parte trasera";
915
549
  this.statusColor = "#007bff";
@@ -1039,7 +673,7 @@ export class JaakStamps {
1039
673
  this.cleanup();
1040
674
  }
1041
675
  render() {
1042
- return (h("div", { key: '42591479495df221b101555198a23288d7d765b0', class: "detector-container" }, h("div", { key: '2b9ab48572aa2fb5542b8a8dc1b70a0f2a6eca89', class: "video-container" }, h("video", { key: 'b9e84f2eb67fa6f7f158e19b90871a1eebee624b', ref: el => this.videoRef = el, autoplay: true, muted: true, playsinline: true, class: this.shouldMirrorVideo ? 'mirror' : '', style: { display: this.isVideoActive ? 'block' : 'none' } }), h("canvas", { key: 'a82fc4826e220e696799b07b3510456f174a6628', ref: el => this.canvasRef = el, class: this.shouldMirrorVideo ? 'mirror' : '' }), this.isMaskReady && (h("div", { key: '9b3b838f99030e3dfa760fa0dd7c89ff24f26ed9', class: "overlay-mask" }, h("div", { key: 'f6a3b1ac2f12c1fb081f6b5eb853e627040396f4', class: "card-outline" }, h("div", { key: '6626259249ac5e0fd6ba665ab802af1ac2f9fc17', class: "side side-top" }), h("div", { key: '7a3195c96b2406b40b122f4267c2a251614cdede', class: "side side-right" }), h("div", { key: 'ece78305cfb083ada1d44de1d7d5226730879cc3', class: "side side-bottom" }), h("div", { key: '107468c583bbb01dd46c36c096e49be8e0b574ba', class: "side side-left" }), h("div", { key: 'c590f13b80c5e37c0ac0c68cfc2e2904b4345ebc', class: "corner corner-tl" }), h("div", { key: 'ab1e5aab179068ad1bc7b58ef3628d9618a877a8', class: "corner corner-tr" }), h("div", { key: '3a1db6cf1105bd3a2dfe7d4b998e79f6e40625ec', class: "corner corner-bl" }), h("div", { key: '5f9bc4e4557e5539335894160dccbaa2a6d6ac2d', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (h("div", { key: '8226d6721b0ae800f935e978a93113bd3b99656a', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (h("button", { key: '16cec7ca4a80ba0db1ace768826da17063eddb3e', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")))), this.isCapturing && (h("div", { key: 'bfdca0059eb50d37a77e8e43ef963ba7ed953edf', class: "capture-animation" })), this.showFlipAnimation && (h("div", { key: 'a1ad4b4f884d7d9f6090f148ddd6df19250073dd', class: "flip-animation" }, h("div", { key: 'e159ce385824dc049a6e9409d3747105c6f0a08e', class: "id-card-icon" }), h("div", { key: '6fcff650a3c7fdb16f8d327750e06055b9a93d0d', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (h("div", { key: 'c4b76ecb19c65969676e5156689c2c0b1c9a584e', class: "success-animation" }, h("div", { key: '12203a8fe7ee878089b3dda1d1142cde5489eed0', class: "check-icon" }), h("div", { key: 'a2d41c8944873d33106994b8d56c3ee1ee1ae9fc', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (h("div", { key: 'a155cd999fa40c35fa7b391cde7c1026edb250a7', class: "loading-overlay" }, h("div", { key: 'ccba76c5d4a472158c28bc564ba95bd65829b58d', class: "loading-spinner" }), h("div", { key: '23168f9bdcf4e993539288ff5703acaed13bb16a', class: "loading-text" }, this.statusMessage))), h("div", { key: '0107b82ad19726c1bab131e17892a46b04e08cfd', class: "watermark" }, h("img", { key: 'ad8831a6f77fa61805f22e3a27f5c5619ac1cc0e', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
676
+ return (h("div", { key: 'a1036d3867a4f5c40a942e47a30992a6c56e5240', class: "detector-container" }, h("div", { key: 'dada4edb4cc690e4e73d616e8eb22fa8fb6b2817', class: "video-container" }, h("video", { key: '16b43f5efdd0c32dbfab49a86e6904baabfdc220', ref: el => this.videoRef = el, width: "640", height: "640", autoplay: true, muted: true, playsinline: true, class: this.shouldMirrorVideo ? 'mirror' : '', style: { display: this.isVideoActive ? 'block' : 'none' } }), h("canvas", { key: 'e89cf0292df3bef51d9e9ed650b4f68493506314', ref: el => this.canvasRef = el, width: "640", height: "640", class: this.shouldMirrorVideo ? 'mirror' : '' }), h("div", { key: '3740295495466519be1b4b95891dd06d8272a7d6', class: "overlay-mask" }, h("div", { key: 'ac61b03420ae83d06ec8e5095a11665a8b5a4cd1', class: "card-outline" }, h("div", { key: '7190506e4803ccde1f6c95e6238b05271e7e01a5', class: "side side-top" }), h("div", { key: 'e383f023305021cdd5a02ccaf6a2bb2c775b28be', class: "side side-right" }), h("div", { key: '733f572b80c5f0050c21aa4cf5efd5b499859c23', class: "side side-bottom" }), h("div", { key: 'dbf175597a0d0790b9cc54f737693e418f1500f2', class: "side side-left" }), h("div", { key: '657375f468fc83444e6157c5308fca7237e85f22', class: "corner corner-tl" }), h("div", { key: '0491bf2ed49322cba5220a82016bb9a77c102386', class: "corner corner-tr" }), h("div", { key: 'eb7d153a47dfb1f0c98229752aabfe71181d6c3b', class: "corner corner-bl" }), h("div", { key: '7d57726a70864f9c2590395f6dc89918558fbc87', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (h("div", { key: '8deff6975766142bae69fb7596f0097b1319bc5f', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (h("button", { key: '471fae3b2c48302d474a7e7186cbe21e1260288f', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso"))), this.isCapturing && (h("div", { key: '83fa0133b072f982c9d861632525a64068271833', class: "capture-animation" })), this.showFlipAnimation && (h("div", { key: '0cdcabf20a263067a3fb120ec112a7c688eaece1', class: "flip-animation" }, h("div", { key: 'c7fd5c4211aa67cdc37be882617120cfb3afcfad', class: "id-card-icon" }), h("div", { key: '1c8e889d1de4867887fc25ac221b780154da59dd', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (h("div", { key: '7fcf315cb26c2c860d06dcdb7da6f58524ef4474', class: "success-animation" }, h("div", { key: '5ea1a6aa4368cd154189db166af531abe2e0029e', class: "check-icon" }), h("div", { key: 'deb064b437a664ea5dfdb9b3883ee83bc85b939e', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (h("div", { key: '7a28906555b0e5b891e1f8516a318ec540a83320', class: "loading-overlay" }, h("div", { key: '6f0778d156648405dd385f95c5e9bad0c4112eda', class: "loading-spinner" }), h("div", { key: 'b1cd4ddee0e282e8353bf8ed298fbd1c8498fb5e', class: "loading-text" }, this.statusMessage))), h("div", { key: '1e74b90a10ef2e2e71505160accb0ea83672c5de', class: "watermark" }, h("img", { key: '352fee0189ac25f59724e69e317b28859c86476e', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
1043
677
  }
1044
678
  static get is() { return "jaak-stamps"; }
1045
679
  static get encapsulation() { return "shadow"; }
@@ -1094,66 +728,6 @@ export class JaakStamps {
1094
728
  "setter": false,
1095
729
  "reflect": false,
1096
730
  "defaultValue": "10"
1097
- },
1098
- "maskSize": {
1099
- "type": "number",
1100
- "attribute": "mask-size",
1101
- "mutable": false,
1102
- "complexType": {
1103
- "original": "number",
1104
- "resolved": "number",
1105
- "references": {}
1106
- },
1107
- "required": false,
1108
- "optional": false,
1109
- "docs": {
1110
- "tags": [],
1111
- "text": ""
1112
- },
1113
- "getter": false,
1114
- "setter": false,
1115
- "reflect": false,
1116
- "defaultValue": "90"
1117
- },
1118
- "cropMargin": {
1119
- "type": "number",
1120
- "attribute": "crop-margin",
1121
- "mutable": false,
1122
- "complexType": {
1123
- "original": "number",
1124
- "resolved": "number",
1125
- "references": {}
1126
- },
1127
- "required": false,
1128
- "optional": false,
1129
- "docs": {
1130
- "tags": [],
1131
- "text": ""
1132
- },
1133
- "getter": false,
1134
- "setter": false,
1135
- "reflect": false,
1136
- "defaultValue": "0"
1137
- },
1138
- "useDocumentClassification": {
1139
- "type": "boolean",
1140
- "attribute": "use-document-classification",
1141
- "mutable": false,
1142
- "complexType": {
1143
- "original": "boolean",
1144
- "resolved": "boolean",
1145
- "references": {}
1146
- },
1147
- "required": false,
1148
- "optional": false,
1149
- "docs": {
1150
- "tags": [],
1151
- "text": ""
1152
- },
1153
- "getter": false,
1154
- "setter": false,
1155
- "reflect": false,
1156
- "defaultValue": "false"
1157
731
  }
1158
732
  };
1159
733
  }
@@ -1175,8 +749,7 @@ export class JaakStamps {
1175
749
  "sideAlignment": {},
1176
750
  "isDetectionPaused": {},
1177
751
  "isLoading": {},
1178
- "isModelPreloaded": {},
1179
- "isMaskReady": {}
752
+ "isModelPreloaded": {}
1180
753
  };
1181
754
  }
1182
755
  static get events() {
@@ -1195,21 +768,6 @@ export class JaakStamps {
1195
768
  "resolved": "any",
1196
769
  "references": {}
1197
770
  }
1198
- }, {
1199
- "method": "isReady",
1200
- "name": "isReady",
1201
- "bubbles": true,
1202
- "cancelable": true,
1203
- "composed": true,
1204
- "docs": {
1205
- "tags": [],
1206
- "text": ""
1207
- },
1208
- "complexType": {
1209
- "original": "boolean",
1210
- "resolved": "boolean",
1211
- "references": {}
1212
- }
1213
771
  }];
1214
772
  }
1215
773
  static get methods() {