millirec 0.1.2 → 0.2.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/CHANGELOG.md +65 -0
- package/README.md +171 -58
- package/dist/char-cnn/cnn-web.wasm +0 -0
- package/dist/char-cnn/core.d.ts +3 -1
- package/dist/char-cnn/core.js +145 -99
- package/dist/char-cnn/index.d.ts +1 -1
- package/dist/char-cnn/index.js +198 -136
- package/dist/char-cnn/millirec-char-cnn-core.min.js +1 -1
- package/dist/char-cnn/millirec-char-cnn.min.js +1 -1
- package/dist/char-cnn/options/accurate/tiny.head.bin +0 -0
- package/dist/char-cnn/options/accurate.js +2 -2
- package/dist/char-cnn/options/accurate.json +1 -1
- package/dist/char-cnn/options/all/all-base.head.bin +0 -0
- package/dist/char-cnn/options/all/all-base.q4.bin +0 -0
- package/dist/char-cnn/options/all/all-tiny.bin +0 -0
- package/dist/char-cnn/options/all/all-tiny.head.bin +0 -0
- package/dist/char-cnn/options/all-fast/all-base-p25.bin +0 -0
- package/dist/char-cnn/options/all-fast/all-base-p25.head.bin +0 -0
- package/dist/char-cnn/options/all-fast/all-tiny.bin +0 -0
- package/dist/char-cnn/options/all-fast/all-tiny.head.bin +0 -0
- package/dist/char-cnn/options/all-fast.js +17 -0
- package/dist/char-cnn/options/all-fast.json +15 -0
- package/dist/char-cnn/options/all-small/all-tiny-qat4.head.bin +0 -0
- package/dist/char-cnn/options/all-small/all-tiny-qat4.q4.bin +0 -0
- package/dist/char-cnn/options/all-small.js +11 -0
- package/dist/char-cnn/options/all-small.json +9 -0
- package/dist/char-cnn/options/all.js +17 -0
- package/dist/char-cnn/options/all.json +15 -0
- package/dist/char-cnn/options/digits/digits-base.head.bin +0 -0
- package/dist/char-cnn/options/digits/digits-tiny.head.bin +0 -0
- package/dist/char-cnn/options/digits-fast/digits-base-p25.bin +0 -0
- package/dist/char-cnn/options/digits-fast/digits-base-p25.head.bin +0 -0
- package/dist/char-cnn/options/digits-fast/digits-tiny.bin +0 -0
- package/dist/char-cnn/options/digits-fast/digits-tiny.head.bin +0 -0
- package/dist/char-cnn/options/digits-fast.js +17 -0
- package/dist/char-cnn/options/digits-fast.json +15 -0
- package/dist/char-cnn/options/digits-small/digits-tiny-qat4.head.bin +0 -0
- package/dist/char-cnn/options/digits-small/digits-tiny-qat4.q4.bin +0 -0
- package/dist/char-cnn/options/digits-small.js +11 -0
- package/dist/char-cnn/options/digits-small.json +9 -0
- package/dist/char-cnn/options/digits.js +2 -2
- package/dist/char-cnn/options/digits.json +1 -1
- package/dist/char-cnn/options/fast/base-p25.head.bin +0 -0
- package/dist/char-cnn/options/fast/tiny.head.bin +0 -0
- package/dist/char-cnn/options/fast.js +2 -2
- package/dist/char-cnn/options/fast.json +1 -1
- package/dist/char-cnn/options/lowercase/lowercase-tiny.head.bin +0 -0
- package/dist/char-cnn/options/lowercase-fast/lowercase-base-p25.bin +0 -0
- package/dist/char-cnn/options/lowercase-fast/lowercase-base-p25.head.bin +0 -0
- package/dist/char-cnn/options/lowercase-fast/lowercase-tiny.bin +0 -0
- package/dist/char-cnn/options/lowercase-fast/lowercase-tiny.head.bin +0 -0
- package/dist/char-cnn/options/lowercase-fast.js +17 -0
- package/dist/char-cnn/options/lowercase-fast.json +15 -0
- package/dist/char-cnn/options/lowercase-small/lowercase-tiny-qat4.head.bin +0 -0
- package/dist/char-cnn/options/lowercase-small/lowercase-tiny-qat4.q4.bin +0 -0
- package/dist/char-cnn/options/lowercase-small.js +11 -0
- package/dist/char-cnn/options/lowercase-small.json +9 -0
- package/dist/char-cnn/options/lowercase.js +2 -2
- package/dist/char-cnn/options/lowercase.json +1 -1
- package/dist/char-cnn/options/small/tiny.head.bin +0 -0
- package/dist/char-cnn/options/small/tiny.q4.bin +0 -0
- package/dist/char-cnn/options/small.js +2 -2
- package/dist/char-cnn/options/small.json +1 -1
- package/dist/char-lite/core.d.ts +1 -0
- package/dist/char-lite/core.js +628 -0
- package/dist/char-lite/index.d.ts +28 -8
- package/dist/char-lite/index.js +845 -717
- package/dist/char-lite/millirec-char-lite.min.js +1 -1
- package/dist/char-lite/sets.json +17 -17
- package/dist/index.d.ts +35 -0
- package/dist/index.js +88 -0
- package/dist/overlap/millirec-overlap.min.js +7 -7
- package/dist/pad/index.d.ts +8 -0
- package/dist/pad/index.js +482 -0
- package/package.json +21 -7
- package/dist/char-cnn/options/small/tiny.bin +0 -0
package/dist/char-lite/index.js
CHANGED
|
@@ -114,7 +114,8 @@ function orientedPointsFromPolyline(polyline) {
|
|
|
114
114
|
function resampleStrokes(strokes, n = POINTS_PER_SHAPE) {
|
|
115
115
|
const segs = [];
|
|
116
116
|
let cum = 0;
|
|
117
|
-
for (const
|
|
117
|
+
for (const raw of strokes) {
|
|
118
|
+
const stroke = raw.length === 1 ? [{ x: raw[0].x - 0.5, y: raw[0].y }, { x: raw[0].x + 0.5, y: raw[0].y }] : raw;
|
|
118
119
|
for (let i = 1; i < stroke.length; i++) {
|
|
119
120
|
const dx = stroke[i].x - stroke[i - 1].x;
|
|
120
121
|
const dy = stroke[i].y - stroke[i - 1].y;
|
|
@@ -190,770 +191,892 @@ function samplesMap(data) {
|
|
|
190
191
|
return out;
|
|
191
192
|
}
|
|
192
193
|
|
|
193
|
-
// ../../
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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 };
|
|
194
|
+
// ../../library/src/assetbase.js
|
|
195
|
+
function assetBaseOf(base) {
|
|
196
|
+
let s = base ? String(base) : "";
|
|
197
|
+
if (!s) return typeof location !== "undefined" ? new URL("./", location.href).href : "";
|
|
198
|
+
if (!s.endsWith("/")) s += "/";
|
|
199
|
+
return typeof location !== "undefined" ? new URL(s, location.href).href : s;
|
|
224
200
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
if (
|
|
201
|
+
var notServed = (url2, what, base, recognizer) => new Error(`millirec: ${url2} is not ${what} \u2014 the package files are not served at ${base}; copy node_modules/millirec/dist/${recognizer}/ and pass assetBase (see README "Serving the files")`);
|
|
202
|
+
async function fetchAsset(url2, { as = "json", what, base, recognizer }) {
|
|
203
|
+
const fail = (detail) => {
|
|
204
|
+
const e = notServed(url2, what, base, recognizer);
|
|
205
|
+
if (detail) e.message += ` (${detail})`;
|
|
206
|
+
return e;
|
|
207
|
+
};
|
|
208
|
+
let r;
|
|
209
|
+
try {
|
|
210
|
+
r = await fetch(url2);
|
|
211
|
+
} catch (e) {
|
|
212
|
+
throw fail(e && e.message);
|
|
230
213
|
}
|
|
231
|
-
const
|
|
232
|
-
if (!(
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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;
|
|
214
|
+
const type = r.headers && r.headers.get("content-type") || "";
|
|
215
|
+
if (!r.ok) throw fail(`HTTP ${r.status}`);
|
|
216
|
+
if (as === "json") {
|
|
217
|
+
try {
|
|
218
|
+
return await r.json();
|
|
219
|
+
} catch (e) {
|
|
220
|
+
throw fail(/html/i.test(type) ? "an HTML page" : e && e.message);
|
|
255
221
|
}
|
|
256
222
|
}
|
|
257
|
-
|
|
223
|
+
const buf = await r.arrayBuffer();
|
|
224
|
+
const head = String.fromCharCode(...new Uint8Array(buf, 0, Math.min(buf.byteLength, 16))).trimStart().toLowerCase();
|
|
225
|
+
if (head.startsWith("<!doctype") || head.startsWith("<html")) throw fail("an HTML page");
|
|
226
|
+
return buf;
|
|
258
227
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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 };
|
|
228
|
+
|
|
229
|
+
// ../../library/src/char-lite-core.js
|
|
230
|
+
function scriptBase() {
|
|
231
|
+
const src = typeof document !== "undefined" && document.currentScript && document.currentScript.src || "";
|
|
232
|
+
return src ? src.slice(0, src.lastIndexOf("/") + 1) : "";
|
|
283
233
|
}
|
|
284
|
-
var
|
|
285
|
-
var
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
234
|
+
var ASSET_BASE = scriptBase();
|
|
235
|
+
var CACHE_MAX = 256;
|
|
236
|
+
var StrokeWorker = class {
|
|
237
|
+
constructor({ assetBase, workerName, training, params }) {
|
|
238
|
+
assetBase = assetBaseOf(assetBase);
|
|
239
|
+
const decoded = decode(training);
|
|
240
|
+
this.trainPaths = samplesMap(decoded);
|
|
241
|
+
this.charList = Object.keys(this.trainPaths);
|
|
242
|
+
this.samplesPerChar = Math.max(1, ...this.charList.map((c) => this.trainPaths[c].length));
|
|
243
|
+
this.pointsPerShape = decoded.pointsPerShape || POINTS_PER_SHAPE;
|
|
244
|
+
this.params = params || decoded.params || null;
|
|
245
|
+
this.plugins = [];
|
|
246
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
247
|
+
this.inFlight = /* @__PURE__ */ new Map();
|
|
248
|
+
this.allWaiters = /* @__PURE__ */ new Map();
|
|
249
|
+
this.reqCounter = 0;
|
|
250
|
+
const boot = `self.__MILLIREC_ASSET_BASE=${JSON.stringify(assetBase)};importScripts(${JSON.stringify(assetBase + workerName)});`;
|
|
251
|
+
this.bootUrl = URL.createObjectURL(new Blob([boot], { type: "text/javascript" }));
|
|
252
|
+
this.worker = new Worker(this.bootUrl);
|
|
253
|
+
this.readyPromise = new Promise((resolve, reject) => {
|
|
254
|
+
this.readyResolve = resolve;
|
|
255
|
+
this.readyReject = reject;
|
|
256
|
+
});
|
|
257
|
+
this.worker.onmessage = (evt) => this.onMessage(evt);
|
|
258
|
+
const workerUrl = assetBase + workerName;
|
|
259
|
+
this.worker.onerror = (evt) => {
|
|
260
|
+
if (this.booted) {
|
|
261
|
+
this.flush();
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const e = notServed(workerUrl, "the char-lite worker", assetBase, "char-lite");
|
|
265
|
+
e.message += ` (${evt.message || "script failed to load"})`;
|
|
266
|
+
this.failBoot(e);
|
|
267
|
+
};
|
|
268
|
+
this.assetBase = assetBase;
|
|
269
|
+
}
|
|
270
|
+
onMessage(evt) {
|
|
271
|
+
const d = evt.data;
|
|
272
|
+
if (this.bootUrl) {
|
|
273
|
+
URL.revokeObjectURL(this.bootUrl);
|
|
274
|
+
this.bootUrl = null;
|
|
275
|
+
}
|
|
276
|
+
if (d.type === "getCharList") {
|
|
277
|
+
if (this.params) this.worker.postMessage({ type: "setParams", params: this.params });
|
|
278
|
+
this.worker.postMessage({ type: "charList", charList: this.charList, pointsPerShape: this.pointsPerShape, samplesPerChar: this.samplesPerChar });
|
|
279
|
+
} else if (d.type === "prepAll") {
|
|
280
|
+
this.charList.forEach((c, idx) => {
|
|
281
|
+
this.trainPaths[c].forEach((sample, i) => {
|
|
282
|
+
const { points, scale } = orientedPointsFromPolyline(decodeSample(sample));
|
|
283
|
+
this.worker.postMessage({ type: "addPoints", points, m: idx * this.samplesPerChar + i, scale });
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
this.booted = true;
|
|
287
|
+
this.readyResolve();
|
|
288
|
+
} else if (d.type === "addResult" && d.result) {
|
|
289
|
+
this.cache.delete(d.path);
|
|
290
|
+
this.cache.set(d.path, d.result);
|
|
291
|
+
if (this.cache.size > CACHE_MAX) this.cache.delete(this.cache.keys().next().value);
|
|
292
|
+
const waiters = this.inFlight.get(d.path) || [];
|
|
293
|
+
this.inFlight.delete(d.path);
|
|
294
|
+
for (const resolve of waiters) resolve(this.applyPlugins(d.result, d.path));
|
|
295
|
+
} else if (d.type === "allResult") {
|
|
296
|
+
const waiters = this.allWaiters.get(d.path) || [];
|
|
297
|
+
this.allWaiters.delete(d.path);
|
|
298
|
+
for (const resolve of waiters) resolve(d.costs);
|
|
299
|
+
} else if (d.type === "bootError") {
|
|
300
|
+
const e = notServed(this.assetBase + "millirec.wasm", "the char-lite matcher", this.assetBase, "char-lite");
|
|
301
|
+
e.message += ` (worker boot failed: ${d.message})`;
|
|
302
|
+
this.failBoot(e);
|
|
299
303
|
}
|
|
300
|
-
carry = (carry + d) % step;
|
|
301
304
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
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
|
-
}
|
|
305
|
+
/** Everyone waiting on the worker gets null, and nothing is left "in flight". */
|
|
306
|
+
flush() {
|
|
307
|
+
for (const map of [this.inFlight, this.allWaiters]) {
|
|
308
|
+
const lists = [...map.values()];
|
|
309
|
+
map.clear();
|
|
310
|
+
for (const list of lists) for (const done of list) done(null);
|
|
326
311
|
}
|
|
327
|
-
if (found) hit++;
|
|
328
312
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
if (
|
|
313
|
+
/** The worker never came up: create() rejects with `e`, and the worker and its boot URL are released. */
|
|
314
|
+
failBoot(e) {
|
|
315
|
+
this.readyReject(e);
|
|
316
|
+
this.destroyed = true;
|
|
317
|
+
try {
|
|
318
|
+
this.worker.terminate();
|
|
319
|
+
} catch {
|
|
320
|
+
}
|
|
321
|
+
if (this.bootUrl) {
|
|
322
|
+
URL.revokeObjectURL(this.bootUrl);
|
|
323
|
+
this.bootUrl = null;
|
|
324
|
+
}
|
|
338
325
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
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);
|
|
326
|
+
applyPlugins(raw, path) {
|
|
327
|
+
let out = parseResult(raw, this.charList, "stroke", SECOND_AVERAGE);
|
|
328
|
+
for (const p of this.plugins) if (p.rerank) out = p.rerank(out, { raw, path, charList: this.charList, mode: "stroke", recognizer: this }) || out;
|
|
329
|
+
return out;
|
|
452
330
|
}
|
|
453
|
-
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
331
|
+
uploadTest(input) {
|
|
332
|
+
const strokes = Array.isArray(input[0]) ? input : [input];
|
|
333
|
+
const polyline = resampleStrokes(strokes, this.pointsPerShape);
|
|
334
|
+
if (!polyline) return false;
|
|
335
|
+
const { points, scale } = orientedPointsFromPolyline(polyline);
|
|
336
|
+
this.worker.postMessage({ type: "addPoints", points, m: -1, scale });
|
|
458
337
|
return true;
|
|
459
338
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
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;
|
|
339
|
+
// The cache key of a drawing. It holds the STROKE BOUNDARIES (the same points split into two
|
|
340
|
+
// strokes resample differently — the pen-up jump is skipped) and hashes x and y separately at
|
|
341
|
+
// 1/1000 of a unit, so 0–1 coordinates do not collapse (the old (x*7919+y)|0 truncated them).
|
|
342
|
+
keyFor(input) {
|
|
343
|
+
const strokes = Array.isArray(input[0]) ? input : [input];
|
|
344
|
+
let h1 = 2166136261, h2 = 16777619, n = 0;
|
|
345
|
+
const mix = (v) => {
|
|
346
|
+
h1 = Math.imul(h1 ^ v, 16777619);
|
|
347
|
+
h2 = Math.imul(h2 ^ v, 2246822519);
|
|
348
|
+
};
|
|
349
|
+
for (const st of strokes) {
|
|
350
|
+
mix(2147483647 ^ st.length);
|
|
351
|
+
for (const p of st) {
|
|
352
|
+
mix(Math.round(p.x * 1e3) | 0);
|
|
353
|
+
mix(Math.round(p.y * 1e3) | 0);
|
|
354
|
+
n++;
|
|
560
355
|
}
|
|
561
|
-
st.id = nextId++;
|
|
562
|
-
strokes = [...strokes, st];
|
|
563
|
-
current = [];
|
|
564
|
-
droppedPending = false;
|
|
565
|
-
lastEndAt = now();
|
|
566
|
-
armStale();
|
|
567
|
-
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
568
356
|
}
|
|
569
|
-
|
|
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
|
-
var notServed = (url2, what, base, recognizer) => new Error(`millirec: ${url2} is not ${what} \u2014 the package files are not served at ${base}; copy node_modules/millirec/dist/${recognizer}/ and pass assetBase (see README "Serving the files")`);
|
|
636
|
-
async function fetchAsset(url2, { as = "json", what, base, recognizer }) {
|
|
637
|
-
const fail = (detail) => {
|
|
638
|
-
const e = notServed(url2, what, base, recognizer);
|
|
639
|
-
if (detail) e.message += ` (${detail})`;
|
|
640
|
-
return e;
|
|
641
|
-
};
|
|
642
|
-
let r;
|
|
643
|
-
try {
|
|
644
|
-
r = await fetch(url2);
|
|
645
|
-
} catch (e) {
|
|
646
|
-
throw fail(e && e.message);
|
|
357
|
+
return "strokes:" + strokes.length + ":" + n + ":" + (h1 >>> 0).toString(36) + (h2 >>> 0).toString(36);
|
|
647
358
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
359
|
+
async recognize(strokes) {
|
|
360
|
+
if (this.destroyed || !strokes || !strokes.length) return null;
|
|
361
|
+
await this.readyPromise;
|
|
362
|
+
if (this.destroyed) return null;
|
|
363
|
+
const key = this.keyFor(strokes);
|
|
364
|
+
if (this.cache.has(key)) {
|
|
365
|
+
const hit = this.cache.get(key);
|
|
366
|
+
this.cache.delete(key);
|
|
367
|
+
this.cache.set(key, hit);
|
|
368
|
+
return this.applyPlugins(hit, key);
|
|
655
369
|
}
|
|
370
|
+
if (!this.uploadTest(strokes)) return null;
|
|
371
|
+
return new Promise((resolve) => {
|
|
372
|
+
let timer;
|
|
373
|
+
const done = (v) => {
|
|
374
|
+
clearTimeout(timer);
|
|
375
|
+
resolve(v);
|
|
376
|
+
};
|
|
377
|
+
if (this.inFlight.has(key)) this.inFlight.get(key).push(done);
|
|
378
|
+
else {
|
|
379
|
+
this.inFlight.set(key, [done]);
|
|
380
|
+
this.worker.postMessage({ type: "compare", path: key, elementID: "req" + ++this.reqCounter });
|
|
381
|
+
}
|
|
382
|
+
timer = setTimeout(() => {
|
|
383
|
+
const waiting = this.inFlight.get(key);
|
|
384
|
+
if (waiting) {
|
|
385
|
+
const i = waiting.indexOf(done);
|
|
386
|
+
if (i >= 0) waiting.splice(i, 1);
|
|
387
|
+
if (!waiting.length) this.inFlight.delete(key);
|
|
388
|
+
}
|
|
389
|
+
done(null);
|
|
390
|
+
}, 4e3);
|
|
391
|
+
});
|
|
656
392
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
this.charList = Object.keys(this.trainPaths);
|
|
676
|
-
this.samplesPerChar = Math.max(1, ...this.charList.map((c) => this.trainPaths[c].length));
|
|
677
|
-
this.pointsPerShape = decoded.pointsPerShape || POINTS_PER_SHAPE;
|
|
678
|
-
this.params = params || decoded.params || null;
|
|
679
|
-
this.plugins = [];
|
|
680
|
-
this.cache = /* @__PURE__ */ new Map();
|
|
681
|
-
this.inFlight = /* @__PURE__ */ new Map();
|
|
682
|
-
this.allWaiters = /* @__PURE__ */ new Map();
|
|
683
|
-
this.reqCounter = 0;
|
|
684
|
-
const boot = `self.__MILLIREC_ASSET_BASE=${JSON.stringify(assetBase)};importScripts(${JSON.stringify(assetBase + workerName)});`;
|
|
685
|
-
this.bootUrl = URL.createObjectURL(new Blob([boot], { type: "text/javascript" }));
|
|
686
|
-
this.worker = new Worker(this.bootUrl);
|
|
687
|
-
this.readyPromise = new Promise((resolve, reject) => {
|
|
688
|
-
this.readyResolve = resolve;
|
|
689
|
-
this.readyReject = reject;
|
|
393
|
+
async rawScores(strokes) {
|
|
394
|
+
if (this.destroyed || !strokes || !strokes.length) return null;
|
|
395
|
+
await this.readyPromise;
|
|
396
|
+
if (this.destroyed) return null;
|
|
397
|
+
if (!this.uploadTest(strokes)) return null;
|
|
398
|
+
const key = "all:" + ++this.reqCounter;
|
|
399
|
+
const costs = await new Promise((resolve) => {
|
|
400
|
+
let timer;
|
|
401
|
+
const done = (v) => {
|
|
402
|
+
clearTimeout(timer);
|
|
403
|
+
resolve(v);
|
|
404
|
+
};
|
|
405
|
+
this.allWaiters.set(key, [done]);
|
|
406
|
+
this.worker.postMessage({ type: "compareAll", path: key, counts: this.charList.map((c) => this.trainPaths[c].length) });
|
|
407
|
+
timer = setTimeout(() => {
|
|
408
|
+
this.allWaiters.delete(key);
|
|
409
|
+
done(null);
|
|
410
|
+
}, 8e3);
|
|
690
411
|
});
|
|
691
|
-
this.
|
|
692
|
-
const workerUrl = assetBase + workerName;
|
|
693
|
-
this.worker.onerror = (evt) => {
|
|
694
|
-
if (this.booted) {
|
|
695
|
-
this.flush();
|
|
696
|
-
return;
|
|
697
|
-
}
|
|
698
|
-
const e = notServed(workerUrl, "the char-lite worker", assetBase, "char-lite");
|
|
699
|
-
e.message += ` (${evt.message || "script failed to load"})`;
|
|
700
|
-
this.failBoot(e);
|
|
701
|
-
};
|
|
702
|
-
this.assetBase = assetBase;
|
|
412
|
+
return costs ? { classes: this.charList, costs } : null;
|
|
703
413
|
}
|
|
704
|
-
|
|
705
|
-
|
|
414
|
+
/** Stop the worker; anything still waiting gets null, and so does every later call. */
|
|
415
|
+
destroy() {
|
|
416
|
+
if (this.destroyed) return;
|
|
417
|
+
this.destroyed = true;
|
|
418
|
+
this.worker.terminate();
|
|
706
419
|
if (this.bootUrl) {
|
|
707
420
|
URL.revokeObjectURL(this.bootUrl);
|
|
708
421
|
this.bootUrl = null;
|
|
709
422
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
} else if (d.type === "addResult" && d.result) {
|
|
723
|
-
this.cache.delete(d.path);
|
|
724
|
-
this.cache.set(d.path, d.result);
|
|
725
|
-
if (this.cache.size > CACHE_MAX) this.cache.delete(this.cache.keys().next().value);
|
|
726
|
-
const waiters = this.inFlight.get(d.path) || [];
|
|
727
|
-
this.inFlight.delete(d.path);
|
|
728
|
-
for (const resolve of waiters) resolve(this.applyPlugins(d.result, d.path));
|
|
729
|
-
} else if (d.type === "allResult") {
|
|
730
|
-
const waiters = this.allWaiters.get(d.path) || [];
|
|
731
|
-
this.allWaiters.delete(d.path);
|
|
732
|
-
for (const resolve of waiters) resolve(d.costs);
|
|
733
|
-
} else if (d.type === "bootError") {
|
|
734
|
-
const e = notServed(this.assetBase + "millirec.wasm", "the char-lite matcher", this.assetBase, "char-lite");
|
|
735
|
-
e.message += ` (worker boot failed: ${d.message})`;
|
|
736
|
-
this.failBoot(e);
|
|
423
|
+
this.flush();
|
|
424
|
+
this.cache.clear();
|
|
425
|
+
this.readyResolve();
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
var toPairs = (parsed) => {
|
|
429
|
+
if (!parsed) return null;
|
|
430
|
+
const seen = /* @__PURE__ */ new Set(), out = [];
|
|
431
|
+
parsed.chars.forEach((c, i) => {
|
|
432
|
+
if (c !== void 0 && !seen.has(c)) {
|
|
433
|
+
seen.add(c);
|
|
434
|
+
out.push({ char: c, prob: parsed.probs[i] });
|
|
737
435
|
}
|
|
436
|
+
});
|
|
437
|
+
return out;
|
|
438
|
+
};
|
|
439
|
+
var classScore = (costs) => {
|
|
440
|
+
let b = Infinity, b2 = Infinity;
|
|
441
|
+
for (const c of costs || []) {
|
|
442
|
+
if (c < b) {
|
|
443
|
+
b2 = b;
|
|
444
|
+
b = c;
|
|
445
|
+
} else if (c < b2) b2 = c;
|
|
738
446
|
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
447
|
+
return b === Infinity ? Infinity : b2 === Infinity ? 0.9 * b * b * b : b * b * b2;
|
|
448
|
+
};
|
|
449
|
+
function withSamplesOf(training, extra, { replace = false } = {}) {
|
|
450
|
+
const empty = training && training.classes && !Object.keys(training.classes).length;
|
|
451
|
+
const base = empty ? { version: 2, mode: "stroke", ext: {}, ...training, pointsPerShape: training.pointsPerShape || POINTS_PER_SHAPE, classes: {} } : decode({ ...training });
|
|
452
|
+
const n = base.pointsPerShape;
|
|
453
|
+
const toSample = (d) => {
|
|
454
|
+
const strokes = Array.isArray(d) ? Array.isArray(d[0]) ? d : [d] : [decodeSample(d)];
|
|
455
|
+
const polyline = resampleStrokes(strokes, n);
|
|
456
|
+
return polyline ? polylineToSample(polyline) : null;
|
|
457
|
+
};
|
|
458
|
+
const classes = { ...base.classes };
|
|
459
|
+
for (const [cls, drawings] of Object.entries(extra || {})) {
|
|
460
|
+
const own = (drawings || []).map(toSample).filter(Boolean);
|
|
461
|
+
if (!own.length) continue;
|
|
462
|
+
const shipped = classes[cls]?.samples || [];
|
|
463
|
+
classes[cls] = { ...classes[cls] || {}, samples: replace ? own : shipped.concat(own) };
|
|
464
|
+
}
|
|
465
|
+
return { ...base, classes };
|
|
466
|
+
}
|
|
467
|
+
var MillirecCharLiteCore = class {
|
|
468
|
+
/** Drawn strokes → one training sample (resampled points, delta-encoded).
|
|
469
|
+
* Pass the set's pointsPerShape to match it (the shipped sets are 25). */
|
|
470
|
+
static strokesToSample(strokes, pointsPerShape = POINTS_PER_SHAPE) {
|
|
471
|
+
const polyline = resampleStrokes(Array.isArray(strokes[0]) ? strokes : [strokes], pointsPerShape);
|
|
472
|
+
return polyline ? polylineToSample(polyline) : null;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* A copy of `training` with your own samples added — the way to make a
|
|
476
|
+
* recognizer learn one person's hand. `extra` maps a class (any string: a
|
|
477
|
+
* letter, a digit, an emoji) to drawings: strokes ([[{x,y},...], ...]) or
|
|
478
|
+
* already-encoded samples ({x:[Δ...], y:[Δ...]}). Each is resampled to the
|
|
479
|
+
* set's pointsPerShape. Classes not in `training` are added. `replace: true`
|
|
480
|
+
* drops a class's shipped samples instead of appending to them. `training`
|
|
481
|
+
* is not modified.
|
|
482
|
+
*/
|
|
483
|
+
static withSamples(training, extra, opts) {
|
|
484
|
+
return withSamplesOf(training, extra, opts);
|
|
485
|
+
}
|
|
486
|
+
/** opts: training (default window.MILLIREC_TRAINING), assetBase (default:
|
|
487
|
+
* alongside this script), params (matcher overrides), workerStroke. */
|
|
488
|
+
static async create(opts = {}) {
|
|
489
|
+
const g = typeof window !== "undefined" ? window : globalThis;
|
|
490
|
+
const config = { ...g.MILLIREC_CONFIG || {}, ...opts };
|
|
491
|
+
const training = opts.training || g.MILLIREC_TRAINING;
|
|
492
|
+
if (!training) throw new Error("MillirecCharLite: no training data (training.js missing?)");
|
|
493
|
+
if (typeof Worker === "undefined" || typeof Blob === "undefined") {
|
|
494
|
+
throw new Error("millirec: char-lite needs a browser (Worker, fetch, canvas); importing is SSR-safe but call create() on the client");
|
|
745
495
|
}
|
|
496
|
+
const inst = new this(config, training);
|
|
497
|
+
await inst.ready;
|
|
498
|
+
return inst;
|
|
746
499
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
this.
|
|
750
|
-
this.
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
500
|
+
constructor(config, training) {
|
|
501
|
+
this.config = config;
|
|
502
|
+
this.plugins = [];
|
|
503
|
+
this.shipped = this.stroke = this.newWorker(training);
|
|
504
|
+
this.ready = this.stroke.readyPromise;
|
|
505
|
+
}
|
|
506
|
+
newWorker(training) {
|
|
507
|
+
const w = new StrokeWorker({
|
|
508
|
+
assetBase: this.config.assetBase || ASSET_BASE,
|
|
509
|
+
workerName: this.config.workerStroke || "worker-stroke.js",
|
|
510
|
+
training,
|
|
511
|
+
params: this.config.params?.stroke || this.config.params || null
|
|
512
|
+
});
|
|
513
|
+
w.plugins = this.plugins;
|
|
514
|
+
return w;
|
|
515
|
+
}
|
|
516
|
+
/** Which engine this is (createRecognizer() picks one). */
|
|
517
|
+
get engine() {
|
|
518
|
+
return "char-lite";
|
|
519
|
+
}
|
|
520
|
+
/** The training set's classes (as char-cnn's `classes`: teach() does not change them; it returns the taught names). */
|
|
521
|
+
get classes() {
|
|
522
|
+
return this.shipped.charList;
|
|
523
|
+
}
|
|
524
|
+
get charList() {
|
|
525
|
+
return this.shipped.charList;
|
|
526
|
+
}
|
|
527
|
+
use(plugin) {
|
|
528
|
+
this.plugins.push(plugin);
|
|
529
|
+
return this;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Recognize drawn strokes ([[{x,y},...], ...] or one polyline) → [{char, prob} x3] | null.
|
|
533
|
+
* `only` (a string, array or Set of classes) answers among those alone, the probabilities taken
|
|
534
|
+
* over them — a box that can only hold a digit gets the likeliest digit. It scores every template
|
|
535
|
+
* exactly (rawScores), so it is slower than a plain recognize(), whose scan gives up early on templates
|
|
536
|
+
* that cannot win: the first answer is the same, the runner-ups and their probabilities can differ.
|
|
537
|
+
* Plugins' rerank does not run on it.
|
|
538
|
+
*/
|
|
539
|
+
async recognize(strokes, { only = null } = {}) {
|
|
540
|
+
if (!only) return toPairs(await this.stroke.recognize(strokes));
|
|
541
|
+
const keep = new Set(typeof only === "string" ? [...only] : only);
|
|
542
|
+
const raw = await this.stroke.rawScores(strokes);
|
|
543
|
+
if (!raw) return null;
|
|
544
|
+
const ranked = raw.classes.map((c, i) => ({ i, c, v: classScore(raw.costs[i]) })).filter((x) => keep.has(x.c) && x.v < Infinity).sort((a, b) => a.v - b.v).slice(0, 3);
|
|
545
|
+
if (!ranked.length) return [];
|
|
546
|
+
while (ranked.length < 3) ranked.push({ ...ranked[0], v: 1e30 });
|
|
547
|
+
return toPairs(parseResult(ranked.flatMap((x) => [x.i, x.v]), raw.classes, "stroke", SECOND_AVERAGE));
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* TEACH: read symbols of your own from a few drawings of each. `examples` is `{ name: [drawing, …] }` — names are
|
|
551
|
+
* any strings, a drawing is strokes as for recognize(). From then on recognize() answers AMONG THE TAUGHT NAMES
|
|
552
|
+
* ONLY, matched against these drawings as templates; `{ add: true }` keeps what was taught before. The same call
|
|
553
|
+
* as char-cnn's teach(). To ADD symbols to a shipped set instead, build the training with withSamples().
|
|
554
|
+
* Starts a second worker for the taught set (the shipped one stays up, so forget() is instant). Resolves
|
|
555
|
+
* { classes, n }, or null when no drawing was usable.
|
|
556
|
+
*/
|
|
557
|
+
async teach(examples, { add = false } = {}) {
|
|
558
|
+
await this.ready;
|
|
559
|
+
if (this.destroyed) return null;
|
|
560
|
+
const base = add && this.taught ? this.taught : { version: 2, mode: "stroke", pointsPerShape: this.shipped.pointsPerShape, classes: {} };
|
|
561
|
+
const training = withSamplesOf(base, examples);
|
|
562
|
+
const n = Object.values(training.classes).reduce((a, c) => a + c.samples.length, 0);
|
|
563
|
+
if (!n) return null;
|
|
564
|
+
const w = this.newWorker(training);
|
|
565
|
+
await w.readyPromise;
|
|
566
|
+
if (this.destroyed) {
|
|
567
|
+
w.destroy();
|
|
568
|
+
return null;
|
|
754
569
|
}
|
|
755
|
-
if (this.
|
|
756
|
-
|
|
757
|
-
|
|
570
|
+
if (this.stroke !== this.shipped) this.stroke.destroy();
|
|
571
|
+
this.stroke = w;
|
|
572
|
+
this.taught = training;
|
|
573
|
+
return { classes: w.charList, n };
|
|
574
|
+
}
|
|
575
|
+
/** Drop what teach() learned: recognize() reads the training set's classes again. */
|
|
576
|
+
forget() {
|
|
577
|
+
if (this.stroke !== this.shipped) this.stroke.destroy();
|
|
578
|
+
this.stroke = this.shipped;
|
|
579
|
+
this.taught = null;
|
|
580
|
+
}
|
|
581
|
+
/** Raw per-template costs → {classes, costs}. */
|
|
582
|
+
rawScores(strokes) {
|
|
583
|
+
return this.stroke.rawScores(strokes);
|
|
584
|
+
}
|
|
585
|
+
destroy() {
|
|
586
|
+
this.destroyed = true;
|
|
587
|
+
if (this.stroke !== this.shipped) this.stroke.destroy();
|
|
588
|
+
this.shipped.destroy();
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
// ../../widget/scribble.js
|
|
593
|
+
var SCRIBBLE = {
|
|
594
|
+
turns: 5,
|
|
595
|
+
// reversals along the principal axis (no letter reaches 6; the scribble reaches 8)
|
|
596
|
+
retrace: 0.5,
|
|
597
|
+
// share of the path laid back over its own ground (letters <= 0.54 at ANY turn count)
|
|
598
|
+
winding: 3.5,
|
|
599
|
+
// path length / bbox diagonal (letters at 5 turns reach 3.29; the scribble 6.14)
|
|
600
|
+
cover: 0.6,
|
|
601
|
+
// how completely this stroke and the existing ink overlap, per axis
|
|
602
|
+
minLength: 40,
|
|
603
|
+
// px of path — a small wiggle is not a scribble
|
|
604
|
+
minSpan: 12,
|
|
605
|
+
// px of bbox diagonal — nor is a dense scrub of one point
|
|
606
|
+
deadband: 0.22
|
|
607
|
+
// a reversal must retrace this much of the axis's extent
|
|
608
|
+
};
|
|
609
|
+
var INK_HALF = 2;
|
|
610
|
+
function grow(b) {
|
|
611
|
+
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 };
|
|
612
|
+
}
|
|
613
|
+
function bbox(pts) {
|
|
614
|
+
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
|
615
|
+
for (const p of pts) {
|
|
616
|
+
const x = p.x !== void 0 ? p.x : p[0], y = p.y !== void 0 ? p.y : p[1];
|
|
617
|
+
if (x < x0) x0 = x;
|
|
618
|
+
if (x > x1) x1 = x;
|
|
619
|
+
if (y < y0) y0 = y;
|
|
620
|
+
if (y > y1) y1 = y;
|
|
621
|
+
}
|
|
622
|
+
return { x0, y0, x1, y1, w: x1 - x0, h: y1 - y0 };
|
|
623
|
+
}
|
|
624
|
+
function turnsAlong(vals, deadband) {
|
|
625
|
+
let lo = Infinity, hi = -Infinity;
|
|
626
|
+
for (const v of vals) {
|
|
627
|
+
if (v < lo) lo = v;
|
|
628
|
+
if (v > hi) hi = v;
|
|
629
|
+
}
|
|
630
|
+
const band = (hi - lo) * deadband;
|
|
631
|
+
if (!(band > 0)) return 0;
|
|
632
|
+
let dir = 0, ext = vals[0], turns = 0;
|
|
633
|
+
for (const v of vals) {
|
|
634
|
+
if (dir > 0) {
|
|
635
|
+
if (v > ext) ext = v;
|
|
636
|
+
else if (v < ext - band) {
|
|
637
|
+
turns++;
|
|
638
|
+
dir = -1;
|
|
639
|
+
ext = v;
|
|
640
|
+
}
|
|
641
|
+
} else if (dir < 0) {
|
|
642
|
+
if (v < ext) ext = v;
|
|
643
|
+
else if (v > ext + band) {
|
|
644
|
+
turns++;
|
|
645
|
+
dir = 1;
|
|
646
|
+
ext = v;
|
|
647
|
+
}
|
|
648
|
+
} else if (v > ext + band) {
|
|
649
|
+
dir = 1;
|
|
650
|
+
ext = v;
|
|
651
|
+
} else if (v < ext - band) {
|
|
652
|
+
dir = -1;
|
|
653
|
+
ext = v;
|
|
758
654
|
}
|
|
759
655
|
}
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
656
|
+
return turns;
|
|
657
|
+
}
|
|
658
|
+
function axes(pts) {
|
|
659
|
+
let mx = 0, my = 0;
|
|
660
|
+
for (const p of pts) {
|
|
661
|
+
mx += p.x;
|
|
662
|
+
my += p.y;
|
|
764
663
|
}
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
const
|
|
770
|
-
|
|
771
|
-
|
|
664
|
+
mx /= pts.length;
|
|
665
|
+
my /= pts.length;
|
|
666
|
+
let sxx = 0, sxy = 0, syy = 0;
|
|
667
|
+
for (const p of pts) {
|
|
668
|
+
const dx = p.x - mx, dy = p.y - my;
|
|
669
|
+
sxx += dx * dx;
|
|
670
|
+
sxy += dx * dy;
|
|
671
|
+
syy += dy * dy;
|
|
772
672
|
}
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
673
|
+
const tr = sxx + syy, det = sxx * syy - sxy * sxy;
|
|
674
|
+
const l = tr / 2 + Math.sqrt(Math.max(0, tr * tr / 4 - det));
|
|
675
|
+
let ux = sxy, uy = l - sxx;
|
|
676
|
+
if (Math.hypot(ux, uy) < 1e-9) {
|
|
677
|
+
ux = 1;
|
|
678
|
+
uy = 0;
|
|
778
679
|
}
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
680
|
+
const n = Math.hypot(ux, uy);
|
|
681
|
+
return { ux: ux / n, uy: uy / n };
|
|
682
|
+
}
|
|
683
|
+
var RETRACE_R = 0.09;
|
|
684
|
+
var RETRACE_SKIP = 4;
|
|
685
|
+
function retraceOf(pts, span) {
|
|
686
|
+
const r = Math.max(2, span * RETRACE_R);
|
|
687
|
+
const step = r / 2;
|
|
688
|
+
const rs = [pts[0]];
|
|
689
|
+
let carry = 0;
|
|
690
|
+
for (let i = 1; i < pts.length; i++) {
|
|
691
|
+
const dx = pts[i].x - pts[i - 1].x, dy = pts[i].y - pts[i - 1].y;
|
|
692
|
+
let d = Math.hypot(dx, dy);
|
|
693
|
+
if (!(d > 0)) continue;
|
|
694
|
+
let t = (step - carry) / d;
|
|
695
|
+
while (t <= 1) {
|
|
696
|
+
rs.push({ x: pts[i - 1].x + dx * t, y: pts[i - 1].y + dy * t });
|
|
697
|
+
t += step / d;
|
|
789
698
|
}
|
|
790
|
-
|
|
791
|
-
return new Promise((resolve) => {
|
|
792
|
-
let timer;
|
|
793
|
-
const done = (v) => {
|
|
794
|
-
clearTimeout(timer);
|
|
795
|
-
resolve(v);
|
|
796
|
-
};
|
|
797
|
-
if (this.inFlight.has(key)) this.inFlight.get(key).push(done);
|
|
798
|
-
else {
|
|
799
|
-
this.inFlight.set(key, [done]);
|
|
800
|
-
this.worker.postMessage({ type: "compare", path: key, elementID: "req" + ++this.reqCounter });
|
|
801
|
-
}
|
|
802
|
-
timer = setTimeout(() => {
|
|
803
|
-
const waiting = this.inFlight.get(key);
|
|
804
|
-
if (waiting) {
|
|
805
|
-
const i = waiting.indexOf(done);
|
|
806
|
-
if (i >= 0) waiting.splice(i, 1);
|
|
807
|
-
if (!waiting.length) this.inFlight.delete(key);
|
|
808
|
-
}
|
|
809
|
-
done(null);
|
|
810
|
-
}, 4e3);
|
|
811
|
-
});
|
|
812
|
-
}
|
|
813
|
-
async rawScores(strokes) {
|
|
814
|
-
if (this.destroyed) return null;
|
|
815
|
-
await this.readyPromise;
|
|
816
|
-
if (this.destroyed) return null;
|
|
817
|
-
if (!this.uploadTest(strokes)) return null;
|
|
818
|
-
const key = "all:" + ++this.reqCounter;
|
|
819
|
-
const costs = await new Promise((resolve) => {
|
|
820
|
-
let timer;
|
|
821
|
-
const done = (v) => {
|
|
822
|
-
clearTimeout(timer);
|
|
823
|
-
resolve(v);
|
|
824
|
-
};
|
|
825
|
-
this.allWaiters.set(key, [done]);
|
|
826
|
-
this.worker.postMessage({ type: "compareAll", path: key, counts: this.charList.map((c) => this.trainPaths[c].length) });
|
|
827
|
-
timer = setTimeout(() => {
|
|
828
|
-
this.allWaiters.delete(key);
|
|
829
|
-
done(null);
|
|
830
|
-
}, 8e3);
|
|
831
|
-
});
|
|
832
|
-
return costs ? { classes: this.charList, costs } : null;
|
|
699
|
+
carry = (carry + d) % step;
|
|
833
700
|
}
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
701
|
+
if (rs.length < 8) return 0;
|
|
702
|
+
const skip = Math.round(RETRACE_SKIP * r / step);
|
|
703
|
+
const key = (p) => `${Math.floor(p.x / r)},${Math.floor(p.y / r)}`;
|
|
704
|
+
const grid = /* @__PURE__ */ new Map();
|
|
705
|
+
rs.forEach((p, i) => {
|
|
706
|
+
const k = key(p);
|
|
707
|
+
if (!grid.has(k)) grid.set(k, []);
|
|
708
|
+
grid.get(k).push(i);
|
|
709
|
+
});
|
|
710
|
+
let hit = 0;
|
|
711
|
+
for (let i = 0; i < rs.length; i++) {
|
|
712
|
+
const p = rs[i];
|
|
713
|
+
const cx = Math.floor(p.x / r), cy = Math.floor(p.y / r);
|
|
714
|
+
let found = false;
|
|
715
|
+
for (let ax = -1; ax <= 1 && !found; ax++) {
|
|
716
|
+
for (let ay = -1; ay <= 1 && !found; ay++) {
|
|
717
|
+
for (const j of grid.get(`${cx + ax},${cy + ay}`) || []) {
|
|
718
|
+
if (Math.abs(i - j) <= skip) continue;
|
|
719
|
+
if (Math.hypot(rs[j].x - p.x, rs[j].y - p.y) <= r) {
|
|
720
|
+
found = true;
|
|
721
|
+
break;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
842
725
|
}
|
|
843
|
-
|
|
844
|
-
this.cache.clear();
|
|
845
|
-
this.readyResolve();
|
|
726
|
+
if (found) hit++;
|
|
846
727
|
}
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
const
|
|
854
|
-
|
|
728
|
+
return hit / rs.length;
|
|
729
|
+
}
|
|
730
|
+
function scribbleFeatures(stroke, prior = [], opts = {}) {
|
|
731
|
+
const k = { ...SCRIBBLE, ...opts };
|
|
732
|
+
const pts = [];
|
|
733
|
+
for (const p of stroke) {
|
|
734
|
+
const q = { x: p.x !== void 0 ? p.x : p[0], y: p.y !== void 0 ? p.y : p[1] };
|
|
735
|
+
const last = pts[pts.length - 1];
|
|
736
|
+
if (!last || Math.hypot(q.x - last.x, q.y - last.y) > 0.75) pts.push(q);
|
|
855
737
|
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
const
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
738
|
+
if (pts.length < 4) return { turns: 0, cross: 0, retrace: 0, winding: 0, cover: 0, length: 0, span: 0 };
|
|
739
|
+
let length = 0;
|
|
740
|
+
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);
|
|
741
|
+
const b = bbox(pts);
|
|
742
|
+
const span = Math.hypot(b.w, b.h);
|
|
743
|
+
const { ux, uy } = axes(pts);
|
|
744
|
+
const major = pts.map((p) => p.x * ux + p.y * uy);
|
|
745
|
+
const minor = pts.map((p) => -p.x * uy + p.y * ux);
|
|
746
|
+
const turns = turnsAlong(major, k.deadband);
|
|
747
|
+
const cross = turnsAlong(minor, k.deadband);
|
|
748
|
+
let cover = 0;
|
|
749
|
+
const flat = [];
|
|
750
|
+
for (const st of prior) for (const p of st) flat.push(p);
|
|
751
|
+
if (flat.length) {
|
|
752
|
+
const a = grow(bbox(flat));
|
|
753
|
+
const c = grow(b);
|
|
754
|
+
const ox = Math.max(0, Math.min(a.x1, c.x1) - Math.max(a.x0, c.x0));
|
|
755
|
+
const oy = Math.max(0, Math.min(a.y1, c.y1) - Math.max(a.y0, c.y0));
|
|
756
|
+
cover = ox / Math.min(a.w, c.w) * (oy / Math.min(a.h, c.h));
|
|
757
|
+
}
|
|
758
|
+
return { turns, cross, retrace: retraceOf(pts, span), winding: span > 0 ? length / span : 0, cover, length, span };
|
|
759
|
+
}
|
|
760
|
+
function isScribble(stroke, prior = [], opts = {}) {
|
|
761
|
+
const k = { ...SCRIBBLE, ...opts };
|
|
762
|
+
if (!prior || !prior.length) return false;
|
|
763
|
+
const f = scribbleFeatures(stroke, prior, k);
|
|
764
|
+
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;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// ../../widget/canvas.js
|
|
768
|
+
var ERASE_RADIUS = 12;
|
|
769
|
+
var now = () => typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
|
|
770
|
+
function createDrawCanvas({
|
|
771
|
+
width = 160,
|
|
772
|
+
height = 90,
|
|
773
|
+
ink = "#111827",
|
|
774
|
+
onStrokeEnd,
|
|
775
|
+
colorOf = null,
|
|
776
|
+
idleOverwrite = 0,
|
|
777
|
+
scribbleClear = false,
|
|
778
|
+
scribble = null,
|
|
779
|
+
onClear = null,
|
|
780
|
+
staleAlpha = 0.3,
|
|
781
|
+
onStale = null
|
|
782
|
+
}) {
|
|
783
|
+
const canvas = document.createElement("canvas");
|
|
784
|
+
const dpr = typeof devicePixelRatio !== "undefined" && devicePixelRatio || 1;
|
|
785
|
+
canvas.width = width * dpr;
|
|
786
|
+
canvas.height = height * dpr;
|
|
787
|
+
canvas.style.width = width + "px";
|
|
788
|
+
canvas.style.height = height + "px";
|
|
789
|
+
canvas.style.touchAction = "none";
|
|
790
|
+
const ctx = canvas.getContext("2d");
|
|
791
|
+
ctx.scale(dpr, dpr);
|
|
792
|
+
let strokes = [];
|
|
793
|
+
let current = [];
|
|
794
|
+
let activeId = null;
|
|
795
|
+
let erasing = false;
|
|
796
|
+
let nextId = 1;
|
|
797
|
+
let lastEndAt = 0;
|
|
798
|
+
let staleTimer = 0;
|
|
799
|
+
let stale = false;
|
|
800
|
+
let dropped = null;
|
|
801
|
+
let droppedPending = false;
|
|
802
|
+
function paint(st, color) {
|
|
803
|
+
if (st.length < 2) return;
|
|
804
|
+
ctx.strokeStyle = color || ink;
|
|
805
|
+
ctx.beginPath();
|
|
806
|
+
ctx.moveTo(st[0].x, st[0].y);
|
|
807
|
+
for (let i = 1; i < st.length; i++) ctx.lineTo(st[i].x, st[i].y);
|
|
808
|
+
ctx.stroke();
|
|
881
809
|
}
|
|
882
|
-
|
|
883
|
-
|
|
810
|
+
function paintFrom(st, from) {
|
|
811
|
+
if (st.length < 2 || from >= st.length - 1) return;
|
|
812
|
+
ctx.lineWidth = 2.5;
|
|
813
|
+
ctx.lineCap = "round";
|
|
814
|
+
ctx.lineJoin = "round";
|
|
815
|
+
ctx.globalAlpha = 1;
|
|
816
|
+
ctx.strokeStyle = ink;
|
|
817
|
+
ctx.beginPath();
|
|
818
|
+
ctx.moveTo(st[Math.max(0, from)].x, st[Math.max(0, from)].y);
|
|
819
|
+
for (let i = Math.max(1, from + 1); i < st.length; i++) ctx.lineTo(st[i].x, st[i].y);
|
|
820
|
+
ctx.stroke();
|
|
884
821
|
}
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
}
|
|
895
|
-
const inst = new this(config, training);
|
|
896
|
-
await inst.ready;
|
|
897
|
-
return inst;
|
|
822
|
+
function render() {
|
|
823
|
+
ctx.clearRect(0, 0, width, height);
|
|
824
|
+
ctx.lineWidth = 2.5;
|
|
825
|
+
ctx.lineCap = "round";
|
|
826
|
+
ctx.lineJoin = "round";
|
|
827
|
+
ctx.globalAlpha = stale ? staleAlpha : 1;
|
|
828
|
+
for (const st of strokes) paint(st, colorOf && colorOf(st));
|
|
829
|
+
ctx.globalAlpha = 1;
|
|
830
|
+
paint(current, null);
|
|
898
831
|
}
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
training,
|
|
905
|
-
params: config.params?.stroke || config.params || null
|
|
906
|
-
});
|
|
907
|
-
this.charList = this.stroke.charList;
|
|
908
|
-
this.ready = this.stroke.readyPromise;
|
|
832
|
+
function setStale(v) {
|
|
833
|
+
if (stale === v) return;
|
|
834
|
+
stale = v;
|
|
835
|
+
render();
|
|
836
|
+
if (onStale) onStale(v);
|
|
909
837
|
}
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
838
|
+
function armStale() {
|
|
839
|
+
clearTimeout(staleTimer);
|
|
840
|
+
staleTimer = 0;
|
|
841
|
+
const ms = (Number(idleOverwrite) || 0) * 1e3;
|
|
842
|
+
if (!ms || !strokes.length) {
|
|
843
|
+
setStale(false);
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
const left = ms - (now() - lastEndAt);
|
|
847
|
+
if (left <= 0) {
|
|
848
|
+
setStale(true);
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
setStale(false);
|
|
852
|
+
staleTimer = setTimeout(() => setStale(true), left);
|
|
913
853
|
}
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
854
|
+
function dropAll(reason) {
|
|
855
|
+
if (!strokes.length) return;
|
|
856
|
+
dropped = strokes;
|
|
857
|
+
strokes = [];
|
|
858
|
+
clearTimeout(staleTimer);
|
|
859
|
+
staleTimer = 0;
|
|
860
|
+
setStale(false);
|
|
861
|
+
render();
|
|
862
|
+
if (onClear) onClear(reason);
|
|
917
863
|
}
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
864
|
+
function eraseAt(x, y) {
|
|
865
|
+
const kept = strokes.filter((st) => !st.some((p) => Math.hypot(p.x - x, p.y - y) <= ERASE_RADIUS));
|
|
866
|
+
if (kept.length === strokes.length) return false;
|
|
867
|
+
strokes = kept;
|
|
868
|
+
render();
|
|
869
|
+
return true;
|
|
921
870
|
}
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
871
|
+
let rect = null;
|
|
872
|
+
const getPos = (e) => {
|
|
873
|
+
const r = rect || (rect = canvas.getBoundingClientRect());
|
|
874
|
+
const sx = width / (canvas.clientWidth || width), sy = height / (canvas.clientHeight || height);
|
|
875
|
+
return { x: (e.clientX - r.left - canvas.clientLeft) * sx, y: (e.clientY - r.top - canvas.clientTop) * sy, p: e.pressure || 0.5 };
|
|
876
|
+
};
|
|
877
|
+
let erasedAny = false;
|
|
878
|
+
let activeType = null;
|
|
879
|
+
const swallow = (e) => e.preventDefault();
|
|
880
|
+
canvas.addEventListener("touchstart", swallow, { passive: false });
|
|
881
|
+
canvas.addEventListener("touchmove", swallow, { passive: false });
|
|
882
|
+
canvas.addEventListener("contextmenu", swallow);
|
|
883
|
+
canvas.style.userSelect = canvas.style.webkitUserSelect = "none";
|
|
884
|
+
canvas.style.webkitTouchCallout = "none";
|
|
885
|
+
canvas.addEventListener("pointerdown", (e) => {
|
|
886
|
+
if (e.button > 0) return;
|
|
887
|
+
if (activeId !== null) {
|
|
888
|
+
if (activeType === "pen" && e.pointerType !== "pen" && e.pointerId !== activeId) return;
|
|
889
|
+
finish({ pointerId: activeId });
|
|
890
|
+
}
|
|
891
|
+
e.preventDefault();
|
|
892
|
+
activeId = e.pointerId;
|
|
893
|
+
activeType = e.pointerType;
|
|
894
|
+
rect = canvas.getBoundingClientRect();
|
|
895
|
+
try {
|
|
896
|
+
canvas.setPointerCapture(e.pointerId);
|
|
897
|
+
} catch {
|
|
898
|
+
}
|
|
899
|
+
const pos = getPos(e);
|
|
900
|
+
if (erasing) {
|
|
901
|
+
erasedAny = eraseAt(pos.x, pos.y);
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
if (stale && strokes.length) {
|
|
905
|
+
dropAll("idle");
|
|
906
|
+
droppedPending = true;
|
|
907
|
+
}
|
|
908
|
+
current = [pos];
|
|
909
|
+
render();
|
|
910
|
+
}, { passive: false });
|
|
911
|
+
canvas.addEventListener("pointermove", (e) => {
|
|
912
|
+
if (activeId !== e.pointerId) return;
|
|
913
|
+
e.preventDefault();
|
|
914
|
+
const co = e.getCoalescedEvents ? e.getCoalescedEvents() : null;
|
|
915
|
+
const events = co && co.length ? co : [e];
|
|
916
|
+
if (erasing) {
|
|
917
|
+
for (const ev of events) {
|
|
918
|
+
const p = getPos(ev);
|
|
919
|
+
if (eraseAt(p.x, p.y)) erasedAny = true;
|
|
920
|
+
}
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
const from = current.length - 1;
|
|
924
|
+
for (const ev of events) current.push(getPos(ev));
|
|
925
|
+
paintFrom(current, from);
|
|
926
|
+
}, { passive: false });
|
|
927
|
+
const finish = (e, cancelled = false) => {
|
|
928
|
+
if (activeId !== e.pointerId) return;
|
|
929
|
+
try {
|
|
930
|
+
canvas.releasePointerCapture(e.pointerId);
|
|
931
|
+
} catch {
|
|
932
|
+
}
|
|
933
|
+
activeId = null;
|
|
934
|
+
activeType = null;
|
|
935
|
+
rect = null;
|
|
936
|
+
if (erasing) {
|
|
937
|
+
if (erasedAny) {
|
|
938
|
+
lastEndAt = now();
|
|
939
|
+
armStale();
|
|
940
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
941
|
+
}
|
|
942
|
+
erasedAny = false;
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
if (current.length > 0) {
|
|
946
|
+
let st = current;
|
|
947
|
+
if (st.length === 1) {
|
|
948
|
+
if (cancelled) {
|
|
949
|
+
current = [];
|
|
950
|
+
render();
|
|
951
|
+
if (droppedPending) {
|
|
952
|
+
droppedPending = false;
|
|
953
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
954
|
+
}
|
|
946
955
|
return;
|
|
947
956
|
}
|
|
948
|
-
const
|
|
949
|
-
|
|
957
|
+
const p = st[0];
|
|
958
|
+
st = [{ x: p.x - 1, y: p.y, p: p.p }, { x: p.x + 1, y: p.y, p: p.p }];
|
|
959
|
+
}
|
|
960
|
+
const aimedAt = strokes.length ? strokes : droppedPending ? dropped : null;
|
|
961
|
+
if (scribbleClear && aimedAt && aimedAt.length && isScribble(st, aimedAt, scribble || {})) {
|
|
962
|
+
current = [];
|
|
963
|
+
lastEndAt = now();
|
|
964
|
+
droppedPending = false;
|
|
965
|
+
if (strokes.length) dropAll("scribble");
|
|
966
|
+
else {
|
|
967
|
+
render();
|
|
968
|
+
if (onClear) onClear("scribble");
|
|
969
|
+
}
|
|
970
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
971
|
+
return;
|
|
950
972
|
}
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
973
|
+
st.id = nextId++;
|
|
974
|
+
strokes = [...strokes, st];
|
|
975
|
+
current = [];
|
|
976
|
+
droppedPending = false;
|
|
977
|
+
lastEndAt = now();
|
|
978
|
+
armStale();
|
|
979
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
980
|
+
}
|
|
981
|
+
render();
|
|
982
|
+
};
|
|
983
|
+
canvas.addEventListener("pointerup", (e) => {
|
|
984
|
+
if (e.pointerId === activeId) e.preventDefault();
|
|
985
|
+
finish(e);
|
|
986
|
+
}, { passive: false });
|
|
987
|
+
canvas.addEventListener("pointercancel", (e) => finish(e, true), { passive: false });
|
|
988
|
+
canvas.addEventListener("lostpointercapture", (e) => {
|
|
989
|
+
if (!canvas.hasPointerCapture || !canvas.hasPointerCapture(e.pointerId)) finish(e, true);
|
|
990
|
+
});
|
|
991
|
+
return {
|
|
992
|
+
el: canvas,
|
|
993
|
+
getStrokes: () => strokes,
|
|
994
|
+
setInk(color) {
|
|
995
|
+
ink = color;
|
|
996
|
+
render();
|
|
997
|
+
},
|
|
998
|
+
setErasing(on) {
|
|
999
|
+
erasing = !!on;
|
|
1000
|
+
canvas.style.cursor = erasing ? "cell" : "crosshair";
|
|
1001
|
+
},
|
|
1002
|
+
isErasing: () => erasing,
|
|
1003
|
+
repaint: render,
|
|
1004
|
+
/** True once the idle window has passed: the next stroke starts fresh. */
|
|
1005
|
+
isStale: () => stale,
|
|
1006
|
+
/**
|
|
1007
|
+
* Put back what the pad cleared BY ITSELF — an idle overwrite or a
|
|
1008
|
+
* scribble. An explicit `clear()` is not stashed: a caller clears the pad
|
|
1009
|
+
* because it has banked the drawing, and restoring that would hand back a
|
|
1010
|
+
* sample the writer already dealt with.
|
|
1011
|
+
*/
|
|
1012
|
+
undoClear() {
|
|
1013
|
+
if (!dropped || !dropped.length) return false;
|
|
1014
|
+
strokes = strokes.length ? [...dropped, ...strokes] : dropped;
|
|
1015
|
+
dropped = null;
|
|
1016
|
+
lastEndAt = now();
|
|
1017
|
+
armStale();
|
|
1018
|
+
render();
|
|
1019
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
1020
|
+
return true;
|
|
1021
|
+
},
|
|
1022
|
+
/** Change either overwrite behaviour, or the settled look, at runtime. */
|
|
1023
|
+
configure(opts = {}) {
|
|
1024
|
+
if ("idleOverwrite" in opts) idleOverwrite = Number(opts.idleOverwrite) || 0;
|
|
1025
|
+
if ("scribbleClear" in opts) scribbleClear = !!opts.scribbleClear;
|
|
1026
|
+
if ("scribble" in opts) scribble = opts.scribble;
|
|
1027
|
+
if ("staleAlpha" in opts) staleAlpha = Number(opts.staleAlpha);
|
|
1028
|
+
armStale();
|
|
1029
|
+
},
|
|
1030
|
+
clear() {
|
|
1031
|
+
strokes = [];
|
|
1032
|
+
current = [];
|
|
1033
|
+
activeId = null;
|
|
1034
|
+
activeType = null;
|
|
1035
|
+
rect = null;
|
|
1036
|
+
clearTimeout(staleTimer);
|
|
1037
|
+
staleTimer = 0;
|
|
1038
|
+
setStale(false);
|
|
1039
|
+
droppedPending = false;
|
|
1040
|
+
render();
|
|
1041
|
+
if (onStrokeEnd) onStrokeEnd(strokes);
|
|
1042
|
+
}
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// ../../library/src/pad.js
|
|
1047
|
+
function attachPad(el, recognizer, { width = 240, height = 240, ink = "#1e293b", idleOverwrite = 2, scribbleClear = true, scribble = null, staleAlpha, onStale, recognizeOptions } = {}) {
|
|
1048
|
+
if (!recognizer || typeof recognizer.recognize !== "function") throw new TypeError("millirec: attachPad(el, recognizer) needs a recognizer with recognize(strokes)");
|
|
1049
|
+
const pad = createDrawCanvas({
|
|
1050
|
+
width,
|
|
1051
|
+
height,
|
|
1052
|
+
ink,
|
|
1053
|
+
idleOverwrite,
|
|
1054
|
+
scribbleClear,
|
|
1055
|
+
scribble,
|
|
1056
|
+
onStale,
|
|
1057
|
+
...staleAlpha === void 0 ? {} : { staleAlpha },
|
|
1058
|
+
onClear: (reason) => el.dispatchEvent(new CustomEvent("millirec:clear", { detail: { reason, undo: () => pad.undoClear() } })),
|
|
1059
|
+
onStrokeEnd: async (strokes) => {
|
|
1060
|
+
if (!strokes.length) {
|
|
1061
|
+
el.dispatchEvent(new CustomEvent("millirec:result", { detail: { results: [], strokes: [] } }));
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const results = await (recognizeOptions ? recognizer.recognize(strokes, recognizeOptions) : recognizer.recognize(strokes));
|
|
1065
|
+
el.dispatchEvent(new CustomEvent("millirec:result", { detail: { results, strokes } }));
|
|
1066
|
+
}
|
|
1067
|
+
});
|
|
1068
|
+
el.appendChild(pad.el);
|
|
1069
|
+
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 };
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// ../../library/src/char-lite.js
|
|
1073
|
+
var MillirecCharLite = class extends MillirecCharLiteCore {
|
|
1074
|
+
static createDrawCanvas(opts) {
|
|
1075
|
+
return createDrawCanvas(opts);
|
|
954
1076
|
}
|
|
955
|
-
|
|
956
|
-
|
|
1077
|
+
/** Mount a drawing pad in `el` (library/src/pad.js): 'millirec:result' after each stroke, 'millirec:clear' when it drops its ink. */
|
|
1078
|
+
attach(el, opts) {
|
|
1079
|
+
return attachPad(el, this, opts);
|
|
957
1080
|
}
|
|
958
1081
|
};
|
|
959
1082
|
if (typeof window !== "undefined" && false) {
|
|
@@ -972,7 +1095,7 @@ function nodeFileUrl(url2, spec) {
|
|
|
972
1095
|
}
|
|
973
1096
|
}
|
|
974
1097
|
|
|
975
|
-
// src/
|
|
1098
|
+
// src/sets.js
|
|
976
1099
|
var SETS = ["all", "capitals", "digits", "lowercase", "punctuation"];
|
|
977
1100
|
async function loadSet(name, { assetBase = HERE } = {}) {
|
|
978
1101
|
if (!SETS.includes(name)) throw new Error(`millirec: no training set "${name}" (one of ${SETS.join(", ")})`);
|
|
@@ -981,12 +1104,17 @@ async function loadSet(name, { assetBase = HERE } = {}) {
|
|
|
981
1104
|
nodeFileUrl(url2, `millirec/char-lite/sets/${name}.json`);
|
|
982
1105
|
return fetchAsset(url2, { what: `the ${name} training set`, base, recognizer: "char-lite" });
|
|
983
1106
|
}
|
|
1107
|
+
function liteOptions(opts = {}) {
|
|
1108
|
+
if (!opts.training) throw new Error('MillirecCharLite.create: pass { training } \u2014 e.g. await loadSet("digits")');
|
|
1109
|
+
return { assetBase: HERE, ...opts };
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// src/char-lite.js
|
|
984
1113
|
var MillirecCharLite2 = class extends MillirecCharLite {
|
|
985
1114
|
/** As the script-tag create(), but `training` is required (no window.MILLIREC_TRAINING)
|
|
986
1115
|
* and the worker/wasm are found beside this module unless `assetBase` says otherwise. */
|
|
987
1116
|
static create(opts = {}) {
|
|
988
|
-
|
|
989
|
-
return super.create({ assetBase: HERE, ...opts });
|
|
1117
|
+
return super.create(liteOptions(opts));
|
|
990
1118
|
}
|
|
991
1119
|
};
|
|
992
1120
|
export {
|