datakeen-session-react 1.1.202-dev.16 → 1.1.202-dev.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/cjs/components/DatakeenSession.js +17 -16
  2. package/dist/cjs/components/card-capture-guide/CardCaptureGuide.js +139 -0
  3. package/dist/cjs/components/card-capture-guide/captureTelemetry.js +81 -0
  4. package/dist/cjs/components/card-capture-guide/guidance.js +48 -0
  5. package/dist/cjs/components/card-capture-guide/guideCore.js +389 -0
  6. package/dist/cjs/components/card-capture-guide/guideRuntime.js +118 -0
  7. package/dist/cjs/components/card-capture-guide/modelLoader.js +46 -0
  8. package/dist/cjs/components/card-capture-guide/useCaptureGuideThresholds.js +33 -0
  9. package/dist/cjs/components/card-capture-guide/useCardCaptureGuide.js +117 -0
  10. package/dist/cjs/components/card-capture-guide/useMinDisplay.js +30 -0
  11. package/dist/cjs/components/document-collection/DocumentCollection.js +9 -0
  12. package/dist/cjs/components/id-check/Photo.js +230 -122
  13. package/dist/cjs/components/id-check/card-capture/CardCapture.js +270 -0
  14. package/dist/cjs/components/id-check/card-capture/DynamicCardMask.js +85 -0
  15. package/dist/cjs/components/id-check/card-capture/geometry.js +119 -0
  16. package/dist/cjs/components/id-check/card-capture/guideTone.js +15 -0
  17. package/dist/cjs/components/jdi/JDIDocumentSelection.js +9 -0
  18. package/dist/cjs/components/selfie/Video.js +2 -2
  19. package/dist/cjs/components/selfie/selfie-flow/SelfieFlow.js +4 -2
  20. package/dist/cjs/components/session/DocumentCheck.js +37 -2
  21. package/dist/cjs/components/session/EndFlow.js +4 -0
  22. package/dist/cjs/components/session/Selfie.js +1 -1
  23. package/dist/cjs/components/signature-electronic/SignatureElectronic.js +9 -2
  24. package/dist/cjs/components/start-flow/Start.js +4 -0
  25. package/dist/cjs/components/template/TemplateNodeRenderer.js +3 -1
  26. package/dist/cjs/components/ui/Button.js +3 -3
  27. package/dist/cjs/context/CardCaptureGuideContext.js +16 -0
  28. package/dist/cjs/hooks/useClientInfo.js +7 -0
  29. package/dist/cjs/hooks/useUserInputForm.js +3 -1
  30. package/dist/cjs/i18n/en.json.js +57 -1
  31. package/dist/cjs/i18n/es.json.js +57 -1
  32. package/dist/cjs/i18n/fr.json.js +57 -1
  33. package/dist/cjs/index.css.js +1 -1
  34. package/dist/cjs/index.js +15 -0
  35. package/dist/cjs/preview/DatakeenJourneyPreview.js +257 -0
  36. package/dist/cjs/preview/PreviewAutomaticStep.js +23 -0
  37. package/dist/cjs/preview/PreviewBranchPicker.js +54 -0
  38. package/dist/cjs/preview/PreviewCaptureDisabled.js +19 -0
  39. package/dist/cjs/preview/previewAdapter.js +27 -0
  40. package/dist/cjs/preview/previewMode.js +21 -0
  41. package/dist/cjs/preview/previewNavigation.js +105 -0
  42. package/dist/cjs/services/api.js +5 -0
  43. package/dist/cjs/services/cameraService.js +6 -0
  44. package/dist/cjs/services/realtime/sseClient.js +4 -0
  45. package/dist/cjs/services/sessionService.js +50 -0
  46. package/dist/cjs/utils/cssLoader.js +6 -4
  47. package/dist/cjs/utils/isMobileDevice.js +8 -0
  48. package/dist/esm/components/DatakeenSession.js +17 -16
  49. package/dist/esm/components/card-capture-guide/CardCaptureGuide.js +135 -0
  50. package/dist/esm/components/card-capture-guide/captureTelemetry.js +78 -0
  51. package/dist/esm/components/card-capture-guide/guidance.js +44 -0
  52. package/dist/esm/components/card-capture-guide/guideCore.js +372 -0
  53. package/dist/esm/components/card-capture-guide/guideRuntime.js +115 -0
  54. package/dist/esm/components/card-capture-guide/modelLoader.js +42 -0
  55. package/dist/esm/components/card-capture-guide/useCaptureGuideThresholds.js +31 -0
  56. package/dist/esm/components/card-capture-guide/useCardCaptureGuide.js +115 -0
  57. package/dist/esm/components/card-capture-guide/useMinDisplay.js +28 -0
  58. package/dist/esm/components/document-collection/DocumentCollection.js +10 -1
  59. package/dist/esm/components/id-check/Photo.js +232 -124
  60. package/dist/esm/components/id-check/card-capture/CardCapture.js +266 -0
  61. package/dist/esm/components/id-check/card-capture/DynamicCardMask.js +81 -0
  62. package/dist/esm/components/id-check/card-capture/geometry.js +110 -0
  63. package/dist/esm/components/id-check/card-capture/guideTone.js +13 -0
  64. package/dist/esm/components/jdi/JDIDocumentSelection.js +9 -0
  65. package/dist/esm/components/selfie/Video.js +2 -2
  66. package/dist/esm/components/selfie/selfie-flow/SelfieFlow.js +4 -2
  67. package/dist/esm/components/session/DocumentCheck.js +37 -2
  68. package/dist/esm/components/session/EndFlow.js +4 -0
  69. package/dist/esm/components/session/Selfie.js +1 -1
  70. package/dist/esm/components/signature-electronic/SignatureElectronic.js +9 -2
  71. package/dist/esm/components/start-flow/Start.js +4 -0
  72. package/dist/esm/components/template/TemplateNodeRenderer.js +3 -1
  73. package/dist/esm/components/ui/Button.js +3 -3
  74. package/dist/esm/context/CardCaptureGuideContext.js +13 -0
  75. package/dist/esm/hooks/useClientInfo.js +7 -0
  76. package/dist/esm/hooks/useUserInputForm.js +3 -1
  77. package/dist/esm/i18n/en.json.js +55 -2
  78. package/dist/esm/i18n/es.json.js +55 -2
  79. package/dist/esm/i18n/fr.json.js +55 -2
  80. package/dist/esm/index.css.js +1 -1
  81. package/dist/esm/index.js +6 -0
  82. package/dist/esm/preview/DatakeenJourneyPreview.js +253 -0
  83. package/dist/esm/preview/PreviewAutomaticStep.js +19 -0
  84. package/dist/esm/preview/PreviewBranchPicker.js +48 -0
  85. package/dist/esm/preview/PreviewCaptureDisabled.js +15 -0
  86. package/dist/esm/preview/previewAdapter.js +25 -0
  87. package/dist/esm/preview/previewMode.js +15 -0
  88. package/dist/esm/preview/previewNavigation.js +98 -0
  89. package/dist/esm/services/api.js +5 -0
  90. package/dist/esm/services/cameraService.js +6 -0
  91. package/dist/esm/services/realtime/sseClient.js +4 -0
  92. package/dist/esm/services/sessionService.js +49 -1
  93. package/dist/esm/utils/cssLoader.js +6 -4
  94. package/dist/esm/utils/isMobileDevice.js +8 -0
  95. package/dist/types/components/card-capture-guide/CardCaptureGuide.d.ts +46 -0
  96. package/dist/types/components/card-capture-guide/guidance.d.ts +45 -0
  97. package/dist/types/components/card-capture-guide/guideCore.d.ts +96 -0
  98. package/dist/types/components/card-capture-guide/guideRuntime.d.ts +13 -0
  99. package/dist/types/components/card-capture-guide/modelLoader.d.ts +13 -0
  100. package/dist/types/components/card-capture-guide/useCardCaptureGuide.d.ts +38 -0
  101. package/dist/types/index.d.ts +8 -0
  102. package/dist/types/preview/DatakeenJourneyPreview.d.ts +6 -0
  103. package/dist/types/preview/types.d.ts +77 -0
  104. package/dist/types/services/documentTemplate.d.ts +13 -0
  105. package/dist/types/types/camera.d.ts +3 -0
  106. package/dist/types/types/session.d.ts +268 -1
  107. package/dist/types/utils/cssLoader.d.ts +0 -4
  108. package/package.json +2 -1
@@ -0,0 +1,78 @@
1
+ import { __assign } from '../../node_modules/tslib/tslib.es6.js';
2
+
3
+ /**
4
+ * Builds the per-capture telemetry of the card guide (APP3-2119): how long each guidance code was shown,
5
+ * time to capture, model and inference timings. It only ever receives codes and durations, so nothing else
6
+ * (image, corners, metrics) can end up in the payload.
7
+ */
8
+ var CaptureTelemetryCollector = /** @class */ (function () {
9
+ function CaptureTelemetryCollector(init) {
10
+ this.init = init;
11
+ this.order = [];
12
+ this.totals = new Map();
13
+ this.current = null;
14
+ this.inferenceTotalMs = 0;
15
+ this.inferenceCount = 0;
16
+ }
17
+ CaptureTelemetryCollector.prototype.guidance = function (code, at) {
18
+ this.close(at);
19
+ var entry = this.totals.get(code);
20
+ if (entry)
21
+ entry.count += 1;
22
+ else {
23
+ this.totals.set(code, { count: 1, totalMs: 0 });
24
+ this.order.push(code);
25
+ }
26
+ this.current = { code: code, since: at };
27
+ };
28
+ CaptureTelemetryCollector.prototype.modelLoaded = function (ms) {
29
+ this.modelLoadMs = Math.max(0, Math.round(ms));
30
+ };
31
+ CaptureTelemetryCollector.prototype.inference = function (ms) {
32
+ this.inferenceTotalMs += Math.max(0, ms);
33
+ this.inferenceCount += 1;
34
+ };
35
+ CaptureTelemetryCollector.prototype.build = function (_a) {
36
+ var _this = this;
37
+ var trigger = _a.trigger, guideStatus = _a.guideStatus, at = _a.at;
38
+ this.close(at);
39
+ var payload = {
40
+ nodeId: this.init.nodeId,
41
+ side: this.init.side,
42
+ trigger: trigger,
43
+ guideStatus: guideStatus,
44
+ timeToCaptureMs: Math.round(Math.abs(at - this.init.startedAt)),
45
+ inferenceCount: this.inferenceCount,
46
+ deviceType: this.init.deviceType,
47
+ guidance: this.order.map(function (code) { return (__assign({ code: code }, _this.totals.get(code))); }),
48
+ };
49
+ if (this.init.documentType)
50
+ payload.documentType = this.init.documentType;
51
+ if (this.modelLoadMs !== undefined)
52
+ payload.modelLoadMs = this.modelLoadMs;
53
+ if (this.inferenceCount > 0)
54
+ payload.meanInferenceMs = Math.round(this.inferenceTotalMs / this.inferenceCount);
55
+ return payload;
56
+ };
57
+ CaptureTelemetryCollector.prototype.close = function (at) {
58
+ if (!this.current)
59
+ return;
60
+ var entry = this.totals.get(this.current.code);
61
+ entry.totalMs += Math.max(0, Math.round(at - this.current.since));
62
+ this.current = null;
63
+ };
64
+ return CaptureTelemetryCollector;
65
+ }());
66
+ /** Coarse device class from the user agent and the viewport; no fingerprinting detail is kept. */
67
+ function detectDeviceType() {
68
+ if (typeof navigator === "undefined")
69
+ return "desktop";
70
+ var ua = navigator.userAgent || "";
71
+ if (/iPad|Tablet/i.test(ua) || (/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1))
72
+ return "tablet";
73
+ if (/Mobi|Android|iPhone/i.test(ua))
74
+ return "mobile";
75
+ return "desktop";
76
+ }
77
+
78
+ export { CaptureTelemetryCollector, detectDeviceType };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The guidance channel of CardCaptureGuide: one machine-readable CODE per situation, pushed in real time through
3
+ * `onGuidance` (on every change) and `onFrame` (every inference, ~8/s). Map the codes to your own UI/copy:
4
+ *
5
+ * too_blurry -> "Ajuster la focalisation" too_dark -> "Augmenter la luminosité" bright_spot -> "Éviter les reflets"
6
+ */
7
+ var GUIDANCE_CODES = [
8
+ "no_card", // nothing that looks like a card in view
9
+ "too_far", // card found but too small / too few camera pixels -> move closer
10
+ "too_dark", // not enough light (card or whole scene)
11
+ "card_detected", // card in view, still moving
12
+ "hold_still", // card steady, capture about to fire
13
+ "too_blurry", // card steady but out of focus
14
+ "bright_spot", // reflection / glare on the card
15
+ "ready", // steady + sharp + lit + no glare: the capture fires (once)
16
+ ];
17
+ /** "warning" = the user must change something; "info" = progress; "success" = capture. */
18
+ var GUIDANCE_SEVERITY = {
19
+ no_card: "info",
20
+ too_far: "warning",
21
+ too_dark: "warning",
22
+ card_detected: "info",
23
+ hold_still: "info",
24
+ too_blurry: "warning",
25
+ bright_spot: "warning",
26
+ ready: "success",
27
+ };
28
+ function toGuidanceEvent(g, previousCode, message, timestamp) {
29
+ var code = g.state;
30
+ var q = g.quality;
31
+ return {
32
+ code: code,
33
+ previousCode: previousCode,
34
+ severity: GUIDANCE_SEVERITY[code],
35
+ message: message,
36
+ presence: g.presence,
37
+ corners: g.corners,
38
+ metrics: q ? { blur: q.blur, brightness: q.brightness, glare: q.blob, cardSizePx: q.nativeLong } : null,
39
+ frameBrightness: g.frameBrightness,
40
+ timestamp: timestamp,
41
+ };
42
+ }
43
+
44
+ export { GUIDANCE_CODES, GUIDANCE_SEVERITY, toGuidanceEvent };
@@ -0,0 +1,372 @@
1
+ /**
2
+ * MIRRORED from model-id-capture-guidance/web/src/guide-core.mjs (parity-tested there against the Python reference).
3
+ * Keep both in sync. Pure (DOM-free) logic for the browser card-guide v2: letterbox mapping, output decoding,
4
+ * the geometric quad gate, and the temporal tracker that turns noisy per-frame predictions
5
+ * into stable guidance states. Shared by the React component, the plain-JS demo and the Node
6
+ * unit tests. Keep numerically identical to training_v2/model.py::decode and
7
+ * eval/quad_validation.py (parity is checked in tests/run_core_test.js).
8
+ *
9
+ * Model I/O (card_guide_v2.onnx): input (1,3,256,256) letterboxed + ImageNet-normalised;
10
+ * outputs cls(1,3 softmax: none,id_document,other_card) heat(1,4,64,64) off(1,8,64,64) vis(1,4) glob(1,4,2).
11
+ */
12
+ var SIZE = 256;
13
+ var HM = 64;
14
+ var AGREE_DIST = 0.08; // heatmap peak must be this close to the global regression (canvas units) to be trusted
15
+ /** Letterbox a (w,h) frame into the SIZExSIZE canvas. */
16
+ function letterbox(w, h) {
17
+ var scale = SIZE / Math.max(w, h);
18
+ var nw = Math.round(w * scale), nh = Math.round(h * scale);
19
+ return { scale: scale, nw: nw, nh: nh, ox: Math.floor((SIZE - nw) / 2), oy: Math.floor((SIZE - nh) / 2) };
20
+ }
21
+ /**
22
+ * Decode raw model outputs. Returns presence (P(id)+P(other)) and 4 corners (TL,TR,BR,BL)
23
+ * normalised to the *source frame* (may fall outside [0,1] when a corner is out of frame).
24
+ */
25
+ function decode(out, srcW, srcH) {
26
+ var cls = out.cls, heat = out.heat, off = out.off, vis = out.vis, glob = out.glob;
27
+ var lb = letterbox(srcW, srcH), pts = [];
28
+ for (var k = 0; k < 4; k++) {
29
+ var cx = glob[k * 2], cy = glob[k * 2 + 1];
30
+ if (vis[k] > 0.5) {
31
+ var best = -1, bi = 0;
32
+ var base = k * HM * HM;
33
+ for (var i = 0; i < HM * HM; i++)
34
+ if (heat[base + i] > best) {
35
+ best = heat[base + i];
36
+ bi = i;
37
+ }
38
+ var iy = Math.floor(bi / HM), ix = bi % HM;
39
+ var px = (ix + 0.5 + off[(2 * k) * HM * HM + bi]) / HM;
40
+ var py = (iy + 0.5 + off[(2 * k + 1) * HM * HM + bi]) / HM;
41
+ if (Math.hypot(px - cx, py - cy) < AGREE_DIST) {
42
+ cx = px;
43
+ cy = py;
44
+ }
45
+ }
46
+ pts.push([((cx * SIZE - lb.ox) / lb.scale) / srcW, ((cy * SIZE - lb.oy) / lb.scale) / srcH]);
47
+ }
48
+ return { presence: cls[1] + cls[2], idProb: cls[1], otherProb: cls[2], corners: pts };
49
+ }
50
+ var MIN_AREA_FRACTION = 0.01, MIN_ASPECT = 1.1, MAX_ASPECT = 2.1, MIN_ANGLE = 40, MAX_ANGLE = 140, MIN_EDGE_RATIO = 0.3;
51
+ /** Port of quad_rejection_reason. quad in pixels. Returns null if plausible, else a reason. */
52
+ function quadRejectionReason(quad, w, h) {
53
+ var q = quad;
54
+ if (!q.every(function (_a) {
55
+ var x = _a[0], y = _a[1];
56
+ return isFinite(x) && isFinite(y);
57
+ }))
58
+ return "non-finite";
59
+ var signs = [];
60
+ for (var i = 0; i < 4; i++) {
61
+ var a = q[i], b = q[(i + 1) % 4], c = q[(i + 2) % 4];
62
+ signs.push(Math.sign((b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])));
63
+ }
64
+ if (signs.includes(0) || new Set(signs).size !== 1)
65
+ return "not convex";
66
+ var area = 0;
67
+ for (var i = 0; i < 4; i++)
68
+ area += q[i][0] * q[(i + 1) % 4][1] - q[(i + 1) % 4][0] * q[i][1];
69
+ area = Math.abs(area) / 2;
70
+ if (area < MIN_AREA_FRACTION * w * h)
71
+ return "area too small";
72
+ var edges = q.map(function (p, i) { return Math.hypot(q[(i + 1) % 4][0] - p[0], q[(i + 1) % 4][1] - p[1]); });
73
+ if (Math.min.apply(Math, edges) / Math.max.apply(Math, edges) < MIN_EDGE_RATIO)
74
+ return "degenerate edge ratio";
75
+ for (var i = 0; i < 4; i++) {
76
+ var p = q[i], a = q[(i + 3) % 4], b = q[(i + 1) % 4];
77
+ var u = [a[0] - p[0], a[1] - p[1]], v = [b[0] - p[0], b[1] - p[1]];
78
+ var cos = (u[0] * v[0] + u[1] * v[1]) / (Math.hypot.apply(Math, u) * Math.hypot.apply(Math, v) + 1e-9);
79
+ var ang = (Math.acos(Math.max(-1, Math.min(1, cos))) * 180) / Math.PI;
80
+ if (ang < MIN_ANGLE || ang > MAX_ANGLE)
81
+ return "corner angle";
82
+ }
83
+ var wm = (edges[0] + edges[2]) / 2, hm = (edges[1] + edges[3]) / 2;
84
+ var aspect = Math.max(wm, hm) / Math.max(Math.min(wm, hm), 1e-9);
85
+ if (aspect < MIN_ASPECT || aspect > MAX_ASPECT)
86
+ return "aspect";
87
+ return null;
88
+ }
89
+ // ---------------------------------------------------------------------------------------------------------------
90
+ // Capture-quality metrics (blur + glare), measured on the card quad warped to a fixed-size patch.
91
+ // Reference implementation + calibration: eval/quality_metrics.py (parity-tested in tests/run_core_test.js).
92
+ // ---------------------------------------------------------------------------------------------------------------
93
+ var WARP_W = 320;
94
+ var SAT_THR = 245; // a pixel is "saturated" when R, G and B are all >= this
95
+ var CELL = 8;
96
+ /** Solve the 3x3 homography H (h33 = 1) that maps each src[i] -> dst[i] (4 point pairs). */
97
+ function homography(src, dst) {
98
+ var _a, _b;
99
+ var A = [], b = [];
100
+ for (var i = 0; i < 4; i++) {
101
+ var _c = src[i], x = _c[0], y = _c[1], _d = dst[i], u = _d[0], v = _d[1];
102
+ A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]);
103
+ b.push(u);
104
+ A.push([0, 0, 0, x, y, 1, -v * x, -v * y]);
105
+ b.push(v);
106
+ }
107
+ for (var c = 0; c < 8; c++) { // gaussian elimination with partial pivoting
108
+ var piv = c;
109
+ for (var r = c + 1; r < 8; r++)
110
+ if (Math.abs(A[r][c]) > Math.abs(A[piv][c]))
111
+ piv = r;
112
+ _a = [A[piv], A[c]], A[c] = _a[0], A[piv] = _a[1];
113
+ _b = [b[piv], b[c]], b[c] = _b[0], b[piv] = _b[1];
114
+ for (var r = c + 1; r < 8; r++) {
115
+ var f = A[r][c] / A[c][c];
116
+ for (var k = c; k < 8; k++)
117
+ A[r][k] -= f * A[c][k];
118
+ b[r] -= f * b[c];
119
+ }
120
+ }
121
+ var h = new Array(8);
122
+ for (var r = 7; r >= 0; r--) {
123
+ var s = b[r];
124
+ for (var k = r + 1; k < 8; k++)
125
+ s -= A[r][k] * h[k];
126
+ h[r] = s / A[r][r];
127
+ }
128
+ return h;
129
+ }
130
+ /** Perspective-warp the quad (TL,TR,BR,BL in frame pixels) out of an RGBA frame into a WARP_W-wide RGB patch (bilinear, edge-clamped). */
131
+ function warpCard(frame, quad) {
132
+ var data = frame.data, W = frame.width, H = frame.height, q = quad;
133
+ var d = function (a, b) { return Math.hypot(q[a][0] - q[b][0], q[a][1] - q[b][1]); };
134
+ var w = (d(0, 1) + d(3, 2)) / 2, h = (d(0, 3) + d(1, 2)) / 2;
135
+ var asp = Math.min(1.8, Math.max(1.2, Math.max(w, h) / Math.max(Math.min(w, h), 1e-6)));
136
+ var pw = WARP_W, ph = Math.round(WARP_W / asp);
137
+ var hh = homography([[0, 0], [pw - 1, 0], [pw - 1, ph - 1], [0, ph - 1]], q); // dst -> src
138
+ var out = new Uint8ClampedArray(pw * ph * 3);
139
+ for (var y = 0; y < ph; y++)
140
+ for (var x = 0; x < pw; x++) {
141
+ var den = hh[6] * x + hh[7] * y + 1;
142
+ var sx = (hh[0] * x + hh[1] * y + hh[2]) / den, sy = (hh[3] * x + hh[4] * y + hh[5]) / den;
143
+ sx = Math.min(W - 1, Math.max(0, sx));
144
+ sy = Math.min(H - 1, Math.max(0, sy));
145
+ var x0 = Math.floor(sx), y0 = Math.floor(sy), x1 = Math.min(W - 1, x0 + 1), y1 = Math.min(H - 1, y0 + 1), fx = sx - x0, fy = sy - y0;
146
+ for (var c = 0; c < 3; c++) {
147
+ var v = (data[(y0 * W + x0) * 4 + c] * (1 - fx) + data[(y0 * W + x1) * 4 + c] * fx) * (1 - fy) + (data[(y1 * W + x0) * 4 + c] * (1 - fx) + data[(y1 * W + x1) * 4 + c] * fx) * fy;
148
+ out[(y * pw + x) * 3 + c] = Math.round(v);
149
+ }
150
+ }
151
+ return { data: out, width: pw, height: ph };
152
+ }
153
+ /** Mean luma (0..255) of an RGB patch. Card patch < ~55 (or whole frame < ~45) = not enough light; normal webcam scenes sit at 95-165. */
154
+ function brightnessScore(patch) {
155
+ var data = patch.data, w = patch.width, h = patch.height;
156
+ var sum = 0;
157
+ for (var i = 0; i < w * h; i++)
158
+ sum += 0.299 * data[i * 3] + 0.587 * data[i * 3 + 1] + 0.114 * data[i * 3 + 2];
159
+ return sum / (w * h);
160
+ }
161
+ /** Mean luma of a RGBA frame region - used on the model's letterboxed canvas so it works even when no card is in view. */
162
+ function frameBrightness(rgba, width, rect) {
163
+ if (rect === void 0) { rect = null; }
164
+ var x0 = rect ? rect.x : 0, y0 = rect ? rect.y : 0, rw = rect ? rect.w : width, rh = rect ? rect.h : rgba.length / 4 / width;
165
+ var sum = 0;
166
+ for (var y = y0; y < y0 + rh; y++)
167
+ for (var x = x0; x < x0 + rw; x++) {
168
+ var i = (y * width + x) * 4;
169
+ sum += 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];
170
+ }
171
+ return sum / (rw * rh);
172
+ }
173
+ /** Variance of the 3x3 Laplacian on the gray patch (higher = sharper). ~<400 blurry, >=600 sharp (calibrated on webcam video). */
174
+ function blurScore(patch) {
175
+ var data = patch.data, w = patch.width, h = patch.height, g = new Float32Array(w * h);
176
+ for (var i = 0; i < w * h; i++)
177
+ g[i] = Math.round(0.299 * data[i * 3] + 0.587 * data[i * 3 + 1] + 0.114 * data[i * 3 + 2]);
178
+ var sum = 0, sum2 = 0, n = 0;
179
+ for (var y = 1; y < h - 1; y++)
180
+ for (var x = 1; x < w - 1; x++) {
181
+ var i = y * w + x, l = -4 * g[i] + g[i - 1] + g[i + 1] + g[i - w] + g[i + w];
182
+ sum += l;
183
+ sum2 += l * l;
184
+ n++;
185
+ }
186
+ var mean = sum / n;
187
+ return sum2 / n - mean * mean;
188
+ }
189
+ /** Glare: share of 8x8 cells that are mostly saturated-white (blob), plus the raw saturated-pixel share. blob >= 0.012 means a highlight >~1.5% of the card. */
190
+ function glareScore(patch) {
191
+ var data = patch.data, w = patch.width, h = patch.height, cw = Math.floor(w / CELL), ch = Math.floor(h / CELL);
192
+ var sat = 0, cellsHit = 0;
193
+ for (var cy = 0; cy < ch; cy++)
194
+ for (var cx = 0; cx < cw; cx++) {
195
+ var s = 0;
196
+ for (var y = 0; y < CELL; y++)
197
+ for (var x = 0; x < CELL; x++) {
198
+ var i = ((cy * CELL + y) * w + cx * CELL + x) * 3;
199
+ if (Math.min(data[i], data[i + 1], data[i + 2]) >= SAT_THR)
200
+ s++;
201
+ }
202
+ if (s / (CELL * CELL) > 0.5)
203
+ cellsHit++;
204
+ }
205
+ for (var i = 0; i < w * h; i++)
206
+ if (Math.min(data[i * 3], data[i * 3 + 1], data[i * 3 + 2]) >= SAT_THR)
207
+ sat++;
208
+ return { sat: sat / (w * h), blob: cellsHit / (cw * ch) };
209
+ }
210
+ /**
211
+ * One call for the browser glue: frame = RGBA ImageData of the video (any scale), quad = the 4 corners in THAT frame's pixels,
212
+ * nativeScale = (frame px per original video px) so `nativeLong` reports the card's long side in true camera pixels.
213
+ */
214
+ function measureQuality(frame, quad, nativeScale) {
215
+ if (nativeScale === void 0) { nativeScale = 1; }
216
+ var patch = warpCard(frame, quad), g = glareScore(patch);
217
+ var d = function (a, b) { return Math.hypot(quad[a][0] - quad[b][0], quad[a][1] - quad[b][1]); };
218
+ var nativeLong = Math.max(d(0, 1), d(3, 2), d(0, 3), d(1, 2)) / nativeScale;
219
+ return { blur: blurScore(patch), sat: g.sat, blob: g.blob, nativeLong: nativeLong, brightness: brightnessScore(patch) };
220
+ }
221
+ var State = Object.freeze({ NO_CARD: "no_card", TOO_FAR: "too_far", TOO_DARK: "too_dark", CARD_DETECTED: "card_detected", HOLD_STILL: "hold_still", TOO_BLURRY: "too_blurry", BRIGHT_SPOT: "bright_spot", READY: "ready" });
222
+ var MESSAGES = {
223
+ no_card: "Position your ID card in frame",
224
+ too_far: "Move the card closer",
225
+ too_dark: "Not enough light — increase the brightness",
226
+ card_detected: "Card detected — keep it in view",
227
+ hold_still: "Hold still…",
228
+ too_blurry: "Image is blurry — adjust the focus and hold steady",
229
+ bright_spot: "Reflection detected — tilt the card to avoid the bright spot",
230
+ ready: "Perfect — capturing",
231
+ };
232
+ /**
233
+ * Temporal tracker. Feed it one decode() result per inference; it returns a stable guidance state.
234
+ * - hysteresis: card must score >= enterThr on `enterFrames` consecutive frames to appear, and is only
235
+ * dropped after `exitFrames` consecutive frames below exitThr (isolated bad frames do not flicker);
236
+ * - corners are EMA-smoothed; a rejected quad keeps the last good one during the grace period;
237
+ * - optional quality (blur/glare from measureQuality) is median-filtered over `qualityWindow` inferences: GLARE when a bright
238
+ * highlight covers the card, BLURRY when the card is still but soft, TOO_FAR when it is under `minNativeLong` camera pixels;
239
+ * READY additionally requires sharp + no glare, so the auto-capture never fires on a blurry or reflective frame;
240
+ * - HOLD_STILL when mean corner motion < stillMotion (fraction of card diagonal) for `stillFrames`;
241
+ * READY once it has been still for `holdMs` -- `onReady` fires once per card presence.
242
+ */
243
+ var GuideTracker = /** @class */ (function () {
244
+ function GuideTracker(opts) {
245
+ if (opts === void 0) { opts = {}; }
246
+ this.fb = [];
247
+ this.present = false;
248
+ this.hi = 0;
249
+ this.lo = 0;
250
+ this.corners = null;
251
+ this.stillCount = 0;
252
+ this.bad = 0;
253
+ this.stillSince = null;
254
+ this.fired = false;
255
+ this.qual = [];
256
+ this.state = State.NO_CARD;
257
+ this.o = Object.assign({ enterThr: 0.5, exitThr: 0.3, enterFrames: 2, exitFrames: 4, ema: 0.5, stillMotion: 0.015, stillFrames: 3, holdMs: 600, stillExitMotion: 0.04, stillGraceFrames: 2, minAreaFrac: 0.06, minBlur: 450, maxGlareBlob: 0.012, minNativeLong: 300, minCardBrightness: 55, minFrameBrightness: 45, qualityWindow: 3 }, opts);
258
+ this.fb = [];
259
+ this.reset();
260
+ }
261
+ GuideTracker.prototype.reset = function () { this.present = false; this.hi = 0; this.lo = 0; this.corners = null; this.stillCount = 0; this.stillSince = null; this.bad = 0; this.fired = false; this.qual = []; this.state = State.NO_CARD; };
262
+ GuideTracker.prototype.update = function (dec, srcW, srcH, tMs, quality, frameBrightness) {
263
+ if (quality === void 0) { quality = null; }
264
+ if (frameBrightness === void 0) { frameBrightness = null; }
265
+ if (frameBrightness !== null) {
266
+ this.fb.push(frameBrightness);
267
+ if (this.fb.length > this.o.qualityWindow)
268
+ this.fb.shift();
269
+ }
270
+ if (quality) {
271
+ this.qual.push(quality);
272
+ if (this.qual.length > this.o.qualityWindow)
273
+ this.qual.shift();
274
+ }
275
+ var o = this.o, px = dec.corners.map(function (_a) {
276
+ var x = _a[0], y = _a[1];
277
+ return [x * srcW, y * srcH];
278
+ });
279
+ var valid = quadRejectionReason(px, srcW, srcH) === null;
280
+ if (dec.presence >= o.enterThr && valid) {
281
+ this.hi++;
282
+ }
283
+ else
284
+ this.hi = 0;
285
+ if (dec.presence < o.exitThr)
286
+ this.lo++;
287
+ else
288
+ this.lo = 0;
289
+ if (!this.present && this.hi >= o.enterFrames)
290
+ this.present = true;
291
+ if (this.present && this.lo >= o.exitFrames) {
292
+ this.reset();
293
+ return this._out(dec, srcW, srcH);
294
+ }
295
+ if (!this.present)
296
+ return this._out(dec, srcW, srcH);
297
+ var motion = Infinity;
298
+ if (valid && dec.presence >= o.exitThr) {
299
+ var prev_1 = this.corners;
300
+ var next = prev_1 ? prev_1.map(function (p, i) { return [p[0] + o.ema * (dec.corners[i][0] - p[0]), p[1] + o.ema * (dec.corners[i][1] - p[1])]; }) : dec.corners.map(function (p) { return [p[0], p[1]]; });
301
+ if (prev_1) {
302
+ var diag = Math.hypot((next[0][0] - next[2][0]) * srcW, (next[0][1] - next[2][1]) * srcH) || 1;
303
+ motion = next.reduce(function (s, p, i) { return s + Math.hypot((p[0] - prev_1[i][0]) * srcW, (p[1] - prev_1[i][1]) * srcH); }, 0) / 4 / diag;
304
+ }
305
+ this.corners = next;
306
+ }
307
+ // Hold-still hysteresis: entering "still" needs motion < stillMotion; once the hold threshold (stillFrames) is reached we are LOCKED and
308
+ // only give up on a clearly different image (motion >= stillExitMotion) or after more than stillGraceFrames consecutive bad frames
309
+ // (a dropped detection, an invalid quad, a hand tremor). Minor changes never invalidate a capture that is about to fire.
310
+ var locked = this.stillCount >= o.stillFrames;
311
+ if (motion < (locked ? o.stillExitMotion : o.stillMotion)) {
312
+ this.stillCount++;
313
+ this.bad = 0;
314
+ if (this.stillSince === null)
315
+ this.stillSince = tMs;
316
+ }
317
+ else if (locked && this.bad < o.stillGraceFrames) {
318
+ this.bad++;
319
+ }
320
+ else {
321
+ this.stillCount = 0;
322
+ this.stillSince = null;
323
+ this.bad = 0;
324
+ }
325
+ return this._out(dec, srcW, srcH, tMs);
326
+ };
327
+ GuideTracker.prototype._out = function (dec, srcW, srcH, tMs) {
328
+ var _this = this;
329
+ if (tMs === void 0) { tMs = 0; }
330
+ var state = State.NO_CARD, readyNow = false;
331
+ if (this.present && this.corners) {
332
+ var c = this.corners;
333
+ var a = 0;
334
+ for (var i = 0; i < 4; i++) {
335
+ var j = (i + 1) % 4;
336
+ a += c[i][0] * c[j][1] - c[j][0] * c[i][1];
337
+ }
338
+ var areaFrac = Math.abs(a) / 2; // corners are normalised, so this is already a fraction of the frame
339
+ var med = function (k) { var v = _this.qual.map(function (x) { return x[k]; }).filter(function (x) { return typeof x === "number"; }).sort(function (a, b) { return a - b; }); return v.length ? v[Math.floor(v.length / 2)] : null; };
340
+ var blur_1 = med("blur"), blob = med("blob"), nat = med("nativeLong"), bri = med("brightness"), still = this.stillCount >= this.o.stillFrames;
341
+ if (areaFrac < this.o.minAreaFrac || (nat !== null && nat < this.o.minNativeLong))
342
+ state = State.TOO_FAR;
343
+ else if (bri !== null && bri < this.o.minCardBrightness)
344
+ state = State.TOO_DARK;
345
+ else if (blob !== null && blob >= this.o.maxGlareBlob)
346
+ state = State.BRIGHT_SPOT;
347
+ else if (still && blur_1 !== null && blur_1 < this.o.minBlur)
348
+ state = State.TOO_BLURRY;
349
+ else if (still && this.stillSince !== null && tMs - this.stillSince >= this.o.holdMs) {
350
+ state = State.READY;
351
+ if (!this.fired) {
352
+ this.fired = true;
353
+ readyNow = true;
354
+ }
355
+ }
356
+ else if (still)
357
+ state = State.HOLD_STILL;
358
+ else
359
+ state = State.CARD_DETECTED;
360
+ }
361
+ if (state === State.NO_CARD && this.fb.length) {
362
+ var f = this.fb.slice().sort(function (x, y) { return x - y; })[Math.floor(this.fb.length / 2)];
363
+ if (f < this.o.minFrameBrightness)
364
+ state = State.TOO_DARK;
365
+ }
366
+ this.state = state;
367
+ return { state: state, message: MESSAGES[state], corners: this.present ? this.corners : null, presence: dec.presence, readyNow: readyNow, quality: this.qual.length ? this.qual[this.qual.length - 1] : null, frameBrightness: this.fb.length ? this.fb[this.fb.length - 1] : null };
368
+ };
369
+ return GuideTracker;
370
+ }());
371
+
372
+ export { GuideTracker, HM, MESSAGES, SAT_THR, SIZE, State, WARP_W, blurScore, brightnessScore, decode, frameBrightness, glareScore, letterbox, measureQuality, quadRejectionReason, warpCard };
@@ -0,0 +1,115 @@
1
+ import { __awaiter, __generator } from '../../node_modules/tslib/tslib.es6.js';
2
+ import { SIZE, decode, frameBrightness, measureQuality, letterbox } from './guideCore.js';
3
+ import { loadModelBytes, DEFAULT_MODEL_URL } from './modelLoader.js';
4
+
5
+ var IMAGENET_MEAN = [0.485, 0.456, 0.406];
6
+ var IMAGENET_STD = [0.229, 0.224, 0.225];
7
+ var PAD = 114; // letterbox gray, same as training
8
+ var QUALITY_MAX_SIDE = 640; // card long side (px) of the crop the quality metrics are measured on
9
+ var QUALITY_MIN_PRESENCE = 0.3;
10
+ function createGuideRuntime() {
11
+ return __awaiter(this, arguments, void 0, function (options) {
12
+ function preprocess(video, w, h) {
13
+ var lb = letterbox(w, h);
14
+ preCtx.fillStyle = "rgb(".concat(PAD, ",").concat(PAD, ",").concat(PAD, ")");
15
+ preCtx.fillRect(0, 0, SIZE, SIZE);
16
+ preCtx.drawImage(video, 0, 0, w, h, lb.ox, lb.oy, lb.nw, lb.nh);
17
+ var data = preCtx.getImageData(0, 0, SIZE, SIZE).data;
18
+ var n = SIZE * SIZE;
19
+ var chw = new Float32Array(3 * n);
20
+ for (var i = 0; i < n; i++) {
21
+ for (var c = 0; c < 3; c++)
22
+ chw[c * n + i] = (data[i * 4 + c] / 255 - IMAGENET_MEAN[c]) / IMAGENET_STD[c];
23
+ }
24
+ return { tensor: new ort.Tensor("float32", chw, [1, 3, SIZE, SIZE]), brightness: frameBrightness(data, SIZE, { x: lb.ox, y: lb.oy, w: lb.nw, h: lb.nh }) };
25
+ }
26
+ /** Crop the card's bounding box out of the video at <= QUALITY_MAX_SIDE px and measure blur/glare on it. */
27
+ function sampleQuality(video, w, h, corners) {
28
+ var px = corners.map(function (_a) {
29
+ var x = _a[0], y = _a[1];
30
+ return [x * w, y * h];
31
+ });
32
+ var xs = px.map(function (p) { return p[0]; });
33
+ var ys = px.map(function (p) { return p[1]; });
34
+ var pad = 0.04 * Math.max(Math.max.apply(Math, xs) - Math.min.apply(Math, xs), Math.max.apply(Math, ys) - Math.min.apply(Math, ys));
35
+ var bx = Math.max(0, Math.floor(Math.min.apply(Math, xs) - pad));
36
+ var by = Math.max(0, Math.floor(Math.min.apply(Math, ys) - pad));
37
+ var cw = Math.min(w, Math.ceil(Math.max.apply(Math, xs) + pad)) - bx;
38
+ var ch = Math.min(h, Math.ceil(Math.max.apply(Math, ys) + pad)) - by;
39
+ if (cw < 16 || ch < 16)
40
+ return null;
41
+ var s = Math.min(1, QUALITY_MAX_SIDE / Math.max(cw, ch));
42
+ crop.width = Math.max(1, Math.round(cw * s));
43
+ crop.height = Math.max(1, Math.round(ch * s));
44
+ cropCtx.drawImage(video, bx, by, cw, ch, 0, 0, crop.width, crop.height);
45
+ var frame = cropCtx.getImageData(0, 0, crop.width, crop.height);
46
+ var quad = px.map(function (_a) {
47
+ var x = _a[0], y = _a[1];
48
+ return [(x - bx) * s, (y - by) * s];
49
+ });
50
+ return measureQuality(frame, quad, s);
51
+ }
52
+ var ort, modelBytes, session, preCanvas, preCtx, crop, cropCtx;
53
+ var _a, _b;
54
+ if (options === void 0) { options = {}; }
55
+ return __generator(this, function (_c) {
56
+ switch (_c.label) {
57
+ case 0: return [4 /*yield*/, import('onnxruntime-web')];
58
+ case 1:
59
+ ort = _c.sent();
60
+ // The .wasm must match the installed JS glue exactly: pin the CDN fallback to the runtime's own version.
61
+ ort.env.wasm.wasmPaths =
62
+ (_a = options.wasmPaths) !== null && _a !== void 0 ? _a : "https://cdn.jsdelivr.net/npm/onnxruntime-web@".concat(ort.env.versions.web, "/dist/");
63
+ return [4 /*yield*/, loadModelBytes((_b = options.modelUrl) !== null && _b !== void 0 ? _b : DEFAULT_MODEL_URL)];
64
+ case 2:
65
+ modelBytes = _c.sent();
66
+ return [4 /*yield*/, ort.InferenceSession.create(modelBytes, {
67
+ executionProviders: ["wasm"],
68
+ graphOptimizationLevel: "all",
69
+ })];
70
+ case 3:
71
+ session = _c.sent();
72
+ preCanvas = document.createElement("canvas");
73
+ preCanvas.width = SIZE;
74
+ preCanvas.height = SIZE;
75
+ preCtx = preCanvas.getContext("2d", { willReadFrequently: true });
76
+ crop = document.createElement("canvas");
77
+ cropCtx = crop.getContext("2d", { willReadFrequently: true });
78
+ if (!preCtx || !cropCtx)
79
+ throw new Error("2D canvas context unavailable");
80
+ return [2 /*return*/, {
81
+ run: function (video) {
82
+ return __awaiter(this, void 0, void 0, function () {
83
+ var w, h, pre, out, decoded, quality;
84
+ return __generator(this, function (_a) {
85
+ switch (_a.label) {
86
+ case 0:
87
+ w = video.videoWidth;
88
+ h = video.videoHeight;
89
+ pre = preprocess(video, w, h);
90
+ return [4 /*yield*/, session.run({ input: pre.tensor })];
91
+ case 1:
92
+ out = _a.sent();
93
+ decoded = decode({
94
+ cls: out.cls.data,
95
+ heat: out.heat.data,
96
+ off: out.off.data,
97
+ vis: out.vis.data,
98
+ glob: out.glob.data,
99
+ }, w, h);
100
+ quality = decoded.presence >= QUALITY_MIN_PRESENCE ? sampleQuality(video, w, h, decoded.corners) : null;
101
+ return [2 /*return*/, { decoded: decoded, quality: quality, frameBrightness: pre.brightness }];
102
+ }
103
+ });
104
+ });
105
+ },
106
+ dispose: function () {
107
+ void session.release();
108
+ },
109
+ }];
110
+ }
111
+ });
112
+ });
113
+ }
114
+
115
+ export { DEFAULT_MODEL_URL, createGuideRuntime };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Model download for the card guide, kept apart from the ONNX runtime so a screen can preload the weights
3
+ * (13.5 MB, the main wait on mobile) without pulling onnxruntime-web or the guide logic.
4
+ */
5
+ /**
6
+ * card-guide-v2b-20261006-weights.onnx (SHA-256 5eae0785…f48b), public Datakeen bucket, CORS `*`.
7
+ * Temporary location for testing: APP3-2118 moves it to the Datakeen CDN with a versioned name and a long cache.
8
+ */
9
+ var DEFAULT_MODEL_URL = "https://datakeen-public.s3.eu-west-3.amazonaws.com/FmyFye6vkg8rrzrtQkW3QADx6eyner1q2WAEVUSB/xyG08fbEmVzYFwezy8zzJvHRbfgWpA8spA0TNeJQ.onnx";
10
+ var cache = new Map();
11
+ /** Downloads the model once per URL and shares the bytes between the preload and the runtime. */
12
+ function loadModelBytes(url) {
13
+ if (url === void 0) { url = DEFAULT_MODEL_URL; }
14
+ var cached = cache.get(url);
15
+ if (cached)
16
+ return cached;
17
+ var pending = fetch(url, { mode: "cors", credentials: "omit" })
18
+ .then(function (res) {
19
+ if (!res.ok)
20
+ throw new Error("Card guide model download failed (".concat(res.status, ")"));
21
+ return res.arrayBuffer();
22
+ })
23
+ .then(function (buf) { return new Uint8Array(buf); });
24
+ // a failed download must not poison the cache: the next attempt retries
25
+ pending.catch(function () { return cache.delete(url); });
26
+ cache.set(url, pending);
27
+ return pending;
28
+ }
29
+ /** Starts the download ahead of the capture screen. Never throws: the capture screen retries or falls back. */
30
+ function preloadCardGuideModel(url) {
31
+ if (url === void 0) { url = DEFAULT_MODEL_URL; }
32
+ if (typeof fetch !== "function")
33
+ return;
34
+ try {
35
+ loadModelBytes(url).catch(function () { });
36
+ }
37
+ catch (_a) {
38
+ // a non-standard fetch can throw synchronously: preloading is best effort
39
+ }
40
+ }
41
+
42
+ export { DEFAULT_MODEL_URL, loadModelBytes, preloadCardGuideModel };