@jaak.ai/stamps 2.0.0-dev.23 → 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.
@@ -13,6 +13,7 @@ const JaakStamps = class {
13
13
  alignmentTolerance = 10; // Tolerancia en píxeles para considerar un lado alineado (escalado para 320x320)
14
14
  maskSize = 90; // Porcentaje del video que ocupará la máscara (default 90%)
15
15
  cropMargin = 0; // Margen en píxeles para el recorte del documento (default 0)
16
+ useDocumentClassification = false; // Habilita la clasificación automática de documentos para determinar si solicitar reverso
16
17
  captureCompleted;
17
18
  isReady;
18
19
  isVideoActive = false;
@@ -46,6 +47,8 @@ const JaakStamps = class {
46
47
  animationId;
47
48
  hasScreenshotTaken = false;
48
49
  lastDetectedBox;
50
+ mobileNetSession;
51
+ mobileNetClassMap;
49
52
  // Performance optimization properties
50
53
  frameSkipCounter = 0;
51
54
  FRAME_SKIP = 2; // Process every 3rd frame (reduces CPU by ~66%)
@@ -58,7 +61,9 @@ const JaakStamps = class {
58
61
  preprocessCtx;
59
62
  captureCanvas;
60
63
  captureCtx;
61
- MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/detector-nano.onnx";
64
+ MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v1.onnx";
65
+ MOBILENET_MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx";
66
+ MOBILENET_CLASSES_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";
62
67
  INPUT_SIZE = 320;
63
68
  CONFIDENCE_THRESHOLD = 0.6;
64
69
  // ISO/IEC 7810 ID-1 standard dimensions (85.60mm x 53.98mm)
@@ -264,25 +269,29 @@ const JaakStamps = class {
264
269
  }
265
270
  try {
266
271
  this.isLoading = true;
267
- this.statusMessage = "Precargando modelo de detección...";
272
+ this.statusMessage = "Precargando modelos...";
268
273
  this.statusColor = "#007bff";
269
274
  const modelPath = this.MODEL_PATH;
270
- this.debugLog('🤖 Preloading model:', modelPath);
275
+ this.debugLog('🤖 Preloading detection model:', modelPath);
271
276
  // Configure ONNX Runtime with device-specific optimizations
272
277
  const sessionOptions = this.getSessionOptions();
273
278
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
279
+ // Preload MobileNet model and classes only if classification is enabled
280
+ if (this.useDocumentClassification) {
281
+ await this.loadMobileNetModel();
282
+ }
274
283
  this.isModelPreloaded = true;
275
284
  this.isLoading = false;
276
- this.statusMessage = "Modelo precargado. Listo para comenzar detección";
285
+ this.statusMessage = "Modelos precargados. Listo para comenzar detección";
277
286
  this.statusColor = "#28a745";
278
287
  this.emitReadyEvent();
279
- this.debugLog('✅ Model preloaded successfully');
280
- return { success: true, message: 'Model preloaded successfully' };
288
+ this.debugLog('✅ Models preloaded successfully');
289
+ return { success: true, message: 'Models preloaded successfully' };
281
290
  }
282
291
  catch (error) {
283
- this.debugLog('❌ Error preloading model:', error);
292
+ this.debugLog('❌ Error preloading models:', error);
284
293
  this.isLoading = false;
285
- this.statusMessage = "Error al precargar el modelo";
294
+ this.statusMessage = "Error al precargar los modelos";
286
295
  this.statusColor = "#ff6b6b";
287
296
  return { success: false, error: error.message };
288
297
  }
@@ -292,6 +301,80 @@ const JaakStamps = class {
292
301
  this.completeProcess(true);
293
302
  }
294
303
  }
304
+ async loadMobileNetModel() {
305
+ try {
306
+ this.debugLog('🤖 Loading MobileNet model...');
307
+ // Load class map
308
+ const classResponse = await fetch(this.MOBILENET_CLASSES_PATH);
309
+ if (!classResponse.ok) {
310
+ throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`);
311
+ }
312
+ this.mobileNetClassMap = await classResponse.json();
313
+ this.debugLog('📋 MobileNet classes loaded:', this.mobileNetClassMap);
314
+ // Load model
315
+ const sessionOptions = this.getSessionOptions();
316
+ this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, sessionOptions);
317
+ this.debugLog('✅ MobileNet model loaded successfully');
318
+ }
319
+ catch (error) {
320
+ this.debugLog('❌ Error loading MobileNet model:', error);
321
+ throw error;
322
+ }
323
+ }
324
+ preprocessMobileNet(canvas) {
325
+ // Create a temporary canvas for MobileNet preprocessing (224x224)
326
+ const tempCanvas = document.createElement('canvas');
327
+ tempCanvas.width = 224;
328
+ tempCanvas.height = 224;
329
+ const tempCtx = tempCanvas.getContext('2d');
330
+ // Draw the cropped image onto the 224x224 canvas
331
+ tempCtx.drawImage(canvas, 0, 0, 224, 224);
332
+ // Get image data and preprocess for MobileNet
333
+ const imageData = tempCtx.getImageData(0, 0, 224, 224);
334
+ const data = imageData.data;
335
+ const hw = 224 * 224;
336
+ const arr = new Float32Array(3 * hw);
337
+ // Normalize pixels: (pixel/255 - 0.5) / 0.5 = (pixel - 127.5) / 127.5
338
+ for (let i = 0; i < hw; i++) {
339
+ arr[i] = (data[i * 4 + 0] / 255 - 0.5) / 0.5; // R
340
+ arr[hw + i] = (data[i * 4 + 1] / 255 - 0.5) / 0.5; // G
341
+ arr[2 * hw + i] = (data[i * 4 + 2] / 255 - 0.5) / 0.5; // B
342
+ }
343
+ return new window.ort.Tensor('float32', arr, [1, 3, 224, 224]);
344
+ }
345
+ async classifyDocument(canvas) {
346
+ if (!this.mobileNetSession || !this.mobileNetClassMap) {
347
+ this.debugLog('⚠️ MobileNet model not loaded');
348
+ return null;
349
+ }
350
+ try {
351
+ this.debugLog('🔍 Classifying document...');
352
+ // Preprocess image for MobileNet
353
+ const inputTensor = this.preprocessMobileNet(canvas);
354
+ // Run inference
355
+ const feeds = { input: inputTensor };
356
+ const results = await this.mobileNetSession.run(feeds);
357
+ const output = results[Object.keys(results)[0]].data;
358
+ // Find the class with highest confidence
359
+ const maxIdx = output.reduce((bestIdx, val, idx, arr) => val > arr[bestIdx] ? idx : bestIdx, 0);
360
+ const confidence = output[maxIdx];
361
+ const className = this.mobileNetClassMap[maxIdx.toString()] || "unknown";
362
+ this.debugLog('📄 Document classification result:', {
363
+ class: className,
364
+ confidence: confidence.toFixed(3),
365
+ classIndex: maxIdx
366
+ });
367
+ return {
368
+ class: className,
369
+ confidence: confidence,
370
+ classIndex: maxIdx
371
+ };
372
+ }
373
+ catch (error) {
374
+ this.debugLog('❌ Error classifying document:', error);
375
+ return null;
376
+ }
377
+ }
295
378
  cleanup() {
296
379
  if (this.animationId) {
297
380
  cancelAnimationFrame(this.animationId);
@@ -319,11 +402,16 @@ const JaakStamps = class {
319
402
  this.captureCtx = undefined;
320
403
  this.captureCanvas = undefined;
321
404
  }
322
- // Disposed ONNX session
405
+ // Disposed ONNX sessions
323
406
  if (this.session) {
324
407
  this.session.release?.();
325
408
  this.session = undefined;
326
409
  }
410
+ if (this.mobileNetSession) {
411
+ this.mobileNetSession.release?.();
412
+ this.mobileNetSession = undefined;
413
+ }
414
+ this.mobileNetClassMap = undefined;
327
415
  this.isModelPreloaded = false;
328
416
  this.debugLog('🧹 Canvas pool cleaned up');
329
417
  }
@@ -454,18 +542,22 @@ const JaakStamps = class {
454
542
  // Check if model is already preloaded
455
543
  if (!this.session) {
456
544
  this.isLoading = true;
457
- this.statusMessage = "Cargando modelo de detección...";
545
+ this.statusMessage = "Cargando modelos...";
458
546
  this.statusColor = "#007bff";
459
547
  const modelPath = this.MODEL_PATH;
460
- this.debugLog('🤖 Loading model:', modelPath);
548
+ this.debugLog('🤖 Loading detection model:', modelPath);
461
549
  const sessionOptions = this.getSessionOptions();
462
550
  this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
551
+ // Load MobileNet model if classification is enabled and not already loaded
552
+ if (this.useDocumentClassification && !this.mobileNetSession) {
553
+ await this.loadMobileNetModel();
554
+ }
463
555
  this.isModelPreloaded = true;
464
556
  this.emitReadyEvent();
465
557
  }
466
558
  else {
467
- this.debugLog('🚀 Using preloaded model');
468
- this.statusMessage = "Usando modelo precargado...";
559
+ this.debugLog('🚀 Using preloaded models');
560
+ this.statusMessage = "Usando modelos precargados...";
469
561
  this.statusColor = "#007bff";
470
562
  }
471
563
  this.statusMessage = "Configurando cámara...";
@@ -684,7 +776,9 @@ const JaakStamps = class {
684
776
  corners?.forEach(corner => corner.classList.add('perfect-match'));
685
777
  if (!this.hasScreenshotTaken) {
686
778
  this.lastDetectedBox = bestBox;
687
- this.takeScreenshot();
779
+ this.takeScreenshot().catch(error => {
780
+ this.debugLog('❌ Error taking screenshot:', error);
781
+ });
688
782
  this.hasScreenshotTaken = true;
689
783
  // Reset para permitir segunda captura
690
784
  setTimeout(() => {
@@ -767,7 +861,7 @@ const JaakStamps = class {
767
861
  ctx.strokeRect(x, y, w, h);
768
862
  });
769
863
  }
770
- takeScreenshot() {
864
+ async takeScreenshot() {
771
865
  if (!this.videoRef || !this.lastDetectedBox)
772
866
  return;
773
867
  // Activar animación
@@ -801,6 +895,29 @@ const JaakStamps = class {
801
895
  // Captura del frente usando canvas reutilizado
802
896
  this.capturedFullFrame = this.captureCanvas.toDataURL('image/png');
803
897
  this.capturedCroppedId = croppedCanvas.toDataURL('image/png');
898
+ // Check if document classification is enabled
899
+ if (this.useDocumentClassification) {
900
+ // Load MobileNet model if not loaded yet (lazy loading)
901
+ if (!this.mobileNetSession) {
902
+ try {
903
+ await this.loadMobileNetModel();
904
+ }
905
+ catch (error) {
906
+ this.debugLog('⚠️ Failed to load classification model, continuing without classification:', error);
907
+ }
908
+ }
909
+ // Classify the cropped document if model is available
910
+ if (this.mobileNetSession) {
911
+ const classification = await this.classifyDocument(croppedCanvas);
912
+ if (classification && classification.class === 'passport') {
913
+ // If it's a passport, skip back capture since passports don't have a back side
914
+ this.debugLog('📄 Passport detected - skipping back capture');
915
+ this.completeProcess(true);
916
+ return;
917
+ }
918
+ }
919
+ }
920
+ // For other IDs, continue with normal flow (back capture)
804
921
  this.captureStep = 'back';
805
922
  this.statusMessage = "Voltee la identificación y muestre la parte trasera";
806
923
  this.statusColor = "#007bff";
@@ -930,7 +1047,7 @@ const JaakStamps = class {
930
1047
  this.cleanup();
931
1048
  }
932
1049
  render() {
933
- return (h("div", { key: '7cd80970b12ba60949ff34b5a9405b9782267918', class: "detector-container" }, h("div", { key: '0e66e46a524bd37f60f30504a270f72b64a97fc1', class: "video-container" }, h("video", { key: '0c1b0719c626659e54bec8ce3383f50d990c32c1', ref: el => this.videoRef = el, autoplay: true, muted: true, playsinline: true, class: this.shouldMirrorVideo ? 'mirror' : '', style: { display: this.isVideoActive ? 'block' : 'none' } }), h("canvas", { key: '09fc3a2d511e48186099a0ff5d3d6378f15fe1c4', ref: el => this.canvasRef = el, class: this.shouldMirrorVideo ? 'mirror' : '' }), this.isMaskReady && (h("div", { key: '70a31b04c9543fc0834a848013daf06c654e4194', class: "overlay-mask" }, h("div", { key: '050dcdaa59b028b5c379de310a80ca7191bf8af8', class: "card-outline" }, h("div", { key: 'adef93f2e6b16b308dc5d67469f35c2025ca160f', class: "side side-top" }), h("div", { key: '4900bed8cc2607f92163a25bbf3c0d3a272b9840', class: "side side-right" }), h("div", { key: '11fc9da6cfe04b993bf4a72413da2344122b21e4', class: "side side-bottom" }), h("div", { key: 'ed95ac2578ba045e003d61144aecd09ef4f01561', class: "side side-left" }), h("div", { key: '37eec8aad0a0d449174d52caab7aec5a25d11731', class: "corner corner-tl" }), h("div", { key: 'c7247e71d8936d0a30f415f73377713a8c457420', class: "corner corner-tr" }), h("div", { key: 'e131e0c3bd66068ae1d33cd7211edafd92dfbe62', class: "corner corner-bl" }), h("div", { key: '89234ddcde735501907276e10287af983033ec85', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (h("div", { key: '4b2543dd05f173b3ee4e3053ed7b62d4e7b75e63', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (h("button", { key: 'e7e2b2b1486f7024fc2d42073313833bca88e315', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")))), this.isCapturing && (h("div", { key: '6ca8283fe3eb1c5b2700c0d313afb51c2db3ea7f', class: "capture-animation" })), this.showFlipAnimation && (h("div", { key: 'eaed1200385a98a8750cdaef2dad9f8ff63914f3', class: "flip-animation" }, h("div", { key: 'dbe9bfc929fa8b13cadc60cdece603c48dbcbd4c', class: "id-card-icon" }), h("div", { key: '82b9de0910a993b6cf3af7ecdf43de41d495c181', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (h("div", { key: '92ef47686b0fbf91f6a3f8c3c3f23a78a6fc76f8', class: "success-animation" }, h("div", { key: '35aeb41dce144fc844d7447a958473834f6b0843', class: "check-icon" }), h("div", { key: '2ba06161a8d665394803ce8cc90320b154048c0b', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (h("div", { key: '8abc4f5724ca6543698f7ca9116ccfc9c042edbd', class: "loading-overlay" }, h("div", { key: '5c8f73bb7c30c6a4c304e96e4db2bf75dc89b89e', class: "loading-spinner" }), h("div", { key: '8f5665f21be98ddccb9d9d2c6412e4edf4571a51', class: "loading-text" }, this.statusMessage))), h("div", { key: '00316bee3c56f07b9771c400f5b84b7e14dca4af', class: "watermark" }, h("img", { key: 'd7f58ffa993405912f8aa26386f39caa72e7a000', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
1050
+ 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" })))));
934
1051
  }
935
1052
  };
936
1053
  JaakStamps.style = myComponentCss;