millirec 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +156 -2
- package/dist/char-cnn/base-p25.bin +0 -0
- package/dist/char-cnn/base-p25.head.bin +0 -0
- package/dist/char-cnn/base.head.bin +0 -0
- package/dist/char-cnn/base.q4.bin +0 -0
- package/dist/char-cnn/cnn-web.js +8 -0
- package/dist/char-cnn/cnn-web.wasm +0 -0
- package/dist/char-cnn/core.d.ts +35 -0
- package/dist/char-cnn/core.js +536 -0
- package/dist/char-cnn/index.d.ts +9 -0
- package/dist/char-cnn/index.js +1009 -0
- package/dist/char-cnn/millirec-char-cnn-core.min.js +1 -0
- package/dist/char-cnn/millirec-char-cnn.min.js +1 -0
- package/dist/char-cnn/options/accurate.js +17 -0
- package/dist/char-cnn/options/accurate.json +15 -0
- package/dist/char-cnn/options/fast.js +17 -0
- package/dist/char-cnn/options/fast.json +15 -0
- package/dist/char-cnn/options/small.js +11 -0
- package/dist/char-cnn/options/small.json +9 -0
- package/dist/char-cnn/tiny.bin +0 -0
- package/dist/char-cnn/tiny.head.bin +0 -0
- package/dist/char-lite/index.d.ts +77 -0
- package/dist/char-lite/index.js +894 -0
- package/dist/char-lite/millirec-char-lite.min.js +1 -0
- package/dist/char-lite/millirec.wasm +0 -0
- package/dist/char-lite/sets/all.js +2 -0
- package/dist/char-lite/sets/all.json +1 -0
- package/dist/char-lite/sets/capitals.js +2 -0
- package/dist/char-lite/sets/capitals.json +1 -0
- package/dist/char-lite/sets/digits.js +2 -0
- package/dist/char-lite/sets/digits.json +1 -0
- package/dist/char-lite/sets/lowercase.js +2 -0
- package/dist/char-lite/sets/lowercase.json +1 -0
- package/dist/char-lite/sets/punctuation.js +2 -0
- package/dist/char-lite/sets/punctuation.json +1 -0
- package/dist/char-lite/sets.json +163 -0
- package/dist/char-lite/worker-stroke.js +11 -0
- package/dist/overlap/millirec-overlap.min.js +45 -0
- package/dist/overlap/millirec.wasm +0 -0
- package/dist/overlap/training.all.json +1 -0
- package/dist/overlap/training.capitals.json +1 -0
- package/dist/overlap/training.digits.json +1 -0
- package/dist/overlap/training.lowercase.json +1 -0
- package/dist/overlap/training.punctuation.json +1 -0
- package/dist/overlap/words.json +1 -0
- package/package.json +53 -4
|
@@ -0,0 +1,894 @@
|
|
|
1
|
+
// ../../core/pipeline/constants.js
|
|
2
|
+
var POINTS_PER_SHAPE = 50;
|
|
3
|
+
var SECOND_AVERAGE = 1e3;
|
|
4
|
+
|
|
5
|
+
// ../../core/pipeline/calibrate.js
|
|
6
|
+
var CALIBRATION = {
|
|
7
|
+
image: { margin: 0.6884, mag: 0.6846, bias: -1.0768 },
|
|
8
|
+
imageGeom: { margin: 0.6925, mag: 1.0731, bias: -2.4927 }
|
|
9
|
+
};
|
|
10
|
+
function calibratedProb(a, b, { margin, mag, bias }) {
|
|
11
|
+
if (a < 1e-9) return 0.99;
|
|
12
|
+
return 1 / (1 + Math.exp(-(margin * Math.log(Math.max(b, 1e-9) / a) - mag * Math.log(a) - bias)));
|
|
13
|
+
}
|
|
14
|
+
function parseResult(result, charList, mode, secondAverage = SECOND_AVERAGE) {
|
|
15
|
+
const chars = [];
|
|
16
|
+
for (let i = 0; i < 3; i++) chars.push(charList[result[2 * i]]);
|
|
17
|
+
const cal = CALIBRATION[mode];
|
|
18
|
+
if (cal) {
|
|
19
|
+
const costs = [result[1], result[3], result[5]];
|
|
20
|
+
const probs2 = costs.map((c, i) => {
|
|
21
|
+
let rival = Infinity;
|
|
22
|
+
for (let j = 0; j < 3; j++) if (j !== i) rival = Math.min(rival, costs[j]);
|
|
23
|
+
return calibratedProb(c, rival, cal);
|
|
24
|
+
});
|
|
25
|
+
return { chars, probs: probs2 };
|
|
26
|
+
}
|
|
27
|
+
const denom = Math.max(result[1], secondAverage / 1e3);
|
|
28
|
+
let totalProb = Math.exp(-1 * secondAverage / denom);
|
|
29
|
+
for (let i = 0; i < 3; i++) totalProb += Math.exp(-1 * result[2 * i + 1] / denom);
|
|
30
|
+
const probs = [];
|
|
31
|
+
for (let i = 0; i < 3; i++) {
|
|
32
|
+
probs.push(Math.exp(-1 * result[2 * i + 1] / denom) / totalProb);
|
|
33
|
+
}
|
|
34
|
+
return { chars, probs };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ../../core/format/delta.js
|
|
38
|
+
function decodeSample(sample) {
|
|
39
|
+
const points = [];
|
|
40
|
+
let x = 0;
|
|
41
|
+
let y = 0;
|
|
42
|
+
for (let i = 0; i < sample.x.length; i++) {
|
|
43
|
+
x += sample.x[i];
|
|
44
|
+
y += sample.y[i];
|
|
45
|
+
points.push({ x, y });
|
|
46
|
+
}
|
|
47
|
+
return points;
|
|
48
|
+
}
|
|
49
|
+
function encodeSample(points) {
|
|
50
|
+
const xs = [];
|
|
51
|
+
const ys = [];
|
|
52
|
+
let last = [0, 0];
|
|
53
|
+
for (let i = 0; i < points.length; i++) {
|
|
54
|
+
const x = Math.round(points[i].x);
|
|
55
|
+
const y = Math.round(points[i].y);
|
|
56
|
+
xs.push(i === 0 ? x : x - last[0]);
|
|
57
|
+
ys.push(i === 0 ? y : y - last[1]);
|
|
58
|
+
last = [x, y];
|
|
59
|
+
}
|
|
60
|
+
return { x: xs, y: ys };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ../../core/pipeline/stroke.js
|
|
64
|
+
function orientedPointsFromPolyline(polyline) {
|
|
65
|
+
const n = polyline.length;
|
|
66
|
+
const centroid = [0, 0];
|
|
67
|
+
let lastPoint = [0, 0];
|
|
68
|
+
const points = [];
|
|
69
|
+
for (let i = 0; i < n; i++) {
|
|
70
|
+
const point = polyline[i];
|
|
71
|
+
centroid[0] += point.x;
|
|
72
|
+
centroid[1] += point.y;
|
|
73
|
+
const out = { x: point.x, y: point.y, a: 1.570795 };
|
|
74
|
+
if (i > 0 && point.x !== lastPoint[0]) {
|
|
75
|
+
out.a = Math.atan2(point.y - lastPoint[1], point.x - lastPoint[0]);
|
|
76
|
+
}
|
|
77
|
+
out.s = Math.sin(out.a);
|
|
78
|
+
out.c = Math.cos(out.a);
|
|
79
|
+
if (i === 1) {
|
|
80
|
+
points[0].s = out.s;
|
|
81
|
+
points[0].c = out.c;
|
|
82
|
+
}
|
|
83
|
+
lastPoint = [point.x, point.y];
|
|
84
|
+
points.push(out);
|
|
85
|
+
}
|
|
86
|
+
centroid[0] /= n;
|
|
87
|
+
centroid[1] /= n;
|
|
88
|
+
const tc = [0, 0], bc = [0, 0], lc = [0, 0], rc = [0, 0];
|
|
89
|
+
for (const p of points) {
|
|
90
|
+
if (p.x < centroid[0]) {
|
|
91
|
+
lc[0] += p.x - centroid[0];
|
|
92
|
+
lc[1]++;
|
|
93
|
+
} else {
|
|
94
|
+
rc[0] += p.x - centroid[0];
|
|
95
|
+
rc[1]++;
|
|
96
|
+
}
|
|
97
|
+
if (p.y < centroid[1]) {
|
|
98
|
+
tc[0] += p.y - centroid[1];
|
|
99
|
+
tc[1]++;
|
|
100
|
+
} else {
|
|
101
|
+
bc[0] += p.y - centroid[1];
|
|
102
|
+
bc[1]++;
|
|
103
|
+
}
|
|
104
|
+
p.x -= centroid[0];
|
|
105
|
+
p.y -= centroid[1];
|
|
106
|
+
}
|
|
107
|
+
if (tc[1] > 0) tc[0] /= tc[1];
|
|
108
|
+
if (bc[1] > 0) bc[0] /= bc[1];
|
|
109
|
+
if (lc[1] > 0) lc[0] /= lc[1];
|
|
110
|
+
if (rc[1] > 0) rc[0] /= rc[1];
|
|
111
|
+
const scale = bc[0] - tc[0] < rc[0] - lc[0] ? 100 / (rc[0] - lc[0]) : tc[0] < bc[0] ? 100 / (bc[0] - tc[0]) : 1;
|
|
112
|
+
return { points, scale };
|
|
113
|
+
}
|
|
114
|
+
function resampleStrokes(strokes, n = POINTS_PER_SHAPE) {
|
|
115
|
+
const segs = [];
|
|
116
|
+
let cum = 0;
|
|
117
|
+
for (const stroke of strokes) {
|
|
118
|
+
for (let i = 1; i < stroke.length; i++) {
|
|
119
|
+
const dx = stroke[i].x - stroke[i - 1].x;
|
|
120
|
+
const dy = stroke[i].y - stroke[i - 1].y;
|
|
121
|
+
const len = Math.sqrt(dx * dx + dy * dy);
|
|
122
|
+
segs.push({ ax: stroke[i - 1].x, ay: stroke[i - 1].y, bx: stroke[i].x, by: stroke[i].y, cumStart: cum, cumEnd: cum + len });
|
|
123
|
+
cum += len;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (!cum || !segs.length) return null;
|
|
127
|
+
const out = [];
|
|
128
|
+
let s = 0;
|
|
129
|
+
for (let i = 0; i < n; i++) {
|
|
130
|
+
const target = i * cum / (n - 1);
|
|
131
|
+
while (s < segs.length - 1 && segs[s].cumEnd < target) s++;
|
|
132
|
+
const seg = segs[s];
|
|
133
|
+
const span = seg.cumEnd - seg.cumStart;
|
|
134
|
+
const t = span ? Math.min(1, Math.max(0, (target - seg.cumStart) / span)) : 0;
|
|
135
|
+
out.push({ x: seg.ax + (seg.bx - seg.ax) * t, y: seg.ay + (seg.by - seg.ay) * t });
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
function polylineToSample(polyline) {
|
|
140
|
+
return encodeSample(polyline);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ../../core/format/schema.js
|
|
144
|
+
var FORMAT_VERSION = 2;
|
|
145
|
+
var isCloudSample = (sample) => Array.isArray(sample);
|
|
146
|
+
var isSample = (s) => isCloudSample(s) ? s.every((p) => typeof p?.x === "number" && typeof p?.y === "number") : Array.isArray(s?.x) && Array.isArray(s?.y) && s.x.length === s.y.length;
|
|
147
|
+
function isV1(json) {
|
|
148
|
+
return !!json && typeof json === "object" && !json.version && !json.classes && Object.values(json).every(Array.isArray);
|
|
149
|
+
}
|
|
150
|
+
function migrateV1(v1, { mode = "both" } = {}) {
|
|
151
|
+
const classes = {};
|
|
152
|
+
for (const [cls, samples] of Object.entries(v1)) classes[cls] = { samples, geometry: null };
|
|
153
|
+
return { version: FORMAT_VERSION, mode, pointsPerShape: 50, classes, ext: {} };
|
|
154
|
+
}
|
|
155
|
+
function validate(data) {
|
|
156
|
+
const errors = [];
|
|
157
|
+
if (!data || typeof data !== "object") return ["not an object"];
|
|
158
|
+
if (typeof data.version !== "number" || data.version < 2) errors.push("bad version");
|
|
159
|
+
if (!data.classes || typeof data.classes !== "object" || !Object.keys(data.classes).length) {
|
|
160
|
+
errors.push("no classes");
|
|
161
|
+
return errors;
|
|
162
|
+
}
|
|
163
|
+
for (const [cls, entry] of Object.entries(data.classes)) {
|
|
164
|
+
if (!Array.isArray(entry?.samples) || !entry.samples.length) {
|
|
165
|
+
errors.push(`class ${cls}: no samples`);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
entry.samples.forEach((s, i) => {
|
|
169
|
+
if (!isSample(s)) errors.push(`class ${cls} sample ${i}: bad shape`);
|
|
170
|
+
});
|
|
171
|
+
const g = entry.geometry;
|
|
172
|
+
if (g != null && typeof g !== "object") errors.push(`class ${cls}: bad geometry`);
|
|
173
|
+
}
|
|
174
|
+
if (data.wordList != null && !Array.isArray(data.wordList)) errors.push("bad wordList");
|
|
175
|
+
if (data.params != null && typeof data.params !== "object") errors.push("bad params");
|
|
176
|
+
return errors;
|
|
177
|
+
}
|
|
178
|
+
function decode(json) {
|
|
179
|
+
const data = isV1(json) ? migrateV1(json) : json;
|
|
180
|
+
const errors = validate(data);
|
|
181
|
+
if (errors.length) throw new Error("invalid training data: " + errors.join("; "));
|
|
182
|
+
if (!data.mode) data.mode = "both";
|
|
183
|
+
if (!data.pointsPerShape) data.pointsPerShape = 50;
|
|
184
|
+
if (!data.ext) data.ext = {};
|
|
185
|
+
return data;
|
|
186
|
+
}
|
|
187
|
+
function samplesMap(data) {
|
|
188
|
+
const out = {};
|
|
189
|
+
for (const [cls, entry] of Object.entries(data.classes)) out[cls] = entry.samples;
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ../../widget/scribble.js
|
|
194
|
+
var SCRIBBLE = {
|
|
195
|
+
turns: 5,
|
|
196
|
+
// reversals along the principal axis (no letter reaches 6; the scribble reaches 8)
|
|
197
|
+
retrace: 0.5,
|
|
198
|
+
// share of the path laid back over its own ground (letters <= 0.54 at ANY turn count)
|
|
199
|
+
winding: 3.5,
|
|
200
|
+
// path length / bbox diagonal (letters at 5 turns reach 3.29; the scribble 6.14)
|
|
201
|
+
cover: 0.6,
|
|
202
|
+
// how completely this stroke and the existing ink overlap, per axis
|
|
203
|
+
minLength: 40,
|
|
204
|
+
// px of path — a small wiggle is not a scribble
|
|
205
|
+
minSpan: 12,
|
|
206
|
+
// px of bbox diagonal — nor is a dense scrub of one point
|
|
207
|
+
deadband: 0.22
|
|
208
|
+
// a reversal must retrace this much of the axis's extent
|
|
209
|
+
};
|
|
210
|
+
var INK_HALF = 2;
|
|
211
|
+
function grow(b) {
|
|
212
|
+
return { x0: b.x0 - INK_HALF, y0: b.y0 - INK_HALF, x1: b.x1 + INK_HALF, y1: b.y1 + INK_HALF, w: b.w + 2 * INK_HALF, h: b.h + 2 * INK_HALF };
|
|
213
|
+
}
|
|
214
|
+
function bbox(pts) {
|
|
215
|
+
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
|
216
|
+
for (const p of pts) {
|
|
217
|
+
const x = p.x !== void 0 ? p.x : p[0], y = p.y !== void 0 ? p.y : p[1];
|
|
218
|
+
if (x < x0) x0 = x;
|
|
219
|
+
if (x > x1) x1 = x;
|
|
220
|
+
if (y < y0) y0 = y;
|
|
221
|
+
if (y > y1) y1 = y;
|
|
222
|
+
}
|
|
223
|
+
return { x0, y0, x1, y1, w: x1 - x0, h: y1 - y0 };
|
|
224
|
+
}
|
|
225
|
+
function turnsAlong(vals, deadband) {
|
|
226
|
+
let lo = Infinity, hi = -Infinity;
|
|
227
|
+
for (const v of vals) {
|
|
228
|
+
if (v < lo) lo = v;
|
|
229
|
+
if (v > hi) hi = v;
|
|
230
|
+
}
|
|
231
|
+
const band = (hi - lo) * deadband;
|
|
232
|
+
if (!(band > 0)) return 0;
|
|
233
|
+
let dir = 0, ext = vals[0], turns = 0;
|
|
234
|
+
for (const v of vals) {
|
|
235
|
+
if (dir > 0) {
|
|
236
|
+
if (v > ext) ext = v;
|
|
237
|
+
else if (v < ext - band) {
|
|
238
|
+
turns++;
|
|
239
|
+
dir = -1;
|
|
240
|
+
ext = v;
|
|
241
|
+
}
|
|
242
|
+
} else if (dir < 0) {
|
|
243
|
+
if (v < ext) ext = v;
|
|
244
|
+
else if (v > ext + band) {
|
|
245
|
+
turns++;
|
|
246
|
+
dir = 1;
|
|
247
|
+
ext = v;
|
|
248
|
+
}
|
|
249
|
+
} else if (v > ext + band) {
|
|
250
|
+
dir = 1;
|
|
251
|
+
ext = v;
|
|
252
|
+
} else if (v < ext - band) {
|
|
253
|
+
dir = -1;
|
|
254
|
+
ext = v;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return turns;
|
|
258
|
+
}
|
|
259
|
+
function axes(pts) {
|
|
260
|
+
let mx = 0, my = 0;
|
|
261
|
+
for (const p of pts) {
|
|
262
|
+
mx += p.x;
|
|
263
|
+
my += p.y;
|
|
264
|
+
}
|
|
265
|
+
mx /= pts.length;
|
|
266
|
+
my /= pts.length;
|
|
267
|
+
let sxx = 0, sxy = 0, syy = 0;
|
|
268
|
+
for (const p of pts) {
|
|
269
|
+
const dx = p.x - mx, dy = p.y - my;
|
|
270
|
+
sxx += dx * dx;
|
|
271
|
+
sxy += dx * dy;
|
|
272
|
+
syy += dy * dy;
|
|
273
|
+
}
|
|
274
|
+
const tr = sxx + syy, det = sxx * syy - sxy * sxy;
|
|
275
|
+
const l = tr / 2 + Math.sqrt(Math.max(0, tr * tr / 4 - det));
|
|
276
|
+
let ux = sxy, uy = l - sxx;
|
|
277
|
+
if (Math.hypot(ux, uy) < 1e-9) {
|
|
278
|
+
ux = 1;
|
|
279
|
+
uy = 0;
|
|
280
|
+
}
|
|
281
|
+
const n = Math.hypot(ux, uy);
|
|
282
|
+
return { ux: ux / n, uy: uy / n };
|
|
283
|
+
}
|
|
284
|
+
var RETRACE_R = 0.09;
|
|
285
|
+
var RETRACE_SKIP = 4;
|
|
286
|
+
function retraceOf(pts, span) {
|
|
287
|
+
const r = Math.max(2, span * RETRACE_R);
|
|
288
|
+
const step = r / 2;
|
|
289
|
+
const rs = [pts[0]];
|
|
290
|
+
let carry = 0;
|
|
291
|
+
for (let i = 1; i < pts.length; i++) {
|
|
292
|
+
const dx = pts[i].x - pts[i - 1].x, dy = pts[i].y - pts[i - 1].y;
|
|
293
|
+
let d = Math.hypot(dx, dy);
|
|
294
|
+
if (!(d > 0)) continue;
|
|
295
|
+
let t = (step - carry) / d;
|
|
296
|
+
while (t <= 1) {
|
|
297
|
+
rs.push({ x: pts[i - 1].x + dx * t, y: pts[i - 1].y + dy * t });
|
|
298
|
+
t += step / d;
|
|
299
|
+
}
|
|
300
|
+
carry = (carry + d) % step;
|
|
301
|
+
}
|
|
302
|
+
if (rs.length < 8) return 0;
|
|
303
|
+
const skip = Math.round(RETRACE_SKIP * r / step);
|
|
304
|
+
const key = (p) => `${Math.floor(p.x / r)},${Math.floor(p.y / r)}`;
|
|
305
|
+
const grid = /* @__PURE__ */ new Map();
|
|
306
|
+
rs.forEach((p, i) => {
|
|
307
|
+
const k = key(p);
|
|
308
|
+
if (!grid.has(k)) grid.set(k, []);
|
|
309
|
+
grid.get(k).push(i);
|
|
310
|
+
});
|
|
311
|
+
let hit = 0;
|
|
312
|
+
for (let i = 0; i < rs.length; i++) {
|
|
313
|
+
const p = rs[i];
|
|
314
|
+
const cx = Math.floor(p.x / r), cy = Math.floor(p.y / r);
|
|
315
|
+
let found = false;
|
|
316
|
+
for (let ax = -1; ax <= 1 && !found; ax++) {
|
|
317
|
+
for (let ay = -1; ay <= 1 && !found; ay++) {
|
|
318
|
+
for (const j of grid.get(`${cx + ax},${cy + ay}`) || []) {
|
|
319
|
+
if (Math.abs(i - j) <= skip) continue;
|
|
320
|
+
if (Math.hypot(rs[j].x - p.x, rs[j].y - p.y) <= r) {
|
|
321
|
+
found = true;
|
|
322
|
+
break;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (found) hit++;
|
|
328
|
+
}
|
|
329
|
+
return hit / rs.length;
|
|
330
|
+
}
|
|
331
|
+
function scribbleFeatures(stroke, prior = [], opts = {}) {
|
|
332
|
+
const k = { ...SCRIBBLE, ...opts };
|
|
333
|
+
const pts = [];
|
|
334
|
+
for (const p of stroke) {
|
|
335
|
+
const q = { x: p.x !== void 0 ? p.x : p[0], y: p.y !== void 0 ? p.y : p[1] };
|
|
336
|
+
const last = pts[pts.length - 1];
|
|
337
|
+
if (!last || Math.hypot(q.x - last.x, q.y - last.y) > 0.75) pts.push(q);
|
|
338
|
+
}
|
|
339
|
+
if (pts.length < 4) return { turns: 0, cross: 0, retrace: 0, winding: 0, cover: 0, length: 0, span: 0 };
|
|
340
|
+
let length = 0;
|
|
341
|
+
for (let i = 1; i < pts.length; i++) length += Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
|
|
342
|
+
const b = bbox(pts);
|
|
343
|
+
const span = Math.hypot(b.w, b.h);
|
|
344
|
+
const { ux, uy } = axes(pts);
|
|
345
|
+
const major = pts.map((p) => p.x * ux + p.y * uy);
|
|
346
|
+
const minor = pts.map((p) => -p.x * uy + p.y * ux);
|
|
347
|
+
const turns = turnsAlong(major, k.deadband);
|
|
348
|
+
const cross = turnsAlong(minor, k.deadband);
|
|
349
|
+
let cover = 0;
|
|
350
|
+
const flat = [];
|
|
351
|
+
for (const st of prior) for (const p of st) flat.push(p);
|
|
352
|
+
if (flat.length) {
|
|
353
|
+
const a = grow(bbox(flat));
|
|
354
|
+
const c = grow(b);
|
|
355
|
+
const ox = Math.max(0, Math.min(a.x1, c.x1) - Math.max(a.x0, c.x0));
|
|
356
|
+
const oy = Math.max(0, Math.min(a.y1, c.y1) - Math.max(a.y0, c.y0));
|
|
357
|
+
cover = ox / Math.min(a.w, c.w) * (oy / Math.min(a.h, c.h));
|
|
358
|
+
}
|
|
359
|
+
return { turns, cross, retrace: retraceOf(pts, span), winding: span > 0 ? length / span : 0, cover, length, span };
|
|
360
|
+
}
|
|
361
|
+
function isScribble(stroke, prior = [], opts = {}) {
|
|
362
|
+
const k = { ...SCRIBBLE, ...opts };
|
|
363
|
+
if (!prior || !prior.length) return false;
|
|
364
|
+
const f = scribbleFeatures(stroke, prior, k);
|
|
365
|
+
return f.length >= k.minLength && f.span >= k.minSpan && f.turns >= k.turns && f.retrace >= k.retrace && f.winding >= k.winding && f.cover >= k.cover;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ../../widget/canvas.js
|
|
369
|
+
var ERASE_RADIUS = 12;
|
|
370
|
+
var now = () => typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
|
|
371
|
+
function createDrawCanvas({
|
|
372
|
+
width = 160,
|
|
373
|
+
height = 90,
|
|
374
|
+
ink = "#111827",
|
|
375
|
+
onStrokeEnd,
|
|
376
|
+
colorOf = null,
|
|
377
|
+
idleOverwrite = 0,
|
|
378
|
+
scribbleClear = false,
|
|
379
|
+
scribble = null,
|
|
380
|
+
onClear = null,
|
|
381
|
+
staleAlpha = 0.3,
|
|
382
|
+
onStale = null
|
|
383
|
+
}) {
|
|
384
|
+
const canvas = document.createElement("canvas");
|
|
385
|
+
const dpr = typeof devicePixelRatio !== "undefined" && devicePixelRatio || 1;
|
|
386
|
+
canvas.width = width * dpr;
|
|
387
|
+
canvas.height = height * dpr;
|
|
388
|
+
canvas.style.width = width + "px";
|
|
389
|
+
canvas.style.height = height + "px";
|
|
390
|
+
canvas.style.touchAction = "none";
|
|
391
|
+
const ctx = canvas.getContext("2d");
|
|
392
|
+
ctx.scale(dpr, dpr);
|
|
393
|
+
let strokes = [];
|
|
394
|
+
let current = [];
|
|
395
|
+
let activeId = null;
|
|
396
|
+
let erasing = false;
|
|
397
|
+
let nextId = 1;
|
|
398
|
+
let lastEndAt = 0;
|
|
399
|
+
let staleTimer = 0;
|
|
400
|
+
let stale = false;
|
|
401
|
+
let dropped = null;
|
|
402
|
+
let droppedPending = false;
|
|
403
|
+
function paint(st, color) {
|
|
404
|
+
if (st.length < 2) return;
|
|
405
|
+
ctx.strokeStyle = color || ink;
|
|
406
|
+
ctx.beginPath();
|
|
407
|
+
ctx.moveTo(st[0].x, st[0].y);
|
|
408
|
+
for (let i = 1; i < st.length; i++) ctx.lineTo(st[i].x, st[i].y);
|
|
409
|
+
ctx.stroke();
|
|
410
|
+
}
|
|
411
|
+
function render() {
|
|
412
|
+
ctx.clearRect(0, 0, width, height);
|
|
413
|
+
ctx.lineWidth = 2.5;
|
|
414
|
+
ctx.lineCap = "round";
|
|
415
|
+
ctx.lineJoin = "round";
|
|
416
|
+
ctx.globalAlpha = stale ? staleAlpha : 1;
|
|
417
|
+
for (const st of strokes) paint(st, colorOf && colorOf(st));
|
|
418
|
+
ctx.globalAlpha = 1;
|
|
419
|
+
paint(current, null);
|
|
420
|
+
}
|
|
421
|
+
function setStale(v) {
|
|
422
|
+
if (stale === v) return;
|
|
423
|
+
stale = v;
|
|
424
|
+
render();
|
|
425
|
+
if (onStale) onStale(v);
|
|
426
|
+
}
|
|
427
|
+
function armStale() {
|
|
428
|
+
clearTimeout(staleTimer);
|
|
429
|
+
staleTimer = 0;
|
|
430
|
+
const ms = (Number(idleOverwrite) || 0) * 1e3;
|
|
431
|
+
if (!ms || !strokes.length) {
|
|
432
|
+
setStale(false);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const left = ms - (now() - lastEndAt);
|
|
436
|
+
if (left <= 0) {
|
|
437
|
+
setStale(true);
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
setStale(false);
|
|
441
|
+
staleTimer = setTimeout(() => setStale(true), left);
|
|
442
|
+
}
|
|
443
|
+
function dropAll(reason) {
|
|
444
|
+
if (!strokes.length) return;
|
|
445
|
+
dropped = strokes;
|
|
446
|
+
strokes = [];
|
|
447
|
+
clearTimeout(staleTimer);
|
|
448
|
+
staleTimer = 0;
|
|
449
|
+
setStale(false);
|
|
450
|
+
render();
|
|
451
|
+
if (onClear) onClear(reason);
|
|
452
|
+
}
|
|
453
|
+
function eraseAt(x, y) {
|
|
454
|
+
const kept = strokes.filter((st) => !st.some((p) => Math.hypot(p.x - x, p.y - y) <= ERASE_RADIUS));
|
|
455
|
+
if (kept.length === strokes.length) return false;
|
|
456
|
+
strokes = kept;
|
|
457
|
+
render();
|
|
458
|
+
return true;
|
|
459
|
+
}
|
|
460
|
+
let rect = null;
|
|
461
|
+
const getPos = (e) => {
|
|
462
|
+
const r = rect || (rect = canvas.getBoundingClientRect());
|
|
463
|
+
const sx = width / (canvas.clientWidth || width), sy = height / (canvas.clientHeight || height);
|
|
464
|
+
return { x: (e.clientX - r.left - canvas.clientLeft) * sx, y: (e.clientY - r.top - canvas.clientTop) * sy, p: e.pressure || 0.5 };
|
|
465
|
+
};
|
|
466
|
+
let erasedAny = false;
|
|
467
|
+
let activeType = null;
|
|
468
|
+
const swallow = (e) => e.preventDefault();
|
|
469
|
+
canvas.addEventListener("touchstart", swallow, { passive: false });
|
|
470
|
+
canvas.addEventListener("touchmove", swallow, { passive: false });
|
|
471
|
+
canvas.addEventListener("contextmenu", swallow);
|
|
472
|
+
canvas.style.userSelect = canvas.style.webkitUserSelect = "none";
|
|
473
|
+
canvas.style.webkitTouchCallout = "none";
|
|
474
|
+
canvas.addEventListener("pointerdown", (e) => {
|
|
475
|
+
if (e.button > 0) return;
|
|
476
|
+
if (activeId !== null && activeId !== e.pointerId) {
|
|
477
|
+
if (activeType === "pen" && e.pointerType !== "pen") return;
|
|
478
|
+
finish({ pointerId: activeId });
|
|
479
|
+
}
|
|
480
|
+
e.preventDefault();
|
|
481
|
+
activeId = e.pointerId;
|
|
482
|
+
activeType = e.pointerType;
|
|
483
|
+
rect = canvas.getBoundingClientRect();
|
|
484
|
+
try {
|
|
485
|
+
canvas.setPointerCapture(e.pointerId);
|
|
486
|
+
} catch {
|
|
487
|
+
}
|
|
488
|
+
const pos = getPos(e);
|
|
489
|
+
if (erasing) {
|
|
490
|
+
erasedAny = eraseAt(pos.x, pos.y);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
if (stale && strokes.length) {
|
|
494
|
+
dropAll("idle");
|
|
495
|
+
droppedPending = true;
|
|
496
|
+
}
|
|
497
|
+
current = [pos];
|
|
498
|
+
render();
|
|
499
|
+
}, { passive: false });
|
|
500
|
+
canvas.addEventListener("pointermove", (e) => {
|
|
501
|
+
if (activeId !== e.pointerId) return;
|
|
502
|
+
e.preventDefault();
|
|
503
|
+
const co = e.getCoalescedEvents ? e.getCoalescedEvents() : null;
|
|
504
|
+
const events = co && co.length ? co : [e];
|
|
505
|
+
if (erasing) {
|
|
506
|
+
for (const ev of events) {
|
|
507
|
+
const p = getPos(ev);
|
|
508
|
+
if (eraseAt(p.x, p.y)) erasedAny = true;
|
|
509
|
+
}
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
for (const ev of events) current.push(getPos(ev));
|
|
513
|
+
render();
|
|
514
|
+
}, { passive: false });
|
|
515
|
+
const finish = (e, cancelled = false) => {
|
|
516
|
+
if (activeId !== e.pointerId) return;
|
|
517
|
+
try {
|
|
518
|
+
canvas.releasePointerCapture(e.pointerId);
|
|
519
|
+
} catch {
|
|
520
|
+
}
|
|
521
|
+
activeId = null;
|
|
522
|
+
activeType = null;
|
|
523
|
+
rect = null;
|
|
524
|
+
if (erasing) {
|
|
525
|
+
if (erasedAny) {
|
|
526
|
+
lastEndAt = now();
|
|
527
|
+
armStale();
|
|
528
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
529
|
+
}
|
|
530
|
+
erasedAny = false;
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
if (current.length > 0) {
|
|
534
|
+
let st = current;
|
|
535
|
+
if (st.length === 1) {
|
|
536
|
+
if (cancelled) {
|
|
537
|
+
current = [];
|
|
538
|
+
render();
|
|
539
|
+
if (droppedPending) {
|
|
540
|
+
droppedPending = false;
|
|
541
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
542
|
+
}
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
const p = st[0];
|
|
546
|
+
st = [{ x: p.x - 1, y: p.y, p: p.p }, { x: p.x + 1, y: p.y, p: p.p }];
|
|
547
|
+
}
|
|
548
|
+
const aimedAt = strokes.length ? strokes : droppedPending ? dropped : null;
|
|
549
|
+
if (scribbleClear && aimedAt && aimedAt.length && isScribble(st, aimedAt, scribble || {})) {
|
|
550
|
+
current = [];
|
|
551
|
+
lastEndAt = now();
|
|
552
|
+
droppedPending = false;
|
|
553
|
+
if (strokes.length) dropAll("scribble");
|
|
554
|
+
else {
|
|
555
|
+
render();
|
|
556
|
+
if (onClear) onClear("scribble");
|
|
557
|
+
}
|
|
558
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
st.id = nextId++;
|
|
562
|
+
strokes = [...strokes, st];
|
|
563
|
+
current = [];
|
|
564
|
+
droppedPending = false;
|
|
565
|
+
lastEndAt = now();
|
|
566
|
+
armStale();
|
|
567
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
568
|
+
}
|
|
569
|
+
render();
|
|
570
|
+
};
|
|
571
|
+
canvas.addEventListener("pointerup", (e) => finish(e));
|
|
572
|
+
canvas.addEventListener("pointercancel", (e) => finish(e, true));
|
|
573
|
+
return {
|
|
574
|
+
el: canvas,
|
|
575
|
+
getStrokes: () => strokes,
|
|
576
|
+
setInk(color) {
|
|
577
|
+
ink = color;
|
|
578
|
+
render();
|
|
579
|
+
},
|
|
580
|
+
setErasing(on) {
|
|
581
|
+
erasing = !!on;
|
|
582
|
+
canvas.style.cursor = erasing ? "cell" : "crosshair";
|
|
583
|
+
},
|
|
584
|
+
isErasing: () => erasing,
|
|
585
|
+
repaint: render,
|
|
586
|
+
/** True once the idle window has passed: the next stroke starts fresh. */
|
|
587
|
+
isStale: () => stale,
|
|
588
|
+
/**
|
|
589
|
+
* Put back what the pad cleared BY ITSELF — an idle overwrite or a
|
|
590
|
+
* scribble. An explicit `clear()` is not stashed: a caller clears the pad
|
|
591
|
+
* because it has banked the drawing, and restoring that would hand back a
|
|
592
|
+
* sample the writer already dealt with.
|
|
593
|
+
*/
|
|
594
|
+
undoClear() {
|
|
595
|
+
if (!dropped || !dropped.length) return false;
|
|
596
|
+
strokes = strokes.length ? [...dropped, ...strokes] : dropped;
|
|
597
|
+
dropped = null;
|
|
598
|
+
lastEndAt = now();
|
|
599
|
+
armStale();
|
|
600
|
+
render();
|
|
601
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
602
|
+
return true;
|
|
603
|
+
},
|
|
604
|
+
/** Change either overwrite behaviour, or the settled look, at runtime. */
|
|
605
|
+
configure(opts = {}) {
|
|
606
|
+
if ("idleOverwrite" in opts) idleOverwrite = Number(opts.idleOverwrite) || 0;
|
|
607
|
+
if ("scribbleClear" in opts) scribbleClear = !!opts.scribbleClear;
|
|
608
|
+
if ("scribble" in opts) scribble = opts.scribble;
|
|
609
|
+
if ("staleAlpha" in opts) staleAlpha = Number(opts.staleAlpha);
|
|
610
|
+
armStale();
|
|
611
|
+
},
|
|
612
|
+
clear() {
|
|
613
|
+
strokes = [];
|
|
614
|
+
current = [];
|
|
615
|
+
activeId = null;
|
|
616
|
+
activeType = null;
|
|
617
|
+
rect = null;
|
|
618
|
+
clearTimeout(staleTimer);
|
|
619
|
+
staleTimer = 0;
|
|
620
|
+
setStale(false);
|
|
621
|
+
droppedPending = false;
|
|
622
|
+
render();
|
|
623
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// ../../library/src/assetbase.js
|
|
629
|
+
function assetBaseOf(base) {
|
|
630
|
+
let s = base ? String(base) : "";
|
|
631
|
+
if (!s) return typeof location !== "undefined" ? new URL("./", location.href).href : "";
|
|
632
|
+
if (!s.endsWith("/")) s += "/";
|
|
633
|
+
return typeof location !== "undefined" ? new URL(s, location.href).href : s;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// ../../library/src/char-lite.js
|
|
637
|
+
function scriptBase() {
|
|
638
|
+
const src = typeof document !== "undefined" && document.currentScript && document.currentScript.src || "";
|
|
639
|
+
return src ? src.slice(0, src.lastIndexOf("/") + 1) : "";
|
|
640
|
+
}
|
|
641
|
+
var ASSET_BASE = scriptBase();
|
|
642
|
+
var StrokeWorker = class {
|
|
643
|
+
constructor({ assetBase, workerName, training, params }) {
|
|
644
|
+
assetBase = assetBaseOf(assetBase);
|
|
645
|
+
const decoded = decode(training);
|
|
646
|
+
this.trainPaths = samplesMap(decoded);
|
|
647
|
+
this.charList = Object.keys(this.trainPaths);
|
|
648
|
+
this.samplesPerChar = Math.max(1, ...this.charList.map((c) => this.trainPaths[c].length));
|
|
649
|
+
this.pointsPerShape = decoded.pointsPerShape || POINTS_PER_SHAPE;
|
|
650
|
+
this.params = params || decoded.params || null;
|
|
651
|
+
this.plugins = [];
|
|
652
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
653
|
+
this.inFlight = /* @__PURE__ */ new Map();
|
|
654
|
+
this.allWaiters = /* @__PURE__ */ new Map();
|
|
655
|
+
this.reqCounter = 0;
|
|
656
|
+
const boot = `self.__MILLIREC_ASSET_BASE=${JSON.stringify(assetBase)};importScripts(${JSON.stringify(assetBase + workerName)});`;
|
|
657
|
+
this.bootUrl = URL.createObjectURL(new Blob([boot], { type: "text/javascript" }));
|
|
658
|
+
this.worker = new Worker(this.bootUrl);
|
|
659
|
+
this.readyPromise = new Promise((resolve, reject) => {
|
|
660
|
+
this.readyResolve = resolve;
|
|
661
|
+
this.readyReject = reject;
|
|
662
|
+
});
|
|
663
|
+
this.worker.onmessage = (evt) => this.onMessage(evt);
|
|
664
|
+
this.worker.onerror = (evt) => this.readyReject(new Error("millirec worker error: " + (evt.message || "script failed to load")));
|
|
665
|
+
}
|
|
666
|
+
onMessage(evt) {
|
|
667
|
+
const d = evt.data;
|
|
668
|
+
if (this.bootUrl) {
|
|
669
|
+
URL.revokeObjectURL(this.bootUrl);
|
|
670
|
+
this.bootUrl = null;
|
|
671
|
+
}
|
|
672
|
+
if (d.type === "getCharList") {
|
|
673
|
+
if (this.params) this.worker.postMessage({ type: "setParams", params: this.params });
|
|
674
|
+
this.worker.postMessage({ type: "charList", charList: this.charList, pointsPerShape: this.pointsPerShape, samplesPerChar: this.samplesPerChar });
|
|
675
|
+
} else if (d.type === "prepAll") {
|
|
676
|
+
this.charList.forEach((c, idx) => {
|
|
677
|
+
this.trainPaths[c].forEach((sample, i) => {
|
|
678
|
+
const { points, scale } = orientedPointsFromPolyline(decodeSample(sample));
|
|
679
|
+
this.worker.postMessage({ type: "addPoints", points, m: idx * this.samplesPerChar + i, scale });
|
|
680
|
+
});
|
|
681
|
+
});
|
|
682
|
+
this.readyResolve();
|
|
683
|
+
} else if (d.type === "addResult" && d.result) {
|
|
684
|
+
this.cache.set(d.path, d.result);
|
|
685
|
+
const waiters = this.inFlight.get(d.path) || [];
|
|
686
|
+
this.inFlight.delete(d.path);
|
|
687
|
+
for (const resolve of waiters) resolve(this.applyPlugins(d.result, d.path));
|
|
688
|
+
} else if (d.type === "allResult") {
|
|
689
|
+
const waiters = this.allWaiters.get(d.path) || [];
|
|
690
|
+
this.allWaiters.delete(d.path);
|
|
691
|
+
for (const resolve of waiters) resolve(d.costs);
|
|
692
|
+
} else if (d.type === "bootError") {
|
|
693
|
+
this.readyReject(new Error("millirec worker boot failed: " + d.message));
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
applyPlugins(raw, path) {
|
|
697
|
+
let out = parseResult(raw, this.charList, "stroke", SECOND_AVERAGE);
|
|
698
|
+
for (const p of this.plugins) if (p.rerank) out = p.rerank(out, { raw, path, charList: this.charList, mode: "stroke", recognizer: this }) || out;
|
|
699
|
+
return out;
|
|
700
|
+
}
|
|
701
|
+
uploadTest(input) {
|
|
702
|
+
const strokes = Array.isArray(input[0]) ? input : [input];
|
|
703
|
+
const polyline = resampleStrokes(strokes, this.pointsPerShape);
|
|
704
|
+
if (!polyline) return false;
|
|
705
|
+
const { points, scale } = orientedPointsFromPolyline(polyline);
|
|
706
|
+
this.worker.postMessage({ type: "addPoints", points, m: -1, scale });
|
|
707
|
+
return true;
|
|
708
|
+
}
|
|
709
|
+
keyFor(input) {
|
|
710
|
+
const flat = Array.isArray(input[0]) ? input.flat() : input;
|
|
711
|
+
let hash = 5381;
|
|
712
|
+
for (const p of flat) hash = (hash * 33 ^ (p.x * 7919 + p.y | 0)) >>> 0;
|
|
713
|
+
return "strokes:" + flat.length + ":" + hash.toString(36);
|
|
714
|
+
}
|
|
715
|
+
async recognize(strokes) {
|
|
716
|
+
if (!strokes || !strokes.length) return null;
|
|
717
|
+
await this.readyPromise;
|
|
718
|
+
const key = this.keyFor(strokes);
|
|
719
|
+
if (this.cache.has(key)) return this.applyPlugins(this.cache.get(key), key);
|
|
720
|
+
if (!this.uploadTest(strokes)) return null;
|
|
721
|
+
return new Promise((resolve) => {
|
|
722
|
+
let timer;
|
|
723
|
+
const done = (v) => {
|
|
724
|
+
clearTimeout(timer);
|
|
725
|
+
resolve(v);
|
|
726
|
+
};
|
|
727
|
+
if (this.inFlight.has(key)) this.inFlight.get(key).push(done);
|
|
728
|
+
else {
|
|
729
|
+
this.inFlight.set(key, [done]);
|
|
730
|
+
this.worker.postMessage({ type: "compare", path: key, elementID: "req" + ++this.reqCounter });
|
|
731
|
+
}
|
|
732
|
+
timer = setTimeout(() => done(null), 4e3);
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
async rawScores(strokes) {
|
|
736
|
+
await this.readyPromise;
|
|
737
|
+
if (!this.uploadTest(strokes)) return null;
|
|
738
|
+
const key = "all:" + ++this.reqCounter;
|
|
739
|
+
const costs = await new Promise((resolve) => {
|
|
740
|
+
let timer;
|
|
741
|
+
const done = (v) => {
|
|
742
|
+
clearTimeout(timer);
|
|
743
|
+
resolve(v);
|
|
744
|
+
};
|
|
745
|
+
this.allWaiters.set(key, [done]);
|
|
746
|
+
this.worker.postMessage({ type: "compareAll", path: key, counts: this.charList.map((c) => this.trainPaths[c].length) });
|
|
747
|
+
timer = setTimeout(() => done(null), 8e3);
|
|
748
|
+
});
|
|
749
|
+
return costs ? { classes: this.charList, costs } : null;
|
|
750
|
+
}
|
|
751
|
+
destroy() {
|
|
752
|
+
this.worker.terminate();
|
|
753
|
+
if (this.bootUrl) {
|
|
754
|
+
URL.revokeObjectURL(this.bootUrl);
|
|
755
|
+
this.bootUrl = null;
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
var toPairs = (parsed) => parsed ? parsed.chars.map((c, i) => ({ char: c, prob: parsed.probs[i] })) : null;
|
|
760
|
+
var MillirecCharLite = class {
|
|
761
|
+
/** Drawn strokes → one training sample (resampled points, delta-encoded).
|
|
762
|
+
* Pass the set's pointsPerShape to match it (the shipped sets are 25). */
|
|
763
|
+
static strokesToSample(strokes, pointsPerShape = POINTS_PER_SHAPE) {
|
|
764
|
+
const polyline = resampleStrokes(Array.isArray(strokes[0]) ? strokes : [strokes], pointsPerShape);
|
|
765
|
+
return polyline ? polylineToSample(polyline) : null;
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* A copy of `training` with your own samples added — the way to make a
|
|
769
|
+
* recognizer learn one person's hand. `extra` maps a class (any string: a
|
|
770
|
+
* letter, a digit, an emoji) to drawings: strokes ([[{x,y},...], ...]) or
|
|
771
|
+
* already-encoded samples ({x:[Δ...], y:[Δ...]}). Each is resampled to the
|
|
772
|
+
* set's pointsPerShape. Classes not in `training` are added. `replace: true`
|
|
773
|
+
* drops a class's shipped samples instead of appending to them. `training`
|
|
774
|
+
* is not modified.
|
|
775
|
+
*/
|
|
776
|
+
static withSamples(training, extra, { replace = false } = {}) {
|
|
777
|
+
const base = decode({ ...training });
|
|
778
|
+
const n = base.pointsPerShape;
|
|
779
|
+
const toSample = (d) => {
|
|
780
|
+
const strokes = Array.isArray(d) ? Array.isArray(d[0]) ? d : [d] : [decodeSample(d)];
|
|
781
|
+
const polyline = resampleStrokes(strokes, n);
|
|
782
|
+
return polyline ? polylineToSample(polyline) : null;
|
|
783
|
+
};
|
|
784
|
+
const classes = { ...base.classes };
|
|
785
|
+
for (const [cls, drawings] of Object.entries(extra || {})) {
|
|
786
|
+
const own = (drawings || []).map(toSample).filter(Boolean);
|
|
787
|
+
if (!own.length) continue;
|
|
788
|
+
const shipped = classes[cls]?.samples || [];
|
|
789
|
+
classes[cls] = { ...classes[cls] || {}, samples: replace ? own : shipped.concat(own) };
|
|
790
|
+
}
|
|
791
|
+
return { ...base, classes };
|
|
792
|
+
}
|
|
793
|
+
static createDrawCanvas(opts) {
|
|
794
|
+
return createDrawCanvas(opts);
|
|
795
|
+
}
|
|
796
|
+
/** opts: training (default window.MILLIREC_TRAINING), assetBase (default:
|
|
797
|
+
* alongside this script), params (matcher overrides), workerStroke. */
|
|
798
|
+
static async create(opts = {}) {
|
|
799
|
+
const g = typeof window !== "undefined" ? window : globalThis;
|
|
800
|
+
const config = { ...g.MILLIREC_CONFIG || {}, ...opts };
|
|
801
|
+
const training = opts.training || g.MILLIREC_TRAINING;
|
|
802
|
+
if (!training) throw new Error("MillirecCharLite: no training data (training.js missing?)");
|
|
803
|
+
const inst = new this(config, training);
|
|
804
|
+
await inst.ready;
|
|
805
|
+
return inst;
|
|
806
|
+
}
|
|
807
|
+
constructor(config, training) {
|
|
808
|
+
this.config = config;
|
|
809
|
+
this.stroke = new StrokeWorker({
|
|
810
|
+
assetBase: config.assetBase || ASSET_BASE,
|
|
811
|
+
workerName: config.workerStroke || "worker-stroke.js",
|
|
812
|
+
training,
|
|
813
|
+
params: config.params?.stroke || config.params || null
|
|
814
|
+
});
|
|
815
|
+
this.charList = this.stroke.charList;
|
|
816
|
+
this.ready = this.stroke.readyPromise;
|
|
817
|
+
}
|
|
818
|
+
use(plugin) {
|
|
819
|
+
this.stroke.plugins.push(plugin);
|
|
820
|
+
return this;
|
|
821
|
+
}
|
|
822
|
+
/** Recognize drawn strokes ([[{x,y},...], ...] or one polyline) → [{char, prob} x3] | null. */
|
|
823
|
+
async recognize(strokes) {
|
|
824
|
+
return toPairs(await this.stroke.recognize(strokes));
|
|
825
|
+
}
|
|
826
|
+
/** Raw per-template costs → {classes, costs}. */
|
|
827
|
+
rawScores(strokes) {
|
|
828
|
+
return this.stroke.rawScores(strokes);
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Mount a drawing pad in `el`; fires 'millirec:result' ({results, strokes})
|
|
832
|
+
* after each stroke, and 'millirec:clear' ({reason, undo}) when the pad
|
|
833
|
+
* drops its own ink.
|
|
834
|
+
*
|
|
835
|
+
* The pad reads ONE character, so by default writing in it after a pause
|
|
836
|
+
* starts a fresh one (`idleOverwrite`, seconds — 0 turns it off) and
|
|
837
|
+
* scribbling over it throws it away (`scribbleClear`). Both are measured:
|
|
838
|
+
* see widget/canvas.js and scripts/verify-scribble.mjs.
|
|
839
|
+
*/
|
|
840
|
+
attach(el, { width = 240, height = 240, ink = "#1e293b", idleOverwrite = 2, scribbleClear = true, scribble = null, staleAlpha, onStale } = {}) {
|
|
841
|
+
const pad = createDrawCanvas({
|
|
842
|
+
width,
|
|
843
|
+
height,
|
|
844
|
+
ink,
|
|
845
|
+
idleOverwrite,
|
|
846
|
+
scribbleClear,
|
|
847
|
+
scribble,
|
|
848
|
+
onStale,
|
|
849
|
+
...staleAlpha === void 0 ? {} : { staleAlpha },
|
|
850
|
+
onClear: (reason) => el.dispatchEvent(new CustomEvent("millirec:clear", { detail: { reason, undo: () => pad.undoClear() } })),
|
|
851
|
+
onStrokeEnd: async (strokes) => {
|
|
852
|
+
if (!strokes.length) {
|
|
853
|
+
el.dispatchEvent(new CustomEvent("millirec:result", { detail: { results: [], strokes: [] } }));
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
const results = await this.recognize(strokes);
|
|
857
|
+
el.dispatchEvent(new CustomEvent("millirec:result", { detail: { results, strokes } }));
|
|
858
|
+
}
|
|
859
|
+
});
|
|
860
|
+
el.appendChild(pad.el);
|
|
861
|
+
return { clear: pad.clear, undoClear: pad.undoClear, isStale: pad.isStale, configure: pad.configure, setInk: pad.setInk, repaint: pad.repaint, getStrokes: pad.getStrokes, canvas: pad.el };
|
|
862
|
+
}
|
|
863
|
+
destroy() {
|
|
864
|
+
this.stroke.destroy();
|
|
865
|
+
}
|
|
866
|
+
};
|
|
867
|
+
if (typeof window !== "undefined" && false) {
|
|
868
|
+
window.MillirecCharLite = MillirecCharLite;
|
|
869
|
+
if (!window.MillirecChar) window.MillirecChar = MillirecCharLite;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// src/char-lite.js
|
|
873
|
+
var HERE = new URL("./", import.meta.url).href;
|
|
874
|
+
var SETS = ["all", "capitals", "digits", "lowercase", "punctuation"];
|
|
875
|
+
async function loadSet(name, { assetBase = HERE } = {}) {
|
|
876
|
+
if (!SETS.includes(name)) throw new Error(`millirec: no training set "${name}" (one of ${SETS.join(", ")})`);
|
|
877
|
+
const url = new URL(`sets/${name}.json`, assetBaseOf(assetBase));
|
|
878
|
+
const r = await fetch(url);
|
|
879
|
+
if (!r.ok) throw new Error(`millirec: ${url}: ${r.status}`);
|
|
880
|
+
return r.json();
|
|
881
|
+
}
|
|
882
|
+
var MillirecCharLite2 = class extends MillirecCharLite {
|
|
883
|
+
/** As the script-tag create(), but `training` is required (no window.MILLIREC_TRAINING)
|
|
884
|
+
* and the worker/wasm are found beside this module unless `assetBase` says otherwise. */
|
|
885
|
+
static create(opts = {}) {
|
|
886
|
+
if (!opts.training) throw new Error('MillirecCharLite.create: pass { training } \u2014 e.g. await loadSet("digits")');
|
|
887
|
+
return super.create({ assetBase: HERE, ...opts });
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
export {
|
|
891
|
+
MillirecCharLite2 as MillirecCharLite,
|
|
892
|
+
SETS,
|
|
893
|
+
loadSet
|
|
894
|
+
};
|