@jaak.ai/stamps 2.0.0-dev.24 → 2.0.0-dev.25

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
@@ -12,7 +12,7 @@ Un componente web para la detección y captura automática de documentos de iden
12
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" mask-size="90" crop-margin="10"></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>
@@ -142,6 +142,7 @@ import { Component, ElementRef, ViewChild, OnInit } from '@angular/core';
142
142
  [debug]="false"
143
143
  [maskSize]="90"
144
144
  [cropMargin]="10"
145
+ [useDocumentClassification]="false"
145
146
  (captureCompleted)="onCaptureCompleted($event)"
146
147
  (isReady)="onComponentReady($event)">
147
148
  </jaak-stamps>
@@ -243,7 +244,7 @@ import React, { useRef, useEffect, useImperativeHandle, forwardRef } from 'react
243
244
  // Importar el web component
244
245
  import '@jaak.ai/stamps/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js';
245
246
 
246
- const JaakStampsWrapper = forwardRef(({ debug = false, maskSize = 90, cropMargin = 0, onCaptureCompleted, onIsReady }, ref) => {
247
+ const JaakStampsWrapper = forwardRef(({ debug = false, maskSize = 90, cropMargin = 0, useDocumentClassification = false, onCaptureCompleted, onIsReady }, ref) => {
247
248
  const elementRef = useRef(null);
248
249
 
249
250
  useImperativeHandle(ref, () => ({
@@ -289,6 +290,7 @@ const JaakStampsWrapper = forwardRef(({ debug = false, maskSize = 90, cropMargin
289
290
  debug={debug}
290
291
  mask-size={maskSize}
291
292
  crop-margin={cropMargin}
293
+ use-document-classification={useDocumentClassification}
292
294
  />
293
295
  );
294
296
  });
@@ -370,6 +372,7 @@ function App() {
370
372
  debug={false}
371
373
  maskSize={90}
372
374
  cropMargin={10}
375
+ useDocumentClassification={false}
373
376
  onCaptureCompleted={handleCaptureCompleted}
374
377
  onIsReady={handleIsReady}
375
378
  />
@@ -443,6 +446,7 @@ export default App;
443
446
  | `alignmentTolerance` | `number` | `10` | Tolerancia en píxeles para considerar un lado alineado |
444
447
  | `maskSize` | `number` | `90` | Porcentaje del video que ocupará la máscara de detección (50-100) |
445
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. |
446
450
 
447
451
  ### Métodos Públicos
448
452
 
@@ -462,7 +466,7 @@ export default App;
462
466
  | Evento | Payload | Descripción |
463
467
  |--------|---------|-------------|
464
468
  | `captureCompleted` | `CapturedImages` | Se emite cuando se completa el proceso de captura |
465
- | `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) |
466
470
 
467
471
  ### Tipos de Datos
468
472
 
@@ -496,14 +500,22 @@ interface Status {
496
500
 
497
501
  ## Flujo de Trabajo
498
502
 
499
- ### Flujo Estándar
503
+ ### Flujo Estándar (useDocumentClassification = false)
504
+ 1. **Inicialización**: El componente se prepara para la detección
505
+ 2. **Inicio de captura**: Se carga automáticamente el modelo de detección
506
+ 3. **Captura del frente**: El usuario posiciona el documento y se captura automáticamente
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)
500
512
  1. **Inicialización**: El componente se prepara para la detección
501
513
  2. **Inicio de captura**: Se cargan automáticamente los modelos de detección y clasificación
502
514
  3. **Captura del frente**: El usuario posiciona el documento y se captura automáticamente
503
515
  4. **Clasificación automática**: El sistema determina si el documento requiere captura de reverso
504
516
  5. **Flujo adaptativo**:
505
- - **Si no requiere reverso**: Se completa automáticamente el proceso
506
- - **Si requiere reverso**: Se solicita voltear el documento para capturar el reverso
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
507
519
  6. **Completado**: Se emite el evento `captureCompleted` con las imágenes correspondientes
508
520
 
509
521
  ### Flujo con Precarga (Recomendado)
@@ -516,25 +528,48 @@ interface Status {
516
528
  5. **Completado**: Se emite el evento `captureCompleted` con todas las imágenes
517
529
 
518
530
  ### Clasificación de Documentos
519
- El sistema utiliza un modelo MobileNet especializado para determinar automáticamente si el documento requiere captura de reverso:
520
- - **Documentos sin reverso**: Se omite automáticamente la captura del reverso
521
- - **Documentos con reverso**: Requieren captura de ambos lados (frente y reverso)
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)
522
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
523
550
 
524
551
  ## Requisitos del Sistema
525
552
 
526
553
  - **Navegadores**: Chrome/Edge 88+, Firefox 85+, Safari 14+
527
554
  - **Cámara**: Acceso a cámara trasera (móvil) o webcam (escritorio)
528
- - **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
529
556
 
530
- ## Consideraciones de Privacidad
557
+ ## Consideraciones de Privacidad y Rendimiento
531
558
 
559
+ ### Privacidad
532
560
  - Las imágenes se procesan localmente en el navegador
533
561
  - No se envían datos a servidores externos
534
562
  - Los modelos de IA (detección y clasificación) se ejecutan completamente en el cliente
535
563
  - La clasificación de documentos se realiza de forma privada y local
536
564
  - Las imágenes capturadas solo están disponibles en el contexto de tu aplicación
537
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
+
538
573
  ## Desarrollo
539
574
 
540
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"],"maskSize":[2,"mask-size"],"cropMargin":[2,"crop-margin"],"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;
@@ -15,6 +15,7 @@ const JaakStamps = class {
15
15
  alignmentTolerance = 10; // Tolerancia en píxeles para considerar un lado alineado (escalado para 320x320)
16
16
  maskSize = 90; // Porcentaje del video que ocupará la máscara (default 90%)
17
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
18
19
  captureCompleted;
19
20
  isReady;
20
21
  isVideoActive = false;
@@ -277,8 +278,10 @@ const JaakStamps = class {
277
278
  // Configure ONNX Runtime with device-specific optimizations
278
279
  const sessionOptions = this.getSessionOptions();
279
280
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
280
- // Preload MobileNet model and classes
281
- await this.loadMobileNetModel();
281
+ // Preload MobileNet model and classes only if classification is enabled
282
+ if (this.useDocumentClassification) {
283
+ await this.loadMobileNetModel();
284
+ }
282
285
  this.isModelPreloaded = true;
283
286
  this.isLoading = false;
284
287
  this.statusMessage = "Modelos precargados. Listo para comenzar detección";
@@ -547,8 +550,8 @@ const JaakStamps = class {
547
550
  this.debugLog('🤖 Loading detection model:', modelPath);
548
551
  const sessionOptions = this.getSessionOptions();
549
552
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
550
- // Load MobileNet model if not already loaded
551
- if (!this.mobileNetSession) {
553
+ // Load MobileNet model if classification is enabled and not already loaded
554
+ if (this.useDocumentClassification && !this.mobileNetSession) {
552
555
  await this.loadMobileNetModel();
553
556
  }
554
557
  this.isModelPreloaded = true;
@@ -894,13 +897,27 @@ const JaakStamps = class {
894
897
  // Captura del frente usando canvas reutilizado
895
898
  this.capturedFullFrame = this.captureCanvas.toDataURL('image/png');
896
899
  this.capturedCroppedId = croppedCanvas.toDataURL('image/png');
897
- // Classify the cropped document
898
- const classification = await this.classifyDocument(croppedCanvas);
899
- if (classification && classification.class === 'passport') {
900
- // If it's a passport, skip back capture since passports don't have a back side
901
- this.debugLog('📄 Passport detected - skipping back capture');
902
- this.completeProcess(true);
903
- return;
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
+ }
904
921
  }
905
922
  // For other IDs, continue with normal flow (back capture)
906
923
  this.captureStep = 'back';
@@ -1032,7 +1049,7 @@ const JaakStamps = class {
1032
1049
  this.cleanup();
1033
1050
  }
1034
1051
  render() {
1035
- return (index.h("div", { key: 'd6cd4225500c44e5c7fb4f2b3dc453a055467066', class: "detector-container" }, index.h("div", { key: '6bd49b0bcd686648aeffb8fb95203dc0779f1d8a', class: "video-container" }, index.h("video", { key: 'd2666ce9d1f5b84703ac86fd4eb901f4298ed7d5', 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: 'e997f063450d81d2a15398f0761c9d06c28a85c9', ref: el => this.canvasRef = el, class: this.shouldMirrorVideo ? 'mirror' : '' }), this.isMaskReady && (index.h("div", { key: '4ccb8bf05091a7173255181eae1a8699fe512b56', class: "overlay-mask" }, index.h("div", { key: 'b35defa8c207b05e41d64c8e1eefc905d31fad55', class: "card-outline" }, index.h("div", { key: '6ed8dad63d6d79c1bb4a64f0b28467f5b29d778a', class: "side side-top" }), index.h("div", { key: '403d4a5ba681a58ad1870a4339e19b4f037a8795', class: "side side-right" }), index.h("div", { key: '3cb3276bb184a4b76419b4cb0b4fcb151a4df631', class: "side side-bottom" }), index.h("div", { key: 'ed7c9bec0e708ab282ba8b24a08d21b8126af27e', class: "side side-left" }), index.h("div", { key: '157be211355bf9260dc7a73d03831dbb1a2945e3', class: "corner corner-tl" }), index.h("div", { key: 'b19af5f319333ff05f981063af939d2c4cfc9b5f', class: "corner corner-tr" }), index.h("div", { key: '6fcd3e2c8842261dcd32c36e6df5b2f3dd0c8fc8', class: "corner corner-bl" }), index.h("div", { key: '7caab5eaee62f3f9039075b3748083c89c8127e0', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("div", { key: 'e3dd42ddb75b22aeef438d8651955f3dc039f00c', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("button", { key: '54b8651817cd52bad2f34ac1413a4b1e21166cee', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")))), this.isCapturing && (index.h("div", { key: '853707a4fa71eeacbee7985e619fca80d6522cbd', class: "capture-animation" })), this.showFlipAnimation && (index.h("div", { key: '246ed3f5dc57ee57345105cdebe5f950d5ff4c90', class: "flip-animation" }, index.h("div", { key: 'f03c6c87c8f5e98a32176cca061d369a521da2e8', class: "id-card-icon" }), index.h("div", { key: 'e357785b076a9e41ea4f9b3d9c14e847bacc9604', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (index.h("div", { key: 'df3adaaecd3d547938638c58ccc0e89f8325fc23', class: "success-animation" }, index.h("div", { key: 'a023985b8afd6ed72f9e1c2ee63e2c7ba9fb960b', class: "check-icon" }), index.h("div", { key: '739ff7f329f2131061a6860529c07c8819800aab', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (index.h("div", { key: '9b02df640528a19cb15e5dbabf9ecb43afbceffa', class: "loading-overlay" }, index.h("div", { key: '3652c8e355ea7fe623c478229bf548bdf30e399a', class: "loading-spinner" }), index.h("div", { key: '334f4469b5672f6af78b8679c15ed8c59ecefa85', class: "loading-text" }, this.statusMessage))), index.h("div", { key: 'a0b7c9b92771cff96e97bd67da2fd3090b080f8a', class: "watermark" }, index.h("img", { key: 'b5c8f0de1d8138d4a0c80526fd33b2daefa86b16', 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" })))));
1036
1053
  }
1037
1054
  };
1038
1055
  JaakStamps.style = myComponentCss;