datakeen-session-react 1.1.202-dev.17 → 1.1.202-dev.19

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 (60) 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/id-check/Photo.js +230 -122
  12. package/dist/cjs/components/id-check/card-capture/CardCapture.js +270 -0
  13. package/dist/cjs/components/id-check/card-capture/DynamicCardMask.js +85 -0
  14. package/dist/cjs/components/id-check/card-capture/geometry.js +119 -0
  15. package/dist/cjs/components/id-check/card-capture/guideTone.js +15 -0
  16. package/dist/cjs/components/jdi/JDIDocumentSelection.js +9 -0
  17. package/dist/cjs/components/session/DocumentCheck.js +19 -2
  18. package/dist/cjs/components/start-flow/Start.js +4 -0
  19. package/dist/cjs/context/CardCaptureGuideContext.js +16 -0
  20. package/dist/cjs/i18n/en.json.js +29 -0
  21. package/dist/cjs/i18n/es.json.js +29 -0
  22. package/dist/cjs/i18n/fr.json.js +29 -0
  23. package/dist/cjs/index.css.js +1 -1
  24. package/dist/cjs/index.js +13 -0
  25. package/dist/cjs/services/sessionService.js +43 -0
  26. package/dist/esm/components/DatakeenSession.js +17 -16
  27. package/dist/esm/components/card-capture-guide/CardCaptureGuide.js +135 -0
  28. package/dist/esm/components/card-capture-guide/captureTelemetry.js +78 -0
  29. package/dist/esm/components/card-capture-guide/guidance.js +44 -0
  30. package/dist/esm/components/card-capture-guide/guideCore.js +372 -0
  31. package/dist/esm/components/card-capture-guide/guideRuntime.js +115 -0
  32. package/dist/esm/components/card-capture-guide/modelLoader.js +42 -0
  33. package/dist/esm/components/card-capture-guide/useCaptureGuideThresholds.js +31 -0
  34. package/dist/esm/components/card-capture-guide/useCardCaptureGuide.js +115 -0
  35. package/dist/esm/components/card-capture-guide/useMinDisplay.js +28 -0
  36. package/dist/esm/components/id-check/Photo.js +232 -124
  37. package/dist/esm/components/id-check/card-capture/CardCapture.js +266 -0
  38. package/dist/esm/components/id-check/card-capture/DynamicCardMask.js +81 -0
  39. package/dist/esm/components/id-check/card-capture/geometry.js +110 -0
  40. package/dist/esm/components/id-check/card-capture/guideTone.js +13 -0
  41. package/dist/esm/components/jdi/JDIDocumentSelection.js +9 -0
  42. package/dist/esm/components/session/DocumentCheck.js +19 -2
  43. package/dist/esm/components/start-flow/Start.js +4 -0
  44. package/dist/esm/context/CardCaptureGuideContext.js +13 -0
  45. package/dist/esm/i18n/en.json.js +28 -1
  46. package/dist/esm/i18n/es.json.js +28 -1
  47. package/dist/esm/i18n/fr.json.js +28 -1
  48. package/dist/esm/index.css.js +1 -1
  49. package/dist/esm/index.js +5 -0
  50. package/dist/esm/services/sessionService.js +42 -1
  51. package/dist/types/components/card-capture-guide/CardCaptureGuide.d.ts +46 -0
  52. package/dist/types/components/card-capture-guide/guidance.d.ts +45 -0
  53. package/dist/types/components/card-capture-guide/guideCore.d.ts +96 -0
  54. package/dist/types/components/card-capture-guide/guideRuntime.d.ts +13 -0
  55. package/dist/types/components/card-capture-guide/modelLoader.d.ts +13 -0
  56. package/dist/types/components/card-capture-guide/useCardCaptureGuide.d.ts +38 -0
  57. package/dist/types/index.d.ts +6 -0
  58. package/dist/types/types/camera.d.ts +3 -0
  59. package/dist/types/types/session.d.ts +15 -1
  60. package/package.json +2 -1
@@ -0,0 +1,135 @@
1
+ import { __awaiter, __generator } from '../../node_modules/tslib/tslib.es6.js';
2
+ import { jsxs, jsx } from 'react/jsx-runtime';
3
+ import { useRef, useState, useCallback, useEffect } from 'react';
4
+ import { cameraService } from '../../services/cameraService.js';
5
+ import { useI18n } from '../../hooks/useI18n.js';
6
+ import { State } from './guideCore.js';
7
+ import { useCardCaptureGuide } from './useCardCaptureGuide.js';
8
+
9
+ var _a;
10
+ var COLORS = (_a = {},
11
+ _a[State.CARD_DETECTED] = "#FFD400",
12
+ _a[State.TOO_FAR] = "#FFD400",
13
+ _a[State.HOLD_STILL] = "#7CFC00",
14
+ _a[State.READY] = "#7CFC00",
15
+ _a[State.TOO_BLURRY] = "#FF8A00",
16
+ _a[State.TOO_DARK] = "#FF8A00",
17
+ _a[State.BRIGHT_SPOT] = "#FF4D4D",
18
+ _a);
19
+ /**
20
+ * Live ID-card capture guide: camera preview + tracked card outline + guidance messages (move closer, hold still, blurry,
21
+ * reflection) and automatic capture once the card is steady, sharp and free of bright spots. Runs fully client-side.
22
+ */
23
+ var CardCaptureGuide = function (_a) {
24
+ var _b, _c;
25
+ var onCapture = _a.onCapture, _d = _a.autoCapture, autoCapture = _d === void 0 ? true : _d, _e = _a.facingMode, facingMode = _e === void 0 ? "environment" : _e, modelUrl = _a.modelUrl, wasmPaths = _a.wasmPaths, tracker = _a.tracker, onGuidance = _a.onGuidance, onFrame = _a.onFrame, messages = _a.messages, _f = _a.showMessage, showMessage = _f === void 0 ? true : _f, onError = _a.onError, className = _a.className;
26
+ var t = useI18n().t;
27
+ var videoRef = useRef(null);
28
+ var canvasRef = useRef(null);
29
+ var _g = useState(false), cameraReady = _g[0], setCameraReady = _g[1];
30
+ var _h = useState(null), cameraError = _h[0], setCameraError = _h[1];
31
+ var _j = useState(false), captured = _j[0], setCaptured = _j[1];
32
+ var lastGuide = useRef(null);
33
+ var capturing = useRef(false);
34
+ var capture = useCallback(function (automatic) { return __awaiter(void 0, void 0, void 0, function () {
35
+ var result, e_1, message_1;
36
+ var _a, _b, _c, _d;
37
+ return __generator(this, function (_e) {
38
+ switch (_e.label) {
39
+ case 0:
40
+ if (capturing.current)
41
+ return [2 /*return*/];
42
+ capturing.current = true;
43
+ _e.label = 1;
44
+ case 1:
45
+ _e.trys.push([1, 3, , 4]);
46
+ return [4 /*yield*/, cameraService.captureDocument(videoRef.current, null, { facingMode: facingMode, format: "jpeg", jpegQuality: 0.92 })];
47
+ case 2:
48
+ result = _e.sent();
49
+ setCaptured(true);
50
+ onCapture(result.dataUrl, { corners: (_b = (_a = lastGuide.current) === null || _a === void 0 ? void 0 : _a.corners) !== null && _b !== void 0 ? _b : null, quality: (_d = (_c = lastGuide.current) === null || _c === void 0 ? void 0 : _c.quality) !== null && _d !== void 0 ? _d : null, automatic: automatic });
51
+ return [3 /*break*/, 4];
52
+ case 3:
53
+ e_1 = _e.sent();
54
+ capturing.current = false;
55
+ message_1 = e_1 instanceof Error ? e_1.message : String(e_1);
56
+ setCameraError(message_1);
57
+ onError === null || onError === void 0 ? void 0 : onError(message_1);
58
+ return [3 /*break*/, 4];
59
+ case 4: return [2 /*return*/];
60
+ }
61
+ });
62
+ }); }, [facingMode, onCapture, onError]);
63
+ var _k = useCardCaptureGuide(videoRef, {
64
+ modelUrl: modelUrl,
65
+ wasmPaths: wasmPaths,
66
+ tracker: tracker,
67
+ resolveMessage: function (code) { var _a; return (_a = messages === null || messages === void 0 ? void 0 : messages[code]) !== null && _a !== void 0 ? _a : t("card_capture_guide.".concat(code)); },
68
+ onGuidance: onGuidance,
69
+ onFrame: onFrame,
70
+ enabled: cameraReady && !captured,
71
+ onReady: function () {
72
+ if (autoCapture)
73
+ void capture(true);
74
+ },
75
+ }), modelReady = _k.modelReady, guide = _k.guide, event = _k.event, error = _k.error;
76
+ lastGuide.current = guide;
77
+ useEffect(function () {
78
+ var cancelled = false;
79
+ cameraService
80
+ .startCamera(videoRef.current, { facingMode: facingMode, idealResolution: { width: 1920, height: 1080 }, preferImageCapture: true })
81
+ .then(function (r) {
82
+ var _a, _b;
83
+ if (cancelled)
84
+ return;
85
+ if (r.success)
86
+ setCameraReady(true);
87
+ else {
88
+ setCameraError((_a = r.error) !== null && _a !== void 0 ? _a : "camera");
89
+ onError === null || onError === void 0 ? void 0 : onError((_b = r.error) !== null && _b !== void 0 ? _b : "camera");
90
+ }
91
+ });
92
+ return function () {
93
+ cancelled = true;
94
+ cameraService.stopCamera();
95
+ };
96
+ }, [facingMode]);
97
+ useEffect(function () {
98
+ if (error)
99
+ onError === null || onError === void 0 ? void 0 : onError(error);
100
+ }, [error]);
101
+ useEffect(function () {
102
+ var _a;
103
+ var canvas = canvasRef.current;
104
+ var video = videoRef.current;
105
+ if (!canvas || !video)
106
+ return;
107
+ canvas.width = video.clientWidth;
108
+ canvas.height = video.clientHeight;
109
+ var ctx = canvas.getContext("2d");
110
+ if (!ctx)
111
+ return;
112
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
113
+ if (!(guide === null || guide === void 0 ? void 0 : guide.corners) || captured)
114
+ return;
115
+ ctx.strokeStyle = (_a = COLORS[guide.state]) !== null && _a !== void 0 ? _a : "#FFD400";
116
+ ctx.lineWidth = 4;
117
+ ctx.beginPath();
118
+ guide.corners.forEach(function (_a, i) {
119
+ var x = _a[0], y = _a[1];
120
+ return (i === 0 ? ctx.moveTo(x * canvas.width, y * canvas.height) : ctx.lineTo(x * canvas.width, y * canvas.height));
121
+ });
122
+ ctx.closePath();
123
+ ctx.stroke();
124
+ }, [guide, captured]);
125
+ var message = cameraError
126
+ ? t("card_capture_guide.camera_error")
127
+ : error
128
+ ? t("card_capture_guide.model_error")
129
+ : !modelReady
130
+ ? t("card_capture_guide.loading")
131
+ : ((_c = (_b = event === null || event === void 0 ? void 0 : event.message) !== null && _b !== void 0 ? _b : messages === null || messages === void 0 ? void 0 : messages.no_card) !== null && _c !== void 0 ? _c : t("card_capture_guide.".concat(State.NO_CARD)));
132
+ return (jsxs("div", { className: className, style: { position: "relative", width: "100%" }, "data-testid": "card-capture-guide", children: [jsx("video", { ref: videoRef, style: { width: "100%", display: "block" }, muted: true, playsInline: true, autoPlay: true }), jsx("canvas", { ref: canvasRef, style: { position: "absolute", top: 0, left: 0, width: "100%", height: "100%", pointerEvents: "none" } }), showMessage && (jsx("p", { role: "status", "aria-live": "polite", "data-testid": "card-capture-guide-message", style: { textAlign: "center", margin: "8px 0" }, children: message })), !autoCapture && (jsx("button", { type: "button", onClick: function () { return void capture(false); }, disabled: !cameraReady || captured, children: t("photo.capture", { defaultValue: "Capture" }) }))] }));
133
+ };
134
+
135
+ export { CardCaptureGuide as default };
@@ -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 };