Cotton code
183 lines · 9.9 KB · TypeScriptRaw
/** * The ink corpus converters — `scripts/ink/corpus-ujipenchars2.py` and * `scripts/ink/corpus-hwrt.py` — on a handful of synthetic letters and digits * each, in their dataset's own format. What can be WRONG: a symbol not scaled * to the thumb's 120 pt, time made up where the dataset has it (or missing * where it has not), the case lost, a digit dropped or given a case, a * symbol that is neither letter nor digit let in, a lone tap written as one. */import { spawnSync } from "node:child_process";import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { afterEach, describe, expect, it } from "vitest";const ROOT = resolve(__dirname, "../..");type Row = { strokes: number[][][]; label: string; case: string; writer: string; source: string; input: string };let scratch: string | undefined;afterEach(() => {  if (scratch) rmSync(scratch, { recursive: true, force: true });  scratch = undefined;});function convert(script: string, input: string): { rows: Row[]; labels: string[]; stats: Record<string, unknown>; stdout: string } {  const out = join(scratch!, "corpus");  const run = spawnSync("python3", ["-I", join(ROOT, "scripts/ink", script), input, out], { encoding: "utf8" });  expect(run.stderr).toBe("");  expect(run.status).toBe(0);  const dataset = script.replace(/^corpus-|\.py$/g, "");  const rows = readFileSync(join(out, `${dataset}.jsonl`), "utf8").trim().split("\n").map((l) => JSON.parse(l) as Row);  const labels = JSON.parse(readFileSync(join(out, `${dataset}.labels.json`), "utf8")) as string[];  const stats = JSON.parse(readFileSync(join(out, `${dataset}.stats.json`), "utf8")) as Record<string, unknown>;  return { rows, labels, stats, stdout: run.stdout };}const side = (row: Row) => {  const xs = row.strokes.flat().map((p) => p[0]);  const ys = row.strokes.flat().map((p) => p[1]);  return { left: Math.min(...xs), top: Math.min(...ys), longer: Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)) };};describe("corpus-ujipenchars2.py", () => {  // Six samples: a, A in two strokes, a digit, a sign (neither letter nor digit), a lone tap, h with a repeated point.  const fixture = [    "// a synthetic UJIpenchars2 file",    "// ASCII char: a",    "WORD a trn_UJI_W01-01",    "  NUMSTROKES 1",    "  POINTS 4 # 100 100 300 100 300 400 100 400",    "WORD A tst_UPV_W42-02",    "  NUMSTROKES 2",    "  POINTS 3 # 0 600 300 0 600 600",    "  POINTS 2 # 150 300 450 300",    "WORD 7 trn_UJI_W01-01",    "  NUMSTROKES 1",    "  POINTS 2 # 0 0 100 200",    "WORD ? trn_UJI_W01-01",    "  NUMSTROKES 1",    "  POINTS 2 # 0 0 100 200",    "WORD b trn_UJI_W01-02",    "  NUMSTROKES 1",    "  POINTS 2 # 50 50 50 50",    "WORD h trn_UJI_W03-01",    "  NUMSTROKES 1",    "  POINTS 4 # 0 0 0 0 0 200 100 200",  ].join("\n");  it("writes the letters and digits only, scaled to 120 pt, with synthesised time, the case kept and a digit's case `digit`", () => {    scratch = mkdtempSync(join(tmpdir(), "ink-corpus-"));    const input = join(scratch, "ujipenchars2.txt");    writeFileSync(input, fixture, "latin1");    const { rows, labels, stats, stdout } = convert("corpus-ujipenchars2.py", input);    expect(labels).toEqual(["a", "a", "7", "h"]);    expect(rows.map((r) => [r.label, r.case, r.writer, r.source, r.input])).toEqual([      ["a", "lower", "trn_UJI_W01", "ujipenchars2", "stylus"],      ["a", "upper", "tst_UPV_W42", "ujipenchars2", "stylus"],      ["7", "digit", "trn_UJI_W01", "ujipenchars2", "stylus"],      ["h", "lower", "trn_UJI_W03", "ujipenchars2", "stylus"],    ]);    for (const row of rows) expect(side(row)).toEqual({ left: 0, top: 0, longer: 120 });    // a: 200 × 300 units, the taller side made 120 pt.    expect(rows[0].strokes).toEqual([[[0, 0, 0], [80, 0, 8], [80, 120, 16], [0, 120, 24]]]);    // A: 8 ms a point, 450 ms from one stroke's last point to the next's first.    expect(rows[1].strokes.map((s) => s.map((p) => p[2]))).toEqual([[0, 8, 16], [466, 474]]);    // 7: 100 × 200 units, scaled as a letter is.    expect(rows[2].strokes).toEqual([[[0, 0, 0], [60, 120, 8]]]);    // h: the repeated point is dropped.    expect(rows[3].strokes[0]).toHaveLength(3);    expect(stats.per_symbol).toEqual({ "7": { digit: 1 }, a: { lower: 1, upper: 1 }, h: { lower: 1, upper: 0 } });    expect(stats).toMatchObject({ lines: 4, skipped: 1, writers: 3 });    expect(stdout).toContain("4 symbols, 3 writers, 1 skipped");  });  it("stops on a sample whose points disagree with its header", () => {    scratch = mkdtempSync(join(tmpdir(), "ink-corpus-"));    const input = join(scratch, "ujipenchars2.txt");    writeFileSync(input, "WORD a trn_UJI_W01-01\n  NUMSTROKES 1\n  POINTS 3 # 0 0 10 10\n", "latin1");    const run = spawnSync("python3", ["-I", join(ROOT, "scripts/ink/corpus-ujipenchars2.py"), input, join(scratch, "out")], { encoding: "utf8" });    expect(run.status).not.toBe(0);    expect(run.stderr).toContain("POINTS 3 but 4 numbers");  });});describe("corpus-hwrt.py", () => {  it("keeps the dataset's own time, takes single letters and digits only, and tells touch from desktop", () => {    scratch = mkdtempSync(join(tmpdir(), "ink-corpus-"));    const data = join(scratch, "hwrt");    mkdirSync(data);    writeFileSync(join(data, "symbols.csv"), "symbol_id;latex;training_samples;test_samples\n31;A;1;0\n90;a;1;1\n200;\\alpha;1;0\n77;7;1;0\n300;10;1;0\n");    const stroke = (pts: number[][]) => pts.map(([x, y, time]) => ({ x, y, time }));    const row = (id: number, user: number, strokes: number[][][], agent: string) =>      `${id};${user};${JSON.stringify(strokes.map(stroke))};${agent}`;    const iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) Mobile/11A465";    const desktop = "Mozilla/5.0 (X11; Linux x86_64) Firefox/29.0";    writeFileSync(join(data, "train-data.csv"), ["symbol_id;user_id;data;user_agent",      row(31, 7, [[[0, 100, 1000], [50, 0, 1100], [100, 100, 1200]], [[25, 50, 1700], [75, 50, 1800]]], desktop),      row(90, 8, [[[10, 10, 5000], [10, 70, 5016], [40, 70, 5032]]], iphone),      row(200, 7, [[[0, 0, 1], [9, 9, 2]]], desktop),      row(77, 10, [[[0, 0, 100], [60, 0, 116], [30, 120, 132]]], iphone),      row(300, 10, [[[0, 0, 1], [9, 9, 2]]], desktop),    ].join("\n") + "\n");    writeFileSync(join(data, "test-data.csv"), ["symbol_id;user_id;data;user_agent",      row(90, 7, [[[3, 3, 10], [3, 3, 20]]], desktop),      row(90, 9, [[[0, 0, 0], [20, 10, 30]]], desktop),    ].join("\n") + "\n");    const { rows, labels, stats } = convert("corpus-hwrt.py", data);    expect(labels).toEqual(["a", "a", "7", "a"]);    expect(rows.map((r) => [r.case, r.writer, r.input])).toEqual([      ["upper", "7", "desktop"], ["lower", "8", "touch"], ["digit", "10", "touch"], ["lower", "9", "desktop"],    ]);    // 7: its own time, from its first touch; 60 × 120 is already the thumb's size.    expect(rows[2].strokes).toEqual([[[0, 0, 0], [60, 0, 16], [30, 120, 32]]]);    expect(rows[0].strokes.map((s) => s.map((p) => p[2]))).toEqual([[0, 100, 200], [700, 800]]);    expect(rows[1].strokes).toEqual([[[0, 0, 0], [0, 120, 16], [60, 120, 32]]]);    for (const r of rows) expect(side(r).longer).toBe(120);    expect(stats).toMatchObject({ lines: 4, skipped: 1, writers: 4, inputs: { desktop: 2, touch: 2 }, per_symbol: { "7": { digit: 1 } } });  });});describe("train.py features", () => {  // Five synthetic groups, through the harness's input contract (scripts/ink/ink_input.py):  // an L, a two-stroke T, an i with its dot, a lone tap, an 8-stroke scribble.  const lines = [    { strokes: [[[0, 0, 0], [0, 100, 8], [50, 100, 16]]], label: "l", case: "upper" },    { strokes: [[[0, 0, 0], [100, 0, 8]], [[50, 0, 466], [50, 100, 474]]], label: "t", case: "upper" },    { strokes: [[[10, 30, 0], [10, 100, 8]], [[10, 0, 466]]], label: "i", case: "lower" },    { strokes: [[[5, 5, 0]]], label: "o", case: "lower" },    { strokes: Array.from({ length: 8 }, (_, k) => [[k * 10, 0, k * 500], [k * 10 + 5, 40, k * 500 + 8]]), label: "m", case: "lower" },  ];  type Feature = { points: number[][]; stroke_count: number };  it("reads each group as 64 points of [x, y, pen_up] in the unit box, aspect kept and centred, the jumps between strokes part of the path", () => {    scratch = mkdtempSync(join(tmpdir(), "ink-corpus-"));    const file = join(scratch, "five.jsonl");    writeFileSync(file, lines.map((l) => JSON.stringify({ ...l, writer: "w", source: "fixture", input: "touch" })).join("\n") + "\n");    const run = spawnSync("python3", ["-I", join(ROOT, "scripts/ink/train.py"), "features", file], { encoding: "utf8" });    expect(run.stderr).toBe("");    expect(run.status).toBe(0);    const out = run.stdout.trim().split("\n").map((l) => JSON.parse(l) as Feature);    expect(out.map((f) => [f.points.length, f.stroke_count])).toEqual([[64, 1], [64, 2], [64, 2], [64, 1], [64, 8]]);    for (const f of out) {      for (const [x, y, up] of f.points) {        expect(x).toBeGreaterThanOrEqual(0); expect(x).toBeLessThanOrEqual(1);        expect(y).toBeGreaterThanOrEqual(0); expect(y).toBeLessThanOrEqual(1);        expect([0, 1]).toContain(up);      }    }    // L: 50 × 100, so x spans 0.25–0.75 (centred) and y 0–1, start to end, pen down throughout.    const L = out[0].points;    expect(L[0]).toEqual([0.25, 0, 0]);    expect(L[63]).toEqual([0.75, 1, 0]);    expect(L.every((p) => p[2] === 0)).toBe(true);    // T: bar 100, jump back 50, stem 100 — the samples 26–37 lie on the jump.    const up = out[1].points.flatMap((p, k) => (p[2] === 1 ? [k] : []));    expect(up).toEqual(Array.from({ length: 12 }, (_, k) => 26 + k));    // i: the path ends on the jump up to the dot.    expect(out[2].points[63]).toEqual([0.5, 0, 1]);    // A lone tap: every sample in the box's middle, pen down.    expect(new Set(out[3].points.map((p) => p.join(",")))).toEqual(new Set(["0.5,0.5,0"]));  });});