millirec 0.1.1 → 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 +101 -0
- package/README.md +286 -51
- package/dist/char-cnn/cnn-web.wasm +0 -0
- package/dist/char-cnn/core.d.ts +15 -1
- package/dist/char-cnn/core.js +214 -100
- package/dist/char-cnn/index.d.ts +1 -1
- package/dist/char-cnn/index.js +267 -137
- 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 +6 -6
- package/dist/char-cnn/options/accurate.json +5 -5
- 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-base.q4.bin +0 -0
- package/dist/char-cnn/options/digits/digits-tiny.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 +17 -0
- package/dist/char-cnn/options/digits.json +15 -0
- package/dist/char-cnn/options/fast/base-p25.head.bin +0 -0
- package/dist/char-cnn/options/fast/tiny.bin +0 -0
- package/dist/char-cnn/options/fast/tiny.head.bin +0 -0
- package/dist/char-cnn/options/fast.js +6 -6
- package/dist/char-cnn/options/fast.json +5 -5
- package/dist/char-cnn/options/lowercase/lowercase-base.head.bin +0 -0
- package/dist/char-cnn/options/lowercase/lowercase-base.q4.bin +0 -0
- package/dist/char-cnn/options/lowercase/lowercase-tiny.bin +0 -0
- 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 +17 -0
- package/dist/char-cnn/options/lowercase.json +15 -0
- 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 +3 -3
- package/dist/char-cnn/options/small.json +2 -2
- 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 +459 -297
- package/dist/char-lite/millirec-char-lite.min.js +1 -1
- package/dist/char-lite/millirec.wasm +0 -0
- package/dist/char-lite/sets.json +25 -29
- package/dist/index.d.ts +35 -0
- package/dist/index.js +88 -0
- package/dist/overlap/millirec-overlap.min.js +7 -7
- package/dist/overlap/millirec.wasm +0 -0
- package/dist/pad/index.d.ts +8 -0
- package/dist/pad/index.js +482 -0
- package/package.json +30 -8
- package/dist/char-cnn/base-p25.head.bin +0 -0
- package/dist/char-cnn/tiny.head.bin +0 -0
- /package/dist/char-cnn/{base.head.bin → options/accurate/base.head.bin} +0 -0
- /package/dist/char-cnn/{base.q4.bin → options/accurate/base.q4.bin} +0 -0
- /package/dist/char-cnn/{tiny.bin → options/accurate/tiny.bin} +0 -0
- /package/dist/char-cnn/{base-p25.bin → options/fast/base-p25.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,6 +191,404 @@ function samplesMap(data) {
|
|
|
190
191
|
return out;
|
|
191
192
|
}
|
|
192
193
|
|
|
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;
|
|
200
|
+
}
|
|
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);
|
|
213
|
+
}
|
|
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);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
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;
|
|
227
|
+
}
|
|
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) : "";
|
|
233
|
+
}
|
|
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);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
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);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
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
|
+
}
|
|
325
|
+
}
|
|
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;
|
|
330
|
+
}
|
|
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 });
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
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++;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return "strokes:" + strokes.length + ":" + n + ":" + (h1 >>> 0).toString(36) + (h2 >>> 0).toString(36);
|
|
358
|
+
}
|
|
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);
|
|
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
|
+
});
|
|
392
|
+
}
|
|
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);
|
|
411
|
+
});
|
|
412
|
+
return costs ? { classes: this.charList, costs } : null;
|
|
413
|
+
}
|
|
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();
|
|
419
|
+
if (this.bootUrl) {
|
|
420
|
+
URL.revokeObjectURL(this.bootUrl);
|
|
421
|
+
this.bootUrl = null;
|
|
422
|
+
}
|
|
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] });
|
|
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;
|
|
446
|
+
}
|
|
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");
|
|
495
|
+
}
|
|
496
|
+
const inst = new this(config, training);
|
|
497
|
+
await inst.ready;
|
|
498
|
+
return inst;
|
|
499
|
+
}
|
|
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;
|
|
569
|
+
}
|
|
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
|
+
|
|
193
592
|
// ../../widget/scribble.js
|
|
194
593
|
var SCRIBBLE = {
|
|
195
594
|
turns: 5,
|
|
@@ -408,6 +807,18 @@ function createDrawCanvas({
|
|
|
408
807
|
for (let i = 1; i < st.length; i++) ctx.lineTo(st[i].x, st[i].y);
|
|
409
808
|
ctx.stroke();
|
|
410
809
|
}
|
|
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();
|
|
821
|
+
}
|
|
411
822
|
function render() {
|
|
412
823
|
ctx.clearRect(0, 0, width, height);
|
|
413
824
|
ctx.lineWidth = 2.5;
|
|
@@ -473,8 +884,8 @@ function createDrawCanvas({
|
|
|
473
884
|
canvas.style.webkitTouchCallout = "none";
|
|
474
885
|
canvas.addEventListener("pointerdown", (e) => {
|
|
475
886
|
if (e.button > 0) return;
|
|
476
|
-
if (activeId !== null
|
|
477
|
-
if (activeType === "pen" && e.pointerType !== "pen") return;
|
|
887
|
+
if (activeId !== null) {
|
|
888
|
+
if (activeType === "pen" && e.pointerType !== "pen" && e.pointerId !== activeId) return;
|
|
478
889
|
finish({ pointerId: activeId });
|
|
479
890
|
}
|
|
480
891
|
e.preventDefault();
|
|
@@ -509,8 +920,9 @@ function createDrawCanvas({
|
|
|
509
920
|
}
|
|
510
921
|
return;
|
|
511
922
|
}
|
|
923
|
+
const from = current.length - 1;
|
|
512
924
|
for (const ev of events) current.push(getPos(ev));
|
|
513
|
-
|
|
925
|
+
paintFrom(current, from);
|
|
514
926
|
}, { passive: false });
|
|
515
927
|
const finish = (e, cancelled = false) => {
|
|
516
928
|
if (activeId !== e.pointerId) return;
|
|
@@ -568,8 +980,14 @@ function createDrawCanvas({
|
|
|
568
980
|
}
|
|
569
981
|
render();
|
|
570
982
|
};
|
|
571
|
-
canvas.addEventListener("pointerup", (e) =>
|
|
572
|
-
|
|
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
|
+
});
|
|
573
991
|
return {
|
|
574
992
|
el: canvas,
|
|
575
993
|
getStrokes: () => strokes,
|
|
@@ -625,301 +1043,40 @@ function createDrawCanvas({
|
|
|
625
1043
|
};
|
|
626
1044
|
}
|
|
627
1045
|
|
|
628
|
-
// ../../library/src/
|
|
629
|
-
function
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
const type = r.headers && r.headers.get("content-type") || "";
|
|
649
|
-
if (!r.ok) throw fail(`HTTP ${r.status}`);
|
|
650
|
-
if (as === "json") {
|
|
651
|
-
try {
|
|
652
|
-
return await r.json();
|
|
653
|
-
} catch (e) {
|
|
654
|
-
throw fail(/html/i.test(type) ? "an HTML page" : e && e.message);
|
|
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 } }));
|
|
655
1066
|
}
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
if (head.startsWith("<!doctype") || head.startsWith("<html")) throw fail("an HTML page");
|
|
660
|
-
return buf;
|
|
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 };
|
|
661
1070
|
}
|
|
662
1071
|
|
|
663
1072
|
// ../../library/src/char-lite.js
|
|
664
|
-
|
|
665
|
-
const src = typeof document !== "undefined" && document.currentScript && document.currentScript.src || "";
|
|
666
|
-
return src ? src.slice(0, src.lastIndexOf("/") + 1) : "";
|
|
667
|
-
}
|
|
668
|
-
var ASSET_BASE = scriptBase();
|
|
669
|
-
var CACHE_MAX = 256;
|
|
670
|
-
var StrokeWorker = class {
|
|
671
|
-
constructor({ assetBase, workerName, training, params }) {
|
|
672
|
-
assetBase = assetBaseOf(assetBase);
|
|
673
|
-
const decoded = decode(training);
|
|
674
|
-
this.trainPaths = samplesMap(decoded);
|
|
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;
|
|
690
|
-
});
|
|
691
|
-
this.worker.onmessage = (evt) => this.onMessage(evt);
|
|
692
|
-
const workerUrl = assetBase + workerName;
|
|
693
|
-
this.worker.onerror = (evt) => {
|
|
694
|
-
const e = notServed(workerUrl, "the char-lite worker", assetBase, "char-lite");
|
|
695
|
-
e.message += ` (${evt.message || "script failed to load"})`;
|
|
696
|
-
this.readyReject(e);
|
|
697
|
-
};
|
|
698
|
-
this.assetBase = assetBase;
|
|
699
|
-
}
|
|
700
|
-
onMessage(evt) {
|
|
701
|
-
const d = evt.data;
|
|
702
|
-
if (this.bootUrl) {
|
|
703
|
-
URL.revokeObjectURL(this.bootUrl);
|
|
704
|
-
this.bootUrl = null;
|
|
705
|
-
}
|
|
706
|
-
if (d.type === "getCharList") {
|
|
707
|
-
if (this.params) this.worker.postMessage({ type: "setParams", params: this.params });
|
|
708
|
-
this.worker.postMessage({ type: "charList", charList: this.charList, pointsPerShape: this.pointsPerShape, samplesPerChar: this.samplesPerChar });
|
|
709
|
-
} else if (d.type === "prepAll") {
|
|
710
|
-
this.charList.forEach((c, idx) => {
|
|
711
|
-
this.trainPaths[c].forEach((sample, i) => {
|
|
712
|
-
const { points, scale } = orientedPointsFromPolyline(decodeSample(sample));
|
|
713
|
-
this.worker.postMessage({ type: "addPoints", points, m: idx * this.samplesPerChar + i, scale });
|
|
714
|
-
});
|
|
715
|
-
});
|
|
716
|
-
this.readyResolve();
|
|
717
|
-
} else if (d.type === "addResult" && d.result) {
|
|
718
|
-
this.cache.delete(d.path);
|
|
719
|
-
this.cache.set(d.path, d.result);
|
|
720
|
-
if (this.cache.size > CACHE_MAX) this.cache.delete(this.cache.keys().next().value);
|
|
721
|
-
const waiters = this.inFlight.get(d.path) || [];
|
|
722
|
-
this.inFlight.delete(d.path);
|
|
723
|
-
for (const resolve of waiters) resolve(this.applyPlugins(d.result, d.path));
|
|
724
|
-
} else if (d.type === "allResult") {
|
|
725
|
-
const waiters = this.allWaiters.get(d.path) || [];
|
|
726
|
-
this.allWaiters.delete(d.path);
|
|
727
|
-
for (const resolve of waiters) resolve(d.costs);
|
|
728
|
-
} else if (d.type === "bootError") {
|
|
729
|
-
const e = notServed(this.assetBase + "millirec.wasm", "the char-lite matcher", this.assetBase, "char-lite");
|
|
730
|
-
e.message += ` (worker boot failed: ${d.message})`;
|
|
731
|
-
this.readyReject(e);
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
applyPlugins(raw, path) {
|
|
735
|
-
let out = parseResult(raw, this.charList, "stroke", SECOND_AVERAGE);
|
|
736
|
-
for (const p of this.plugins) if (p.rerank) out = p.rerank(out, { raw, path, charList: this.charList, mode: "stroke", recognizer: this }) || out;
|
|
737
|
-
return out;
|
|
738
|
-
}
|
|
739
|
-
uploadTest(input) {
|
|
740
|
-
const strokes = Array.isArray(input[0]) ? input : [input];
|
|
741
|
-
const polyline = resampleStrokes(strokes, this.pointsPerShape);
|
|
742
|
-
if (!polyline) return false;
|
|
743
|
-
const { points, scale } = orientedPointsFromPolyline(polyline);
|
|
744
|
-
this.worker.postMessage({ type: "addPoints", points, m: -1, scale });
|
|
745
|
-
return true;
|
|
746
|
-
}
|
|
747
|
-
keyFor(input) {
|
|
748
|
-
const flat = Array.isArray(input[0]) ? input.flat() : input;
|
|
749
|
-
let hash = 5381;
|
|
750
|
-
for (const p of flat) hash = (hash * 33 ^ (p.x * 7919 + p.y | 0)) >>> 0;
|
|
751
|
-
return "strokes:" + flat.length + ":" + hash.toString(36);
|
|
752
|
-
}
|
|
753
|
-
async recognize(strokes) {
|
|
754
|
-
if (this.destroyed || !strokes || !strokes.length) return null;
|
|
755
|
-
await this.readyPromise;
|
|
756
|
-
if (this.destroyed) return null;
|
|
757
|
-
const key = this.keyFor(strokes);
|
|
758
|
-
if (this.cache.has(key)) {
|
|
759
|
-
const hit = this.cache.get(key);
|
|
760
|
-
this.cache.delete(key);
|
|
761
|
-
this.cache.set(key, hit);
|
|
762
|
-
return this.applyPlugins(hit, key);
|
|
763
|
-
}
|
|
764
|
-
if (!this.uploadTest(strokes)) return null;
|
|
765
|
-
return new Promise((resolve) => {
|
|
766
|
-
let timer;
|
|
767
|
-
const done = (v) => {
|
|
768
|
-
clearTimeout(timer);
|
|
769
|
-
resolve(v);
|
|
770
|
-
};
|
|
771
|
-
if (this.inFlight.has(key)) this.inFlight.get(key).push(done);
|
|
772
|
-
else {
|
|
773
|
-
this.inFlight.set(key, [done]);
|
|
774
|
-
this.worker.postMessage({ type: "compare", path: key, elementID: "req" + ++this.reqCounter });
|
|
775
|
-
}
|
|
776
|
-
timer = setTimeout(() => done(null), 4e3);
|
|
777
|
-
});
|
|
778
|
-
}
|
|
779
|
-
async rawScores(strokes) {
|
|
780
|
-
if (this.destroyed) return null;
|
|
781
|
-
await this.readyPromise;
|
|
782
|
-
if (this.destroyed) return null;
|
|
783
|
-
if (!this.uploadTest(strokes)) return null;
|
|
784
|
-
const key = "all:" + ++this.reqCounter;
|
|
785
|
-
const costs = await new Promise((resolve) => {
|
|
786
|
-
let timer;
|
|
787
|
-
const done = (v) => {
|
|
788
|
-
clearTimeout(timer);
|
|
789
|
-
resolve(v);
|
|
790
|
-
};
|
|
791
|
-
this.allWaiters.set(key, [done]);
|
|
792
|
-
this.worker.postMessage({ type: "compareAll", path: key, counts: this.charList.map((c) => this.trainPaths[c].length) });
|
|
793
|
-
timer = setTimeout(() => done(null), 8e3);
|
|
794
|
-
});
|
|
795
|
-
return costs ? { classes: this.charList, costs } : null;
|
|
796
|
-
}
|
|
797
|
-
/** Stop the worker; anything still waiting gets null, and so does every later call. */
|
|
798
|
-
destroy() {
|
|
799
|
-
if (this.destroyed) return;
|
|
800
|
-
this.destroyed = true;
|
|
801
|
-
this.worker.terminate();
|
|
802
|
-
if (this.bootUrl) {
|
|
803
|
-
URL.revokeObjectURL(this.bootUrl);
|
|
804
|
-
this.bootUrl = null;
|
|
805
|
-
}
|
|
806
|
-
for (const map of [this.inFlight, this.allWaiters]) {
|
|
807
|
-
for (const list of map.values()) for (const done of list) done(null);
|
|
808
|
-
map.clear();
|
|
809
|
-
}
|
|
810
|
-
this.cache.clear();
|
|
811
|
-
this.readyResolve();
|
|
812
|
-
}
|
|
813
|
-
};
|
|
814
|
-
var toPairs = (parsed) => parsed ? parsed.chars.map((c, i) => ({ char: c, prob: parsed.probs[i] })) : null;
|
|
815
|
-
var MillirecCharLite = class {
|
|
816
|
-
/** Drawn strokes → one training sample (resampled points, delta-encoded).
|
|
817
|
-
* Pass the set's pointsPerShape to match it (the shipped sets are 25). */
|
|
818
|
-
static strokesToSample(strokes, pointsPerShape = POINTS_PER_SHAPE) {
|
|
819
|
-
const polyline = resampleStrokes(Array.isArray(strokes[0]) ? strokes : [strokes], pointsPerShape);
|
|
820
|
-
return polyline ? polylineToSample(polyline) : null;
|
|
821
|
-
}
|
|
822
|
-
/**
|
|
823
|
-
* A copy of `training` with your own samples added — the way to make a
|
|
824
|
-
* recognizer learn one person's hand. `extra` maps a class (any string: a
|
|
825
|
-
* letter, a digit, an emoji) to drawings: strokes ([[{x,y},...], ...]) or
|
|
826
|
-
* already-encoded samples ({x:[Δ...], y:[Δ...]}). Each is resampled to the
|
|
827
|
-
* set's pointsPerShape. Classes not in `training` are added. `replace: true`
|
|
828
|
-
* drops a class's shipped samples instead of appending to them. `training`
|
|
829
|
-
* is not modified.
|
|
830
|
-
*/
|
|
831
|
-
static withSamples(training, extra, { replace = false } = {}) {
|
|
832
|
-
const base = decode({ ...training });
|
|
833
|
-
const n = base.pointsPerShape;
|
|
834
|
-
const toSample = (d) => {
|
|
835
|
-
const strokes = Array.isArray(d) ? Array.isArray(d[0]) ? d : [d] : [decodeSample(d)];
|
|
836
|
-
const polyline = resampleStrokes(strokes, n);
|
|
837
|
-
return polyline ? polylineToSample(polyline) : null;
|
|
838
|
-
};
|
|
839
|
-
const classes = { ...base.classes };
|
|
840
|
-
for (const [cls, drawings] of Object.entries(extra || {})) {
|
|
841
|
-
const own = (drawings || []).map(toSample).filter(Boolean);
|
|
842
|
-
if (!own.length) continue;
|
|
843
|
-
const shipped = classes[cls]?.samples || [];
|
|
844
|
-
classes[cls] = { ...classes[cls] || {}, samples: replace ? own : shipped.concat(own) };
|
|
845
|
-
}
|
|
846
|
-
return { ...base, classes };
|
|
847
|
-
}
|
|
1073
|
+
var MillirecCharLite = class extends MillirecCharLiteCore {
|
|
848
1074
|
static createDrawCanvas(opts) {
|
|
849
1075
|
return createDrawCanvas(opts);
|
|
850
1076
|
}
|
|
851
|
-
/**
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
const g = typeof window !== "undefined" ? window : globalThis;
|
|
855
|
-
const config = { ...g.MILLIREC_CONFIG || {}, ...opts };
|
|
856
|
-
const training = opts.training || g.MILLIREC_TRAINING;
|
|
857
|
-
if (!training) throw new Error("MillirecCharLite: no training data (training.js missing?)");
|
|
858
|
-
if (typeof Worker === "undefined" || typeof Blob === "undefined") {
|
|
859
|
-
throw new Error("millirec: char-lite needs a browser (Worker, fetch, canvas); importing is SSR-safe but call create() on the client");
|
|
860
|
-
}
|
|
861
|
-
const inst = new this(config, training);
|
|
862
|
-
await inst.ready;
|
|
863
|
-
return inst;
|
|
864
|
-
}
|
|
865
|
-
constructor(config, training) {
|
|
866
|
-
this.config = config;
|
|
867
|
-
this.stroke = new StrokeWorker({
|
|
868
|
-
assetBase: config.assetBase || ASSET_BASE,
|
|
869
|
-
workerName: config.workerStroke || "worker-stroke.js",
|
|
870
|
-
training,
|
|
871
|
-
params: config.params?.stroke || config.params || null
|
|
872
|
-
});
|
|
873
|
-
this.charList = this.stroke.charList;
|
|
874
|
-
this.ready = this.stroke.readyPromise;
|
|
875
|
-
}
|
|
876
|
-
use(plugin) {
|
|
877
|
-
this.stroke.plugins.push(plugin);
|
|
878
|
-
return this;
|
|
879
|
-
}
|
|
880
|
-
/** Recognize drawn strokes ([[{x,y},...], ...] or one polyline) → [{char, prob} x3] | null. */
|
|
881
|
-
async recognize(strokes) {
|
|
882
|
-
return toPairs(await this.stroke.recognize(strokes));
|
|
883
|
-
}
|
|
884
|
-
/** Raw per-template costs → {classes, costs}. */
|
|
885
|
-
rawScores(strokes) {
|
|
886
|
-
return this.stroke.rawScores(strokes);
|
|
887
|
-
}
|
|
888
|
-
/**
|
|
889
|
-
* Mount a drawing pad in `el`; fires 'millirec:result' ({results, strokes})
|
|
890
|
-
* after each stroke, and 'millirec:clear' ({reason, undo}) when the pad
|
|
891
|
-
* drops its own ink.
|
|
892
|
-
*
|
|
893
|
-
* The pad reads ONE character, so by default writing in it after a pause
|
|
894
|
-
* starts a fresh one (`idleOverwrite`, seconds — 0 turns it off) and
|
|
895
|
-
* scribbling over it throws it away (`scribbleClear`). Both are measured:
|
|
896
|
-
* see widget/canvas.js and scripts/verify-scribble.mjs.
|
|
897
|
-
*/
|
|
898
|
-
attach(el, { width = 240, height = 240, ink = "#1e293b", idleOverwrite = 2, scribbleClear = true, scribble = null, staleAlpha, onStale } = {}) {
|
|
899
|
-
const pad = createDrawCanvas({
|
|
900
|
-
width,
|
|
901
|
-
height,
|
|
902
|
-
ink,
|
|
903
|
-
idleOverwrite,
|
|
904
|
-
scribbleClear,
|
|
905
|
-
scribble,
|
|
906
|
-
onStale,
|
|
907
|
-
...staleAlpha === void 0 ? {} : { staleAlpha },
|
|
908
|
-
onClear: (reason) => el.dispatchEvent(new CustomEvent("millirec:clear", { detail: { reason, undo: () => pad.undoClear() } })),
|
|
909
|
-
onStrokeEnd: async (strokes) => {
|
|
910
|
-
if (!strokes.length) {
|
|
911
|
-
el.dispatchEvent(new CustomEvent("millirec:result", { detail: { results: [], strokes: [] } }));
|
|
912
|
-
return;
|
|
913
|
-
}
|
|
914
|
-
const results = await this.recognize(strokes);
|
|
915
|
-
el.dispatchEvent(new CustomEvent("millirec:result", { detail: { results, strokes } }));
|
|
916
|
-
}
|
|
917
|
-
});
|
|
918
|
-
el.appendChild(pad.el);
|
|
919
|
-
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 };
|
|
920
|
-
}
|
|
921
|
-
destroy() {
|
|
922
|
-
this.stroke.destroy();
|
|
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);
|
|
923
1080
|
}
|
|
924
1081
|
};
|
|
925
1082
|
if (typeof window !== "undefined" && false) {
|
|
@@ -938,7 +1095,7 @@ function nodeFileUrl(url2, spec) {
|
|
|
938
1095
|
}
|
|
939
1096
|
}
|
|
940
1097
|
|
|
941
|
-
// src/
|
|
1098
|
+
// src/sets.js
|
|
942
1099
|
var SETS = ["all", "capitals", "digits", "lowercase", "punctuation"];
|
|
943
1100
|
async function loadSet(name, { assetBase = HERE } = {}) {
|
|
944
1101
|
if (!SETS.includes(name)) throw new Error(`millirec: no training set "${name}" (one of ${SETS.join(", ")})`);
|
|
@@ -947,12 +1104,17 @@ async function loadSet(name, { assetBase = HERE } = {}) {
|
|
|
947
1104
|
nodeFileUrl(url2, `millirec/char-lite/sets/${name}.json`);
|
|
948
1105
|
return fetchAsset(url2, { what: `the ${name} training set`, base, recognizer: "char-lite" });
|
|
949
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
|
|
950
1113
|
var MillirecCharLite2 = class extends MillirecCharLite {
|
|
951
1114
|
/** As the script-tag create(), but `training` is required (no window.MILLIREC_TRAINING)
|
|
952
1115
|
* and the worker/wasm are found beside this module unless `assetBase` says otherwise. */
|
|
953
1116
|
static create(opts = {}) {
|
|
954
|
-
|
|
955
|
-
return super.create({ assetBase: HERE, ...opts });
|
|
1117
|
+
return super.create(liteOptions(opts));
|
|
956
1118
|
}
|
|
957
1119
|
};
|
|
958
1120
|
export {
|