@jaak.ai/stamps 2.0.0-beta.1 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,18 +1,18 @@
1
1
  # Jaak Stamps - Document Detector Web Component
2
2
 
3
- [![Built With Stencil](https://img.shields.io/badge/-Built%20With%20Stencil-16161d.svg?logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjIuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1MTIgNTEyOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI%2BCjxzdHlsZSB0eXBlPSJ0ZXh0L2NzcyI%2BCgkuc3Qwe2ZpbGw6I0ZGRkZGRjt9Cjwvc3R5bGU%2BCjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik00MjQuNywzNzMuOWMwLDM3LjYtNTUuMSw2OC42LTkyLjcsNjguNkgxODAuNGMtMzcuOSwwLTkyLjctMzAuNy05Mi43LTY4LjZ2LTMuNmgzMzYuOVYzNzMuOXoiLz4KPHBhdGggY2xhc3M9InN0MCIgZD0iTTQyNC43LDI5Mi4xSDE4MC40Yy0zNy42LDAtOTIuNy0zMS05Mi43LTY4LjZ2LTMuNkgzMzJjMzcuNiwwLDkyLjcsMzEsOTIuNyw2OC42VjI5Mi4xeiIvPgo8cGF0aCBjbGFzcz0ic3QwIiBkPSJNNDI0LjcsMTQxLjdIODcuN3YtMy42YzAtMzcuNiw1NC44LTY4LjYsOTIuNy02OC42SDMzMmMzNy45LDAsOTIuNywzMC43LDkyLjcsNjguNlYxNDEuN3oiLz4KPC9zdmc%2BCg%3D%3D&colorA=16161d&style=flat-square)](https://stenciljs.com)
4
-
5
3
  Un componente web para la detección y captura automática de documentos de identificación usando visión artificial y redes neuronales.
6
4
 
7
5
  ## Características
8
6
 
9
7
  - 📷 **Detección automática** de documentos de identificación en tiempo real
10
8
  - 🎯 **Guía visual** para posicionamiento óptimo del documento
11
- - 📋 **Captura doble cara** (frente y reverso) con opción de omitir reverso
9
+ - 🤖 **Clasificación inteligente** de documentos para determinar si requieren reverso
10
+ - 📋 **Captura adaptativa** - automáticamente detecta si el documento tiene reverso
12
11
  - 🖼 **Doble salida** para cada lado: imagen completa y recorte del documento
12
+ - ✂️ **Recorte configurable** con margen personalizable alrededor del documento
13
13
  - 🔧 **API programática** para control total del proceso
14
14
  - 📱 **Responsive** y compatible con dispositivos móviles
15
- - ⚡ **Optimización automática** usando ONNX Runtime Web
15
+ - ⚡ **Optimización automática** para mejor rendimiento
16
16
 
17
17
  ## Instalación
18
18
 
@@ -43,7 +43,7 @@ yarn add @jaak.ai/stamps
43
43
  <script type="module" src="https://unpkg.com/@jaak.ai/stamps/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js"></script>
44
44
  </head>
45
45
  <body>
46
- <jaak-stamps id="detector" debug="false"></jaak-stamps>
46
+ <jaak-stamps id="detector" debug="false" mask-size="90" crop-margin="10" use-document-classification="false"></jaak-stamps>
47
47
 
48
48
  <button onclick="startCapture()">Iniciar Captura</button>
49
49
  <button onclick="stopCapture()">Detener</button>
@@ -140,6 +140,9 @@ import { Component, ElementRef, ViewChild, OnInit } from '@angular/core';
140
140
  <jaak-stamps
141
141
  #detector
142
142
  [debug]="false"
143
+ [maskSize]="90"
144
+ [cropMargin]="10"
145
+ [useDocumentClassification]="false"
143
146
  (captureCompleted)="onCaptureCompleted($event)"
144
147
  (isReady)="onComponentReady($event)">
145
148
  </jaak-stamps>
@@ -241,7 +244,7 @@ import React, { useRef, useEffect, useImperativeHandle, forwardRef } from 'react
241
244
  // Importar el web component
242
245
  import '@jaak.ai/stamps/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js';
243
246
 
244
- const JaakStampsWrapper = forwardRef(({ debug = false, onCaptureCompleted, onIsReady }, ref) => {
247
+ const JaakStampsWrapper = forwardRef(({ debug = false, maskSize = 90, cropMargin = 0, useDocumentClassification = false, onCaptureCompleted, onIsReady }, ref) => {
245
248
  const elementRef = useRef(null);
246
249
 
247
250
  useImperativeHandle(ref, () => ({
@@ -285,6 +288,9 @@ const JaakStampsWrapper = forwardRef(({ debug = false, onCaptureCompleted, onIsR
285
288
  <jaak-stamps
286
289
  ref={elementRef}
287
290
  debug={debug}
291
+ mask-size={maskSize}
292
+ crop-margin={cropMargin}
293
+ use-document-classification={useDocumentClassification}
288
294
  />
289
295
  );
290
296
  });
@@ -364,6 +370,9 @@ function App() {
364
370
  <JaakStampsWrapper
365
371
  ref={detectorRef}
366
372
  debug={false}
373
+ maskSize={90}
374
+ cropMargin={10}
375
+ useDocumentClassification={false}
367
376
  onCaptureCompleted={handleCaptureCompleted}
368
377
  onIsReady={handleIsReady}
369
378
  />
@@ -435,6 +444,9 @@ export default App;
435
444
  |-----------|------|---------------|-------------|
436
445
  | `debug` | `boolean` | `false` | Activa el modo debug para mostrar información de depuración |
437
446
  | `alignmentTolerance` | `number` | `10` | Tolerancia en píxeles para considerar un lado alineado |
447
+ | `maskSize` | `number` | `90` | Porcentaje del video que ocupará la máscara de detección (50-100) |
448
+ | `cropMargin` | `number` | `0` | Margen en píxeles agregado al recorte del documento (0-100) |
449
+ | `useDocumentClassification` | `boolean` | `false` | Habilita la clasificación automática de documentos para determinar si solicitar reverso. Solo carga el modelo de clasificación cuando está habilitada. |
438
450
 
439
451
  ### Métodos Públicos
440
452
 
@@ -454,7 +466,7 @@ export default App;
454
466
  | Evento | Payload | Descripción |
455
467
  |--------|---------|-------------|
456
468
  | `captureCompleted` | `CapturedImages` | Se emite cuando se completa el proceso de captura |
457
- | `isReady` | `boolean` | Se emite cuando el componente está listo para comenzar la detección (modelo ONNX cargado) |
469
+ | `isReady` | `boolean` | Se emite cuando el componente está listo para comenzar la detección (modelos cargados) |
458
470
 
459
471
  ### Tipos de Datos
460
472
 
@@ -488,33 +500,76 @@ interface Status {
488
500
 
489
501
  ## Flujo de Trabajo
490
502
 
491
- ### Flujo Estándar
503
+ ### Flujo Estándar (useDocumentClassification = false)
492
504
  1. **Inicialización**: El componente se prepara para la detección
493
- 2. **Inicio de captura**: Se carga el modelo ONNX automáticamente al iniciar la detección
505
+ 2. **Inicio de captura**: Se carga automáticamente el modelo de detección
494
506
  3. **Captura del frente**: El usuario posiciona el documento y se captura automáticamente
495
- 4. **Captura del reverso**: Se solicita voltear el documento para capturar el reverso
496
- 5. **Completado**: Se emite el evento `captureCompleted` con todas las imágenes
507
+ 4. **Solicitud de reverso**: Siempre se solicita voltear el documento para capturar el reverso
508
+ 5. **Botón "Saltar reverso"**: Disponible para omitir manualmente la captura del reverso
509
+ 6. **Completado**: Se emite el evento `captureCompleted` con las imágenes correspondientes
510
+
511
+ ### Flujo con Clasificación Inteligente (useDocumentClassification = true)
512
+ 1. **Inicialización**: El componente se prepara para la detección
513
+ 2. **Inicio de captura**: Se cargan automáticamente los modelos de detección y clasificación
514
+ 3. **Captura del frente**: El usuario posiciona el documento y se captura automáticamente
515
+ 4. **Clasificación automática**: El sistema determina si el documento requiere captura de reverso
516
+ 5. **Flujo adaptativo**:
517
+ - **Si es pasaporte**: Se completa automáticamente el proceso (sin reverso)
518
+ - **Si es otro documento**: Se solicita voltear el documento para capturar el reverso
519
+ 6. **Completado**: Se emite el evento `captureCompleted` con las imágenes correspondientes
497
520
 
498
521
  ### Flujo con Precarga (Recomendado)
499
- 1. **Precarga del modelo**: Se llama a `preloadModel()` para cargar el modelo en memoria
500
- 2. **Inicio optimizado**: Al iniciar la captura, se usa el modelo ya cargado
501
- 3. **Captura del frente**: Detección más rápida con el modelo precargado
502
- 4. **Captura del reverso**: Se solicita voltear el documento
522
+ 1. **Precarga de modelos**: Se llama a `preloadModel()` para cargar ambos modelos en memoria
523
+ 2. **Inicio optimizado**: Al iniciar la captura, se usan los modelos ya cargados
524
+ 3. **Captura del frente**: Detección y clasificación más rápidas con modelos precargados
525
+ 4. **Flujo inteligente**:
526
+ - **Documento sin reverso**: Proceso completado inmediatamente
527
+ - **Documento con reverso**: Se solicita captura del reverso
503
528
  5. **Completado**: Se emite el evento `captureCompleted` con todas las imágenes
504
529
 
530
+ ### Clasificación de Documentos
531
+
532
+ #### Modo con Clasificación Habilitada (`useDocumentClassification = true`)
533
+ Cuando la propiedad está habilitada, el sistema utiliza un modelo de inteligencia artificial especializado para determinar automáticamente si el documento requiere captura de reverso:
534
+ - **Pasaportes**: Se omite automáticamente la captura del reverso
535
+ - **Otros documentos**: Requieren captura de ambos lados (frente y reverso)
536
+ - **Botón "Saltar reverso"**: Siempre disponible para permitir flexibilidad manual
537
+ - **Carga optimizada**: El modelo de clasificación se descarga solo cuando es necesario
538
+
539
+ #### Modo Estándar (`useDocumentClassification = false`, por defecto)
540
+ Cuando está deshabilitada, el comportamiento es más liviano y directo:
541
+ - **Todos los documentos**: Siempre se solicita captura del reverso
542
+ - **Botón "Saltar reverso"**: Disponible para omitir manualmente la captura
543
+ - **Sin clasificación**: NO se carga el modelo de clasificación, solo el de detección
544
+ - **Menor uso de ancho de banda**: Solo descarga el modelo de detección (~5MB menos)
545
+
546
+ #### Consideraciones de Rendimiento
547
+ - **Con clasificación deshabilitada**: Carga más rápida y menor uso de datos
548
+ - **Con clasificación habilitada**: Experiencia más inteligente pero requiere descargar modelo adicional
549
+ - **Carga bajo demanda**: El modelo de clasificación se carga solo cuando se captura el primer documento
550
+
505
551
  ## Requisitos del Sistema
506
552
 
507
553
  - **Navegadores**: Chrome/Edge 88+, Firefox 85+, Safari 14+
508
554
  - **Cámara**: Acceso a cámara trasera (móvil) o webcam (escritorio)
509
- - **Conexión**: Conexión a internet para cargar el modelo ONNX Runtime
555
+ - **Conexión**: Conexión a internet para cargar los modelos de IA
510
556
 
511
- ## Consideraciones de Privacidad
557
+ ## Consideraciones de Privacidad y Rendimiento
512
558
 
559
+ ### Privacidad
513
560
  - Las imágenes se procesan localmente en el navegador
514
561
  - No se envían datos a servidores externos
515
- - El modelo de IA se ejecuta completamente en el cliente
562
+ - Los modelos de IA (detección y clasificación) se ejecutan completamente en el cliente
563
+ - La clasificación de documentos se realiza de forma privada y local
516
564
  - Las imágenes capturadas solo están disponibles en el contexto de tu aplicación
517
565
 
566
+ ### Optimización de Recursos
567
+ - **Carga condicional**: Solo descarga modelos necesarios según configuración
568
+ - **Modelo de detección**: ~15MB (siempre requerido)
569
+ - **Modelo de clasificación**: ~5MB (solo si `useDocumentClassification = true`)
570
+ - **Lazy loading**: Los modelos se cargan cuando realmente se necesitan
571
+ - **Cache del navegador**: Los modelos se almacenan localmente después de la primera descarga
572
+
518
573
  ## Desarrollo
519
574
 
520
575
  ### Clonar el repositorio
@@ -18,7 +18,7 @@ var patchBrowser = () => {
18
18
 
19
19
  patchBrowser().then(async (options) => {
20
20
  await index.globalScripts();
21
- return index.bootstrapLazy([["jaak-stamps.cjs",[[1,"jaak-stamps",{"debug":[4],"alignmentTolerance":[2,"alignment-tolerance"],"isVideoActive":[32],"statusMessage":[32],"statusColor":[32],"bestScore":[32],"capturedFullFrame":[32],"capturedCroppedId":[32],"capturedBackFullFrame":[32],"capturedBackCroppedId":[32],"captureStep":[32],"isCapturing":[32],"showFlipAnimation":[32],"showSuccessAnimation":[32],"shouldMirrorVideo":[32],"sideAlignment":[32],"isDetectionPaused":[32],"isLoading":[32],"isModelPreloaded":[32],"isMaskReady":[32],"getCapturedImages":[64],"isProcessCompleted":[64],"startCapture":[64],"stopCapture":[64],"resetCapture":[64],"getStatus":[64],"preloadModel":[64],"skipBackCapture":[64]}]]]], options);
21
+ return index.bootstrapLazy([["jaak-stamps.cjs",[[1,"jaak-stamps",{"debug":[4],"alignmentTolerance":[2,"alignment-tolerance"],"maskSize":[2,"mask-size"],"cropMargin":[2,"crop-margin"],"useDocumentClassification":[4,"use-document-classification"],"isVideoActive":[32],"statusMessage":[32],"statusColor":[32],"bestScore":[32],"capturedFullFrame":[32],"capturedCroppedId":[32],"capturedBackFullFrame":[32],"capturedBackCroppedId":[32],"captureStep":[32],"isCapturing":[32],"showFlipAnimation":[32],"showSuccessAnimation":[32],"shouldMirrorVideo":[32],"sideAlignment":[32],"isDetectionPaused":[32],"isLoading":[32],"isModelPreloaded":[32],"isMaskReady":[32],"getCapturedImages":[64],"isProcessCompleted":[64],"startCapture":[64],"stopCapture":[64],"resetCapture":[64],"getStatus":[64],"preloadModel":[64],"skipBackCapture":[64]}]]]], options);
22
22
  });
23
23
 
24
24
  exports.setNonce = index.setNonce;
@@ -13,6 +13,9 @@ const JaakStamps = class {
13
13
  get el() { return index.getElement(this); }
14
14
  debug = false;
15
15
  alignmentTolerance = 10; // Tolerancia en píxeles para considerar un lado alineado (escalado para 320x320)
16
+ maskSize = 90; // Porcentaje del video que ocupará la máscara (default 90%)
17
+ cropMargin = 0; // Margen en píxeles para el recorte del documento (default 0)
18
+ useDocumentClassification = false; // Habilita la clasificación automática de documentos para determinar si solicitar reverso
16
19
  captureCompleted;
17
20
  isReady;
18
21
  isVideoActive = false;
@@ -46,6 +49,8 @@ const JaakStamps = class {
46
49
  animationId;
47
50
  hasScreenshotTaken = false;
48
51
  lastDetectedBox;
52
+ mobileNetSession;
53
+ mobileNetClassMap;
49
54
  // Performance optimization properties
50
55
  frameSkipCounter = 0;
51
56
  FRAME_SKIP = 2; // Process every 3rd frame (reduces CPU by ~66%)
@@ -58,7 +63,9 @@ const JaakStamps = class {
58
63
  preprocessCtx;
59
64
  captureCanvas;
60
65
  captureCtx;
61
- MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/detector-nano.onnx";
66
+ MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v1.onnx";
67
+ MOBILENET_MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx";
68
+ MOBILENET_CLASSES_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";
62
69
  INPUT_SIZE = 320;
63
70
  CONFIDENCE_THRESHOLD = 0.6;
64
71
  // ISO/IEC 7810 ID-1 standard dimensions (85.60mm x 53.98mm)
@@ -68,6 +75,18 @@ const JaakStamps = class {
68
75
  console.log(...args);
69
76
  }
70
77
  }
78
+ validateMaskSize() {
79
+ if (this.maskSize < 50 || this.maskSize > 100) {
80
+ console.warn(`maskSize debe estar entre 50 y 100. Valor actual: ${this.maskSize}. Usando valor por defecto: 90`);
81
+ this.maskSize = 90;
82
+ }
83
+ }
84
+ validateCropMargin() {
85
+ if (this.cropMargin < 0 || this.cropMargin > 100) {
86
+ console.warn(`cropMargin debe estar entre 0 y 100. Valor actual: ${this.cropMargin}. Usando valor por defecto: 0`);
87
+ this.cropMargin = 0;
88
+ }
89
+ }
71
90
  emitReadyEvent() {
72
91
  const isDocumentReady = !!window.ort && this.isModelPreloaded;
73
92
  this.isReady.emit(isDocumentReady);
@@ -81,6 +100,8 @@ const JaakStamps = class {
81
100
  return settings.facingMode === 'environment';
82
101
  }
83
102
  async componentDidLoad() {
103
+ this.validateMaskSize();
104
+ this.validateCropMargin();
84
105
  if (!window.ort) {
85
106
  const script = document.createElement('script');
86
107
  script.src = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js';
@@ -148,14 +169,15 @@ const JaakStamps = class {
148
169
  // Calculate what would be the max width if limited by video height
149
170
  const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
150
171
  let maskWidthInVideo, maskHeightInVideo;
172
+ const sizeRatio = this.maskSize / 100;
151
173
  if (maxWidthByHeight <= displayedVideoWidth) {
152
174
  // Video height is the limiting factor
153
- maskHeightInVideo = displayedVideoHeight * 0.9; // Use 90% of available height
175
+ maskHeightInVideo = displayedVideoHeight * sizeRatio;
154
176
  maskWidthInVideo = maskHeightInVideo * this.ID1_ASPECT_RATIO;
155
177
  }
156
178
  else {
157
179
  // Video width is the limiting factor
158
- maskWidthInVideo = displayedVideoWidth * 0.9; // Use 90% of available width
180
+ maskWidthInVideo = displayedVideoWidth * sizeRatio;
159
181
  maskHeightInVideo = maskWidthInVideo / this.ID1_ASPECT_RATIO;
160
182
  }
161
183
  // Convert to percentages of the container
@@ -249,25 +271,29 @@ const JaakStamps = class {
249
271
  }
250
272
  try {
251
273
  this.isLoading = true;
252
- this.statusMessage = "Precargando modelo de detección...";
274
+ this.statusMessage = "Precargando modelos...";
253
275
  this.statusColor = "#007bff";
254
276
  const modelPath = this.MODEL_PATH;
255
- this.debugLog('🤖 Preloading model:', modelPath);
277
+ this.debugLog('🤖 Preloading detection model:', modelPath);
256
278
  // Configure ONNX Runtime with device-specific optimizations
257
279
  const sessionOptions = this.getSessionOptions();
258
280
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
281
+ // Preload MobileNet model and classes only if classification is enabled
282
+ if (this.useDocumentClassification) {
283
+ await this.loadMobileNetModel();
284
+ }
259
285
  this.isModelPreloaded = true;
260
286
  this.isLoading = false;
261
- this.statusMessage = "Modelo precargado. Listo para comenzar detección";
287
+ this.statusMessage = "Modelos precargados. Listo para comenzar detección";
262
288
  this.statusColor = "#28a745";
263
289
  this.emitReadyEvent();
264
- this.debugLog('✅ Model preloaded successfully');
265
- return { success: true, message: 'Model preloaded successfully' };
290
+ this.debugLog('✅ Models preloaded successfully');
291
+ return { success: true, message: 'Models preloaded successfully' };
266
292
  }
267
293
  catch (error) {
268
- this.debugLog('❌ Error preloading model:', error);
294
+ this.debugLog('❌ Error preloading models:', error);
269
295
  this.isLoading = false;
270
- this.statusMessage = "Error al precargar el modelo";
296
+ this.statusMessage = "Error al precargar los modelos";
271
297
  this.statusColor = "#ff6b6b";
272
298
  return { success: false, error: error.message };
273
299
  }
@@ -277,6 +303,80 @@ const JaakStamps = class {
277
303
  this.completeProcess(true);
278
304
  }
279
305
  }
306
+ async loadMobileNetModel() {
307
+ try {
308
+ this.debugLog('🤖 Loading MobileNet model...');
309
+ // Load class map
310
+ const classResponse = await fetch(this.MOBILENET_CLASSES_PATH);
311
+ if (!classResponse.ok) {
312
+ throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`);
313
+ }
314
+ this.mobileNetClassMap = await classResponse.json();
315
+ this.debugLog('📋 MobileNet classes loaded:', this.mobileNetClassMap);
316
+ // Load model
317
+ const sessionOptions = this.getSessionOptions();
318
+ this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, sessionOptions);
319
+ this.debugLog('✅ MobileNet model loaded successfully');
320
+ }
321
+ catch (error) {
322
+ this.debugLog('❌ Error loading MobileNet model:', error);
323
+ throw error;
324
+ }
325
+ }
326
+ preprocessMobileNet(canvas) {
327
+ // Create a temporary canvas for MobileNet preprocessing (224x224)
328
+ const tempCanvas = document.createElement('canvas');
329
+ tempCanvas.width = 224;
330
+ tempCanvas.height = 224;
331
+ const tempCtx = tempCanvas.getContext('2d');
332
+ // Draw the cropped image onto the 224x224 canvas
333
+ tempCtx.drawImage(canvas, 0, 0, 224, 224);
334
+ // Get image data and preprocess for MobileNet
335
+ const imageData = tempCtx.getImageData(0, 0, 224, 224);
336
+ const data = imageData.data;
337
+ const hw = 224 * 224;
338
+ const arr = new Float32Array(3 * hw);
339
+ // Normalize pixels: (pixel/255 - 0.5) / 0.5 = (pixel - 127.5) / 127.5
340
+ for (let i = 0; i < hw; i++) {
341
+ arr[i] = (data[i * 4 + 0] / 255 - 0.5) / 0.5; // R
342
+ arr[hw + i] = (data[i * 4 + 1] / 255 - 0.5) / 0.5; // G
343
+ arr[2 * hw + i] = (data[i * 4 + 2] / 255 - 0.5) / 0.5; // B
344
+ }
345
+ return new window.ort.Tensor('float32', arr, [1, 3, 224, 224]);
346
+ }
347
+ async classifyDocument(canvas) {
348
+ if (!this.mobileNetSession || !this.mobileNetClassMap) {
349
+ this.debugLog('⚠️ MobileNet model not loaded');
350
+ return null;
351
+ }
352
+ try {
353
+ this.debugLog('🔍 Classifying document...');
354
+ // Preprocess image for MobileNet
355
+ const inputTensor = this.preprocessMobileNet(canvas);
356
+ // Run inference
357
+ const feeds = { input: inputTensor };
358
+ const results = await this.mobileNetSession.run(feeds);
359
+ const output = results[Object.keys(results)[0]].data;
360
+ // Find the class with highest confidence
361
+ const maxIdx = output.reduce((bestIdx, val, idx, arr) => val > arr[bestIdx] ? idx : bestIdx, 0);
362
+ const confidence = output[maxIdx];
363
+ const className = this.mobileNetClassMap[maxIdx.toString()] || "unknown";
364
+ this.debugLog('📄 Document classification result:', {
365
+ class: className,
366
+ confidence: confidence.toFixed(3),
367
+ classIndex: maxIdx
368
+ });
369
+ return {
370
+ class: className,
371
+ confidence: confidence,
372
+ classIndex: maxIdx
373
+ };
374
+ }
375
+ catch (error) {
376
+ this.debugLog('❌ Error classifying document:', error);
377
+ return null;
378
+ }
379
+ }
280
380
  cleanup() {
281
381
  if (this.animationId) {
282
382
  cancelAnimationFrame(this.animationId);
@@ -304,11 +404,16 @@ const JaakStamps = class {
304
404
  this.captureCtx = undefined;
305
405
  this.captureCanvas = undefined;
306
406
  }
307
- // Disposed ONNX session
407
+ // Disposed ONNX sessions
308
408
  if (this.session) {
309
409
  this.session.release?.();
310
410
  this.session = undefined;
311
411
  }
412
+ if (this.mobileNetSession) {
413
+ this.mobileNetSession.release?.();
414
+ this.mobileNetSession = undefined;
415
+ }
416
+ this.mobileNetClassMap = undefined;
312
417
  this.isModelPreloaded = false;
313
418
  this.debugLog('🧹 Canvas pool cleaned up');
314
419
  }
@@ -439,18 +544,22 @@ const JaakStamps = class {
439
544
  // Check if model is already preloaded
440
545
  if (!this.session) {
441
546
  this.isLoading = true;
442
- this.statusMessage = "Cargando modelo de detección...";
547
+ this.statusMessage = "Cargando modelos...";
443
548
  this.statusColor = "#007bff";
444
549
  const modelPath = this.MODEL_PATH;
445
- this.debugLog('🤖 Loading model:', modelPath);
550
+ this.debugLog('🤖 Loading detection model:', modelPath);
446
551
  const sessionOptions = this.getSessionOptions();
447
552
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
553
+ // Load MobileNet model if classification is enabled and not already loaded
554
+ if (this.useDocumentClassification && !this.mobileNetSession) {
555
+ await this.loadMobileNetModel();
556
+ }
448
557
  this.isModelPreloaded = true;
449
558
  this.emitReadyEvent();
450
559
  }
451
560
  else {
452
- this.debugLog('🚀 Using preloaded model');
453
- this.statusMessage = "Usando modelo precargado...";
561
+ this.debugLog('🚀 Using preloaded models');
562
+ this.statusMessage = "Usando modelos precargados...";
454
563
  this.statusColor = "#007bff";
455
564
  }
456
565
  this.statusMessage = "Configurando cámara...";
@@ -593,14 +702,15 @@ const JaakStamps = class {
593
702
  // Calculate mask dimensions using the same logic as updateMaskDimensions
594
703
  const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
595
704
  let visualMaskWidth, visualMaskHeight;
705
+ const sizeRatio = this.maskSize / 100;
596
706
  if (maxWidthByHeight <= displayedVideoWidth) {
597
707
  // Video height is the limiting factor
598
- visualMaskHeight = displayedVideoHeight * 0.9;
708
+ visualMaskHeight = displayedVideoHeight * sizeRatio;
599
709
  visualMaskWidth = visualMaskHeight * this.ID1_ASPECT_RATIO;
600
710
  }
601
711
  else {
602
712
  // Video width is the limiting factor
603
- visualMaskWidth = displayedVideoWidth * 0.9;
713
+ visualMaskWidth = displayedVideoWidth * sizeRatio;
604
714
  visualMaskHeight = visualMaskWidth / this.ID1_ASPECT_RATIO;
605
715
  }
606
716
  // Now map these visual mask dimensions to the distorted model space
@@ -668,7 +778,9 @@ const JaakStamps = class {
668
778
  corners?.forEach(corner => corner.classList.add('perfect-match'));
669
779
  if (!this.hasScreenshotTaken) {
670
780
  this.lastDetectedBox = bestBox;
671
- this.takeScreenshot();
781
+ this.takeScreenshot().catch(error => {
782
+ this.debugLog('❌ Error taking screenshot:', error);
783
+ });
672
784
  this.hasScreenshotTaken = true;
673
785
  // Reset para permitir segunda captura
674
786
  setTimeout(() => {
@@ -751,7 +863,7 @@ const JaakStamps = class {
751
863
  ctx.strokeRect(x, y, w, h);
752
864
  });
753
865
  }
754
- takeScreenshot() {
866
+ async takeScreenshot() {
755
867
  if (!this.videoRef || !this.lastDetectedBox)
756
868
  return;
757
869
  // Activar animación
@@ -767,10 +879,10 @@ const JaakStamps = class {
767
879
  // Calcular las coordenadas de recorte basadas en la detección
768
880
  const scaleX = this.videoRef.videoWidth / this.INPUT_SIZE;
769
881
  const scaleY = this.videoRef.videoHeight / this.INPUT_SIZE;
770
- const cropX = Math.max(0, this.lastDetectedBox.x * scaleX);
771
- const cropY = Math.max(0, this.lastDetectedBox.y * scaleY);
772
- const cropWidth = Math.min(this.lastDetectedBox.w * scaleX, this.videoRef.videoWidth - cropX);
773
- const cropHeight = Math.min(this.lastDetectedBox.h * scaleY, this.videoRef.videoHeight - cropY);
882
+ const cropX = Math.max(0, (this.lastDetectedBox.x * scaleX) - this.cropMargin);
883
+ const cropY = Math.max(0, (this.lastDetectedBox.y * scaleY) - this.cropMargin);
884
+ const cropWidth = Math.min((this.lastDetectedBox.w * scaleX) + (2 * this.cropMargin), this.videoRef.videoWidth - cropX);
885
+ const cropHeight = Math.min((this.lastDetectedBox.h * scaleY) + (2 * this.cropMargin), this.videoRef.videoHeight - cropY);
774
886
  // OPTIMIZATION: Create temporary canvas only for cropped version
775
887
  // (We reuse main capture canvas for full frame)
776
888
  const croppedCanvas = document.createElement('canvas');
@@ -785,6 +897,29 @@ const JaakStamps = class {
785
897
  // Captura del frente usando canvas reutilizado
786
898
  this.capturedFullFrame = this.captureCanvas.toDataURL('image/png');
787
899
  this.capturedCroppedId = croppedCanvas.toDataURL('image/png');
900
+ // Check if document classification is enabled
901
+ if (this.useDocumentClassification) {
902
+ // Load MobileNet model if not loaded yet (lazy loading)
903
+ if (!this.mobileNetSession) {
904
+ try {
905
+ await this.loadMobileNetModel();
906
+ }
907
+ catch (error) {
908
+ this.debugLog('⚠️ Failed to load classification model, continuing without classification:', error);
909
+ }
910
+ }
911
+ // Classify the cropped document if model is available
912
+ if (this.mobileNetSession) {
913
+ const classification = await this.classifyDocument(croppedCanvas);
914
+ if (classification && classification.class === 'passport') {
915
+ // If it's a passport, skip back capture since passports don't have a back side
916
+ this.debugLog('📄 Passport detected - skipping back capture');
917
+ this.completeProcess(true);
918
+ return;
919
+ }
920
+ }
921
+ }
922
+ // For other IDs, continue with normal flow (back capture)
788
923
  this.captureStep = 'back';
789
924
  this.statusMessage = "Voltee la identificación y muestre la parte trasera";
790
925
  this.statusColor = "#007bff";
@@ -914,7 +1049,7 @@ const JaakStamps = class {
914
1049
  this.cleanup();
915
1050
  }
916
1051
  render() {
917
- return (index.h("div", { key: 'b63a5966ee08d4de7b5d8a10dbf248150e8620ec', class: "detector-container" }, index.h("div", { key: '1c62d540a1802a758b90a543edfdc364123ae950', class: "video-container" }, index.h("video", { key: '18e066e0005c3b287983ebb29c9e4aa147eaaf8d', ref: el => this.videoRef = el, autoplay: true, muted: true, playsinline: true, class: this.shouldMirrorVideo ? 'mirror' : '', style: { display: this.isVideoActive ? 'block' : 'none' } }), index.h("canvas", { key: '43cd238e38a5a2ff9c140800ac686580a7ca33b9', ref: el => this.canvasRef = el, class: this.shouldMirrorVideo ? 'mirror' : '' }), this.isMaskReady && (index.h("div", { key: 'f43db67b9d1ef47264092694c3ab8afa9925e258', class: "overlay-mask" }, index.h("div", { key: 'ac60d94edc4cfa6ccf91ba6e04d2be6e4368be97', class: "card-outline" }, index.h("div", { key: 'de6aca9bbfe778890adf4c69e8525a114c37f6d4', class: "side side-top" }), index.h("div", { key: '7ce7b1e2215b01ea5d714b8ecc988361e384b6f7', class: "side side-right" }), index.h("div", { key: 'b79a68f68facb42ca139d6a2bc8e1e6d7133872d', class: "side side-bottom" }), index.h("div", { key: '81d90c4a08cfc2267cec195a3b342c87bb1d07d0', class: "side side-left" }), index.h("div", { key: 'c93c83abb8e17a5cb9c1bd53b2e1239ef50c7bf4', class: "corner corner-tl" }), index.h("div", { key: '81ca7cf2aab7026e851bd226843a6db5807315d5', class: "corner corner-tr" }), index.h("div", { key: 'c451fe226ac15023ee9799443060f1da620cb3b3', class: "corner corner-bl" }), index.h("div", { key: '7c3e2b2a21bd37144fe6b4d5df67df625dc12103', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("div", { key: '74ab171b64bdf0e1269845b4fcd9bf8e2caf891d', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("button", { key: '2b2b9387ce8b023acf0d65c7f7b3480211f7cb2d', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")))), this.isCapturing && (index.h("div", { key: 'eabd88499f52098f79e434afcce73acb2727c411', class: "capture-animation" })), this.showFlipAnimation && (index.h("div", { key: '9affe6040a39260747db98db2b68a103fb719fbb', class: "flip-animation" }, index.h("div", { key: '8b25f3688a16f4b070664237a093122a6720edfb', class: "id-card-icon" }), index.h("div", { key: '805b11cfb4d06a25e02370b06f6cf15f0f0cf6b5', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (index.h("div", { key: 'cba337b6fef8b919425566c0c9c5de797d42c4c8', class: "success-animation" }, index.h("div", { key: '4a88df3f9285757b489b030ba985d720a8a3badf', class: "check-icon" }), index.h("div", { key: 'a0bdd89c2c6274330ba66a6b6bba86ab6c725979', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (index.h("div", { key: '564fc1333b0fb69102e26ac1da4e77786a9bc7a3', class: "loading-overlay" }, index.h("div", { key: '283e4a6315a39b26203e19a13f35389bc1870a0f', class: "loading-spinner" }), index.h("div", { key: '7e4f00a1fcee1bbf29d74c8be35a72aba2c1041a', class: "loading-text" }, this.statusMessage))), index.h("div", { key: '6cbe1fea1c4a7d3cb25cd34ee04becb5fa538dfd', class: "watermark" }, index.h("img", { key: '1bd4157b7f74753570ddf48682acf419a6de03ea', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
1052
+ return (index.h("div", { key: '42591479495df221b101555198a23288d7d765b0', class: "detector-container" }, index.h("div", { key: '2b9ab48572aa2fb5542b8a8dc1b70a0f2a6eca89', class: "video-container" }, index.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' } }), index.h("canvas", { key: 'a82fc4826e220e696799b07b3510456f174a6628', ref: el => this.canvasRef = el, class: this.shouldMirrorVideo ? 'mirror' : '' }), this.isMaskReady && (index.h("div", { key: '9b3b838f99030e3dfa760fa0dd7c89ff24f26ed9', class: "overlay-mask" }, index.h("div", { key: 'f6a3b1ac2f12c1fb081f6b5eb853e627040396f4', class: "card-outline" }, index.h("div", { key: '6626259249ac5e0fd6ba665ab802af1ac2f9fc17', class: "side side-top" }), index.h("div", { key: '7a3195c96b2406b40b122f4267c2a251614cdede', class: "side side-right" }), index.h("div", { key: 'ece78305cfb083ada1d44de1d7d5226730879cc3', class: "side side-bottom" }), index.h("div", { key: '107468c583bbb01dd46c36c096e49be8e0b574ba', class: "side side-left" }), index.h("div", { key: 'c590f13b80c5e37c0ac0c68cfc2e2904b4345ebc', class: "corner corner-tl" }), index.h("div", { key: 'ab1e5aab179068ad1bc7b58ef3628d9618a877a8', class: "corner corner-tr" }), index.h("div", { key: '3a1db6cf1105bd3a2dfe7d4b998e79f6e40625ec', class: "corner corner-bl" }), index.h("div", { key: '5f9bc4e4557e5539335894160dccbaa2a6d6ac2d', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("div", { key: '8226d6721b0ae800f935e978a93113bd3b99656a', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("button", { key: '16cec7ca4a80ba0db1ace768826da17063eddb3e', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")))), this.isCapturing && (index.h("div", { key: 'bfdca0059eb50d37a77e8e43ef963ba7ed953edf', class: "capture-animation" })), this.showFlipAnimation && (index.h("div", { key: 'a1ad4b4f884d7d9f6090f148ddd6df19250073dd', class: "flip-animation" }, index.h("div", { key: 'e159ce385824dc049a6e9409d3747105c6f0a08e', class: "id-card-icon" }), index.h("div", { key: '6fcff650a3c7fdb16f8d327750e06055b9a93d0d', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (index.h("div", { key: 'c4b76ecb19c65969676e5156689c2c0b1c9a584e', class: "success-animation" }, index.h("div", { key: '12203a8fe7ee878089b3dda1d1142cde5489eed0', class: "check-icon" }), index.h("div", { key: 'a2d41c8944873d33106994b8d56c3ee1ee1ae9fc', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (index.h("div", { key: 'a155cd999fa40c35fa7b391cde7c1026edb250a7', class: "loading-overlay" }, index.h("div", { key: 'ccba76c5d4a472158c28bc564ba95bd65829b58d', class: "loading-spinner" }), index.h("div", { key: '23168f9bdcf4e993539288ff5703acaed13bb16a', class: "loading-text" }, this.statusMessage))), index.h("div", { key: '0107b82ad19726c1bab131e17892a46b04e08cfd', class: "watermark" }, index.h("img", { key: 'ad8831a6f77fa61805f22e3a27f5c5619ac1cc0e', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
918
1053
  }
919
1054
  };
920
1055
  JaakStamps.style = myComponentCss;