Cotton code
105 lines · 4.7 KB · PythonRaw
#!/usr/bin/env python3"""THE INPUT CONTRACT for the Core ML ink model (first the ink-mlkit lane's,contract/ink_input.py, 3 Nov 2026; this is the reference now: the model readsdigits as well as letters, owner, 3 Nov 2026: "I also want to include havingnumbers").This file is the reference: train on exactly what `encode` returns, and thecore's Rust twin (crates/cotton-core/src/ink/input.rs) feeds the model the samenumbers on every phone (held to this file by input_tests.rs over the fixtures,and to contract/fixtures.jsonl by `pnpm ink:corpus`, max |diff| <= 1e-4).A letter group is strokes in the order written, each [[x, y, t], ...] in pt, y down.t is ignored.  points        float32 [1, 64, 3]: 64 samples [x, y, pen_up]  stroke_count  float32 [1, 1]: the number of non-empty strokes1. Path. Join the strokes, in order, into one polyline of all their points.   The segment from a stroke's last point to the next stroke's first point   is a JUMP (pen up); every other segment is DRAWN.2. Resample. L = total length of the path, drawn and jump segments alike.   For k = 0..63, d_k = L * k / 63. The sample lies on the first segment   (in path order, skipping zero-length segments) whose end is at cumulative   distance >= d_k (for k = 63, the last non-zero segment's end), linearly   interpolated. pen_up = 1.0 if that segment is a jump, else 0.0. If L == 0   (a dot), all 64 samples are the first point with pen_up 0.3. Normalise. Over ALL the input points (not the samples): box min (mx, my),   width w, height h, s = max(w, h) (s = 1 if s < 1e-6). Each sample becomes   x' = (x - mx) / s + (1 - w / s) / 2,  y' = (y - my) / s + (1 - h / s) / 2,   so the longer side spans 0..1 and the shorter is centred; y still down.   Computed in float64, stored as float32.Output: `probabilities`, float32 (or float64) [1, 62] or [62], a softmax inthe class order CLASSES below (a..z, then A..Z, then 0..9). A Core MLclassifier whose class labels are exactly these 62 strings is accepted too.Case-folding (search is case-free) sums each letter's two cases and leavesthe digits as they are: 36 symbols."""import mathCLASSES = list("abcdefghijklmnopqrstuvwxyz") + list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + list("0123456789")N = 64def encode(strokes):    strokes = [s for s in strokes if len(s) > 0]    pts, jump = [], []          # path points; jump[i] is True when segment i -> i+1 is a jump    for si, s in enumerate(strokes):        for pi, p in enumerate(s):            if pts:                jump.append(pi == 0)            pts.append((float(p[0]), float(p[1])))    seg = [math.hypot(b[0] - a[0], b[1] - a[1]) for a, b in zip(pts, pts[1:])]    total = sum(seg)    samples = []    if total == 0:        samples = [(pts[0][0], pts[0][1], 0.0)] * N    else:        cum = [0.0]        for d in seg:            cum.append(cum[-1] + d)        nonzero = [i for i, d in enumerate(seg) if d > 0]        j = 0        for k in range(N):            dk = total * k / (N - 1)            if k == N - 1:                i = nonzero[-1]            else:                while cum[nonzero[j] + 1] < dk:                    j += 1                i = nonzero[j]            u = min(1.0, max(0.0, (dk - cum[i]) / seg[i]))            a, b = pts[i], pts[i + 1]            samples.append((a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u, 1.0 if jump[i] else 0.0))    xs, ys = [p[0] for p in pts], [p[1] for p in pts]    mx, my = min(xs), min(ys)    w, h = max(xs) - mx, max(ys) - my    s = max(w, h)    if s < 1e-6:        s = 1.0    ox, oy = (1 - w / s) / 2, (1 - h / s) / 2    points = [[(x - mx) / s + ox, (y - my) / s + oy, f] for x, y, f in samples]    return points, float(len(strokes))def label_index(label, case):    """The class of a corpus line: its label in its case (`digit`: as it is)."""    if case == "digit":        return CLASSES.index(label)    return CLASSES.index(label.upper() if case == "upper" else label.lower())if __name__ == "__main__":    # Writes contract/fixtures.jsonl: the first 40 lines of each real-hands corpus with their encoding.    import json, os, sys    here = os.path.dirname(os.path.abspath(__file__))    out = open(os.path.join(here, "fixtures.jsonl"), "w")    for name in sys.argv[1:] or ["ujipenchars2", "hwrt"]:        with open(os.path.join(here, "..", "corpus", f"{name}.jsonl")) as f:            for i, line in enumerate(f):                if i >= 40:                    break                r = json.loads(line)                pts, count = encode(r["strokes"])                out.write(json.dumps({"strokes": r["strokes"], "label": r["label"], "case": r["case"],                                      "points": pts, "stroke_count": count}) + "\n")