mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-27 07:58:01 +01:00
* Android typing: Adaptive touch's averages, labels and guarded decoder hook (not wired to the keys yet) What: the core of Labs › Keyboard › Adaptive touch for Hex for Android, ported from iPhone's Experiment (#2146), behind nothing yet: no setting, storage or keyboard wiring reads it in this commit. - typing/AdaptiveTouchModel.kt: TouchPlane (a letters page's keycaps, touch cells, rows and pitch, hashed into a plane key) and AdaptiveTouchModel with iPhone's numbers: 4 rotating bins of 200 labelled taps, 8 contexts of up to 40 keys, priors 20 / 50 / 40, offsets within 0.3 keycap moving at most 0.05 per promotion, in use only after 400 labels over 3 sessions. Always 23,588 bytes, with its own magic ("HXAA"); no letters, words, times or tap order. - typing/AdaptiveTouchLabels.kt: iPhone's label rules (words that stood, same-length picks, words kept over a fix, erased letters retyped as a neighbour; never an autocorrection), plus untapped() for held accents. - typing/AdaptiveTouch.kt: the learner: a personal KeyGrid for the decoder, the per-axis fit check that falls back to the drawn centres, two grips per key plane, the label events, and save and reset hooks. - TypingWord keeps each tap read on the drawn keys beside the personal one. Space corrects a word only when the drawn centres would correct it too, and puts in their reading unless the personal one also clears their margin; joins, and the word kept for the next one's revision, read the drawn taps. Without Adaptive touch both lists hold the same taps. - SpatialDecoder: KeyGrid carries the plane and keeps the drawn bottom row when centres move; replaces() (iOS TypingDecoder.replaces) scores one reading against the spelling as typed. Why: a tester asked for iPhone's adaptive touch on Android. The guard is stricter than iPhone's: in the typing gate its margin check alone let a reading the drawn centres never consider change a correctly typed word ("sun" to "su" in Spanish, "Mary" to "Matt" in Bokmål). Verified on the Studio's host JVM (quality-gate.py, next commit's --adaptive): the gate's report for all six layouts is the same as dev 786451f00's, field for field (de, it and nb fail there too), and with Adaptive touch on but before it has learned, every output is the same, item for item. Off-centre typists: see the next commit. * Typing gate: --adaptive checks Adaptive touch with off-centre typists What: quality-gate.py --adaptive, and the Replay options behind it, measure Labs › Keyboard › Adaptive touch per layout, against the same input with it off. Replay's --gate takes --adaptive learn|monitor|frozen, --sessions, --typist T1|T1m|T2|T3, --profile-in, --profile-out and --unguarded; it drives Adaptive touch as the keyboard does (each letter typed, each word finished with what autocorrect did, a field per sentence) and reports on stderr when the personal centres were in use. Its replay geometry gains Adaptive touch's key plane. - A: on but before it has learned, the gate's whole input comes out the same. - B: three typists aim off the centres the same way every time (T1 low and right, T2 thumbs inward, T3 an aim per key), typing the 2,000 noisy sentences in order with it learning; word errors in the second thousand. - C: each learned profile, frozen, changes no more correctly typed words, on the centres or on the typist's aim, and the critical cases pass. - D: learned on T1, typed with T1's aim mirrored: no word broken while the old centres are still in use; also after the fallback and without it. Why: the held-out taps are drawn per tap from a population's offsets, with no aim of their own, so the gate as it was could not show Adaptive touch help or hurt. The README section has the table. Verified on the Studio's host JVM at the previous commit: A holds in all six layouts and the gate's own numbers are unchanged. B (word errors, off -> on): T1 -0.9 to -3.1%, T2 -0.9 to -4.4%, T3 -0.4 to -1.2% except French +1.4% (436 -> 442); without the guard 6-22% fewer for T1 and T2. C never higher. D: 1 word in German before the fallback, 0 elsewhere (71-179 without it). --adaptive exits 1 for German (D) and French (T3) on these bars. * Typing gate: Adaptive touch's grip-change bar, and its numbers on dev with Portuguese What: D in quality-gate.py --adaptive now asks that the old centres fall back within three sentences and break at most 2% of what they break with no fallback, instead of no word at all before the fallback. The README says why, with German's one word as the example, and its table is rerun on dev5d977b5edwith Portuguese, the seventh layout. Why: the fallback needs about 16 labels, two sentences, before it can act, so "zero" only ever held by luck: German broke 1 word where no fallback breaks 179. The coordinator agreed the bar. Verified on the Studio's host JVM (Gradle --no-daemon) on this branch rebased on5d977b5ed: quality-gate.py all gives dev's report field for field in all seven layouts (de, it and nb fail there too). --adaptive: A identical in all seven; B T1 0.9-4.4% fewer word errors, T2 0.9-4.4% (Portuguese 10.2%), T3 0.4-1.2% (Portuguese 4.3%) except French, 436 -> 442, which fails B, with French's held-out taps 415 -> 422; C never higher; D passes in all seven (German 1 word before the fallback against 179 without it). * Android keyboard: Labs › Keyboard › Adaptive touch, wired to the keys (off by default) What: the keyboard now runs Adaptive touch when its Labs switch is on. - KeyPlaneView hands the decoder its key plane (each letter's keycap, touch cell and row; the width in 10 dp steps, orientation and number row name it) and says when a touch slid onto its key (a slide from shift or ?123, a swipe that came back as a tap). - KeyboardEngine: a session per field; letters, held accents, delete, space, marks, Return, picks and undoing a fix tell Adaptive touch what became of each word, and the cursor moving, pastes, swipes, dictation and pads forget what was in hand. It learns only in a field that takes corrections and lets Hex learn, with Autocorrect and Spatial autocorrect on and the layout's own model; never in a password, email, web address or no-learning field. The decoder reads your centres wherever the lab is on. - AdaptiveTouchStore keeps the averages as one Base64 value in their own private SharedPreferences, "adaptiveTouch" (23,588 bytes as a table, under 32 KB as text, never more; allowBackup is off), saved every 400 labels and when the keyboard hides, shared by the keyboard and Settings in one process. - Settings › Labs › Keyboard: Adaptive touch, with "Learning: n of 400 taps" or "Active, using your own key centres" under it, and Reset touch learning behind a confirmation while anything is stored, lab on or off. Delete what Hex learned clears it too. Every string in English and Simplified Chinese, the wording Ryan approved. - AdaptiveTouchTest (the one new test file, approved): what teaches it, the evidence floor, the grip fallback, key planes apart, the table and reset, untrained typing exactly as without it, and that your centres never correct a word the drawn ones leave alone. - docs/features: the Android Labs entry. Why: a tester asked for iPhone's adaptive touch on Android; Ryan approved it as a Labs switch knowing the gate shows 1-4% fewer word errors for typists who aim off the centres. Off, the keyboard makes no learner, reads no table and types exactly as before. Verified on the Studio (host JVM, Gradle --no-daemon, -x prepareSpeechModel): testDebugUnitTest passes, 310 tests with AdaptiveTouchTest's 11; scripts/code-shape.py --check has no hard problems. Not yet tried on an emulator or a device. * Privacy: say what Adaptive touch keeps, in the Android policy and on the site What: android/play/policy/privacy-policy.txt › What stays on your phone, and the Android section's "What Hex keeps" in site/src/iphone.ts: with Adaptive touch on in Labs, Hex keeps for each letter key an average of where taps land on it, in a table of fixed size (under 32 KB) on the phone only; no letters, words or order of taps; never sent; nothing learned from password, email or web address fields. Turning it off stops the learning but keeps the averages until Reset touch learning or Delete what Hex learned removes them. Why: the lab (previous commit) stores a new kind of learned data, and the policy and the site say what Hex keeps on the phone, as #2772 did for Learn from my fixes. Both texts are English only; the date stays November 24, 2026. Checked against the code: AdaptiveTouchStore keeps one "model" value in the private "adaptiveTouch" SharedPreferences (AdaptiveTouchModel.BYTES = 23,588 bytes, Base64), learning runs only where KeyboardEngine.teacher allows, and both Reset touch learning and Delete what Hex learned call AdaptiveTouchStore.clear(). Site: bun run build --mode production, then bun test, 25 pass; the built privacy page carries the sentence. * docs: Adaptive touch on the emulator What: the Android Labs entry for Labs › Keyboard › Adaptive touch now says what the emulator check showed, in place of "not yet tried on an emulator". Why: the coordinator asked for the functional emulator step before the pull request leaves draft. Verified on the Studio's API 35 Pixel 8 emulator (hex-touch-vogel, port 5890, now shut down), the debug build of8ac05c2fa, reading the table back through run-as after each step: words left as typed taught 10 weak labels, a same-length pick 5 picked, what was typed tapped over the fix 5 strong, an undone fix 3 strong, a retyped neighbour 1 strong and 3 weak; password and no-suggestion fields taught nothing; Reset touch learning and Delete what Hex learned each removed the table; landscape, the number row and AZERTY made their own contexts; with the switch off nothing learned and Reset stayed reachable. Active was reached by seeding the table, as AdaptiveTouchTest does. Time per letter not measured yet.
391 lines
26 KiB
Java
391 lines
26 KiB
Java
package local.hex.bench;
|
||
|
||
import ly.anoma.hex.typing.*;
|
||
import org.json.*;
|
||
import java.io.*;
|
||
import java.util.*;
|
||
|
||
/** Runs via app_process against the actual installed APK. Never built into Hex. */
|
||
public final class Replay {
|
||
static KeyGrid originalGeometry(String language) {
|
||
// Portrait KeyboardLayout at 402 pt (side 6.5, gap 6, letter height 45, row gap 11), and its
|
||
// space bar. German and Bokmål have Android's eleven-key rows at a 36 pt pitch; French is
|
||
// AZERTY, its bottom row's apostrophe key (never typed) left out of the letters.
|
||
boolean wide = language.equals("de") || language.equals("nb");
|
||
double pitch = wide ? 36 : 39.5; Map<Character,KeyPoint> points = new LinkedHashMap<>();
|
||
List<KeyRect> caps = new ArrayList<>(), cells = new ArrayList<>(); StringBuilder keys = new StringBuilder(); List<Integer> keyRows = new ArrayList<>();
|
||
String[] rows = language.equals("de") ? new String[]{"qwertzuiopü", "asdfghjklöä", "yxcvbnm"}
|
||
: language.equals("nb") ? new String[]{"qwertyuiopå", "asdfghjkløæ", "zxcvbnm"}
|
||
: language.equals("fr") ? new String[]{"azertyuiop", "qsdfghjklm", "wxcvbn'"}
|
||
: new String[]{"qwertyuiop", language.equals("es") ? "asdfghjklñ" : "asdfghjkl", "zxcvbnm"};
|
||
for (int row=0; row<rows.length; row++) {
|
||
String letters=rows[row];
|
||
for (int i=0; i<letters.length(); i++)
|
||
if (letters.charAt(i) != '\'') {
|
||
double x=201 + (i-(letters.length()-1)/2.0)*pitch, y=66.5+56*row;
|
||
points.put(letters.charAt(i),new KeyPoint(x,y));
|
||
// Adaptive touch's plane: keycaps 6 pt narrower than the pitch and 45 pt tall, touch cells tiling the rows.
|
||
keys.append(letters.charAt(i)); keyRows.add(row);
|
||
caps.add(new KeyRect(x-(pitch-6)/2, y-22.5, x+(pitch-6)/2, y+22.5));
|
||
cells.add(new KeyRect(x-pitch/2, y-28, x+pitch/2, y+28));
|
||
}
|
||
}
|
||
int[] rowOf=new int[keyRows.size()]; for(int i=0;i<rowOf.length;i++) rowOf[i]=keyRows.get(i);
|
||
TouchPlane plane=new TouchPlane("replay|"+language, keys.toString().toCharArray(), caps.toArray(new KeyRect[0]),
|
||
cells.toArray(new KeyRect[0]), rowOf, pitch, 56);
|
||
return new KeyGrid(points, pitch, 56, new KeyRect(64.76, 212, 303.1, 257), plane);
|
||
}
|
||
// A keyboard's own geometry, as the end-to-end check measures it on the emulator: key centres,
|
||
// pitches and the space bar, in the key plane's pixels.
|
||
static KeyGrid geometry(String path) throws Exception {
|
||
JSONObject g=new JSONObject(new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(path)),"UTF-8"));
|
||
Map<Character,KeyPoint> points=new LinkedHashMap<>(); JSONObject keys=g.getJSONObject("keys");
|
||
for(Iterator<String> it=keys.keys(); it.hasNext();) {
|
||
String k=it.next(); if(k.equals("'")) continue;
|
||
points.put(k.charAt(0),new KeyPoint(keys.getJSONArray(k).getDouble(0),keys.getJSONArray(k).getDouble(1)));
|
||
}
|
||
JSONObject cj=g.optJSONObject("cells");
|
||
if(cj!=null) {
|
||
cells=new HashMap<>(); density=g.getDouble("density");
|
||
for(Iterator<String> it=cj.keys(); it.hasNext();) {
|
||
String k=it.next(); JSONArray a=cj.getJSONArray(k);
|
||
cells.put(k.charAt(0),new double[]{a.getDouble(0),a.getDouble(1),a.getDouble(2),a.getDouble(3)});
|
||
}
|
||
}
|
||
JSONArray s=g.getJSONArray("space");
|
||
return new KeyGrid(points,g.getDouble("pitchX"),g.getDouble("pitchY"),new KeyRect(s.getDouble(0),s.getDouble(1),s.getDouble(2),s.getDouble(3)));
|
||
}
|
||
static String[] words(String s) {
|
||
return Arrays.stream(s.toLowerCase(Locale.ROOT).trim().split("\\s+"))
|
||
.map(w -> w.replaceAll("[.,!?;:]+$", "")).filter(w -> !w.isEmpty()).toArray(String[]::new);
|
||
}
|
||
static int edits(String[] ref, String[] hyp) {
|
||
int[] d = new int[hyp.length+1]; for(int j=0;j<d.length;j++) d[j]=j;
|
||
for(int i=1;i<=ref.length;i++) {
|
||
int prev=d[0]; d[0]=i;
|
||
for(int j=1;j<d.length;j++) {
|
||
int old=d[j]; d[j]=Math.min(Math.min(d[j]+1,d[j-1]+1),prev+(ref[i-1].equals(hyp[j-1])?0:1));
|
||
prev=old;
|
||
}
|
||
}
|
||
return d[hyp.length];
|
||
}
|
||
static void latency(String name, List<Long> ns) {
|
||
Collections.sort(ns);
|
||
System.out.printf(Locale.ROOT,"latency\t%s\t%d\t%.4f\t%.4f\t%.4f\n",
|
||
name,ns.size(),ns.get(ns.size()/2)/1e6,ns.get(ns.size()*95/100)/1e6,ns.get(ns.size()-1)/1e6);
|
||
}
|
||
// The strip as the keyboard shows it: strip() where the engine has it, else the old
|
||
// suggestions() with its literal chip.
|
||
static List<String> strip(TypingWord state) throws Exception {
|
||
List<String> out = new ArrayList<>();
|
||
try {
|
||
for (Object s : (List<?>) TypingWord.class.getMethod("strip", boolean.class).invoke(state, true))
|
||
out.add((String) s.getClass().getMethod("getText").invoke(s));
|
||
} catch (NoSuchMethodException old) {
|
||
List<String> words = state.suggestions(); String literal = state.literalChip(words);
|
||
if (literal != null) out.add(literal);
|
||
out.addAll(words);
|
||
}
|
||
return out;
|
||
}
|
||
@SuppressWarnings("unchecked")
|
||
static List<String> predictions(TypingWord state, String before) throws Exception {
|
||
try {
|
||
return (List<String>) TypingWord.class.getMethod("predictions", String.class, Boolean.class).invoke(state, before, null);
|
||
} catch (NoSuchMethodException old) {
|
||
return (List<String>) TypingWord.class.getMethod("predictions", String.class).invoke(state, before);
|
||
}
|
||
}
|
||
static boolean hit(List<String> slots, String word) {
|
||
for (String s : slots) if (s.toLowerCase(Locale.ROOT).replace('\u2019', '\'').equals(word)) return true;
|
||
return false;
|
||
}
|
||
// The replay geometry's touch areas tile each row: a key's centre ± half its pitch. A neighbouring
|
||
// letter within reach of the touch, by its distance to that area, in points (iOS's dp).
|
||
// A measured keyboard's touch cells (left, top, right, bottom) and pixels per dp; null and 1 for the
|
||
// benchmark's own layout, whose cells tile the rows around the centres and whose units are points.
|
||
static Map<Character,double[]> cells; static double density=1;
|
||
// French AZERTY's apostrophe key on the letter rows, which the keyboard reads as it reads the letters.
|
||
static KeyPoint apostropheKey;
|
||
static Map<Character,Double> near(KeyGrid grid, char hit, double x, double y) {
|
||
// KeyPlaneView.likelier: a shifted label uses the same cell, with shifted neighbours.
|
||
boolean shifted=Character.isUpperCase(hit); hit=Character.toLowerCase(hit);
|
||
Map<Character,Double> out = new HashMap<>();
|
||
if (cells != null) {
|
||
// As KeyPlaneView.likelier: the distance from the touch to each other letter's cell, in dp.
|
||
for (Map.Entry<Character,double[]> e : cells.entrySet()) {
|
||
if (e.getKey() == hit) continue;
|
||
double[] c = e.getValue();
|
||
double dx = Math.max(Math.max(c[0] - x, 0), x - c[2]), dy = Math.max(Math.max(c[1] - y, 0), y - c[3]);
|
||
double d = Math.hypot(dx, dy) / density;
|
||
if (d < TypingWord.REACH) out.put(shifted ? Character.toUpperCase(e.getKey()) : e.getKey(), d);
|
||
}
|
||
return out;
|
||
}
|
||
Map<Character,KeyPoint> keys = new HashMap<>(grid.getCentres());
|
||
if (apostropheKey != null) keys.put('\'', apostropheKey);
|
||
for (Map.Entry<Character,KeyPoint> e : keys.entrySet()) {
|
||
if (e.getKey() == hit) continue;
|
||
KeyPoint c = e.getValue();
|
||
double dx = Math.max(0, Math.abs(x - c.getX()) - grid.getPitchX() / 2), dy = Math.max(0, Math.abs(y - c.getY()) - grid.getPitchY() / 2);
|
||
double d = Math.sqrt(dx * dx + dy * dy);
|
||
if (d < TypingWord.REACH) out.put(shifted ? Character.toUpperCase(e.getKey()) : e.getKey(), d);
|
||
}
|
||
return out;
|
||
}
|
||
// Whether a letter after `before` starts a word the keyboard reads (startsWord, else a boundary).
|
||
static boolean startsWord(TypingWord state, String before) throws Exception {
|
||
try {
|
||
return (Boolean) TypingWord.class.getMethod("startsWord", String.class).invoke(state, before);
|
||
} catch (NoSuchMethodException old) {
|
||
return TypingWord.Companion.boundary(before.isEmpty() ? null : before.charAt(before.length() - 1));
|
||
}
|
||
}
|
||
static boolean letterOdds = true;
|
||
static char likelierKey(TypingWord state, String before, char hit, double x, double y, KeyGrid grid) throws Exception {
|
||
if (!letterOdds) return hit;
|
||
try {
|
||
java.lang.reflect.Method m = TypingWord.class.getMethod("likelierKey", String.class, char.class, Map.class, Collection.class);
|
||
return (Character) m.invoke(state, before, hit, near(grid, hit, x, y), grid.getCentres().keySet());
|
||
} catch (NoSuchMethodException old) { return hit; }
|
||
}
|
||
// Labs › Keyboard › Adaptive touch for `--adaptive learn|monitor|frozen`, from `--profile-in` or nothing learned,
|
||
// its guard off with `--unguarded 1`; null without it.
|
||
static AdaptiveTouch adaptive(Map<String,String> o) throws IOException {
|
||
String mode=o.get("--adaptive"); if(mode==null) return null;
|
||
String in=o.get("--profile-in");
|
||
AdaptiveTouchModel learned=in==null ? new AdaptiveTouchModel()
|
||
: AdaptiveTouchModel.Companion.from(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(in)));
|
||
if(learned==null) throw new IllegalArgumentException("Unreadable profile "+in);
|
||
AdaptiveTouch a=new AdaptiveTouch(learned);
|
||
a.setMode(AdaptiveTouch.Mode.valueOf(Character.toUpperCase(mode.charAt(0))+mode.substring(1)));
|
||
a.setGuards(!o.containsKey("--unguarded"));
|
||
return a;
|
||
}
|
||
// Where a typist aims off a key's centre, in points: T1 low and right; T1m low and left (T1 in a mirror, another
|
||
// grip); T2 thumbs reaching inward, low; T3 a fixed aim of its own for every key, drawn once.
|
||
static double[] bias(String typist, char letter, KeyGrid grid) {
|
||
double w=grid.getPitchX()-6, h=45;
|
||
KeyPoint c=grid.getCentres().get(letter);
|
||
switch(typist) {
|
||
case "T1": return new double[]{.2*w,.2*h};
|
||
case "T1m": return new double[]{-.2*w,.2*h};
|
||
case "T2": return new double[]{(c.getX()<201 ? .2 : -.2)*w,.1*h};
|
||
case "T3": {
|
||
// One generator for all the keys, in letter order: generators seeded one apart start alike.
|
||
if(aims==null) {
|
||
aims=new HashMap<>(); Random r=new Random(20261124L);
|
||
for(char k:new TreeSet<>(grid.getCentres().keySet())) aims.put(k,new double[]{r.nextGaussian()*.12*w,r.nextGaussian()*.12*h});
|
||
}
|
||
return aims.get(letter);
|
||
}
|
||
default: throw new IllegalArgumentException("Unknown typist "+typist);
|
||
}
|
||
}
|
||
static Map<Character,double[]> aims;
|
||
// The letter whose touch cell holds (x, y), the nearest row's and key's: a tap aimed at a letter stays on the letters.
|
||
static char letterAt(KeyGrid grid, double x, double y) {
|
||
double row=Double.NaN, best=Double.POSITIVE_INFINITY;
|
||
for(KeyPoint p:grid.getCentres().values()) if(Math.abs(p.getY()-y)<best) { best=Math.abs(p.getY()-y); row=p.getY(); }
|
||
char out=0; best=Double.POSITIVE_INFINITY;
|
||
for(Map.Entry<Character,KeyPoint> e:grid.getCentres().entrySet())
|
||
if(e.getValue().getY()==row && Math.abs(e.getValue().getX()-x)<best) { best=Math.abs(e.getValue().getX()-x); out=e.getKey(); }
|
||
return out;
|
||
}
|
||
// What a space tells Adaptive touch, as the keyboard does: the word as typed, whether autocorrect replaced it or
|
||
// revised the word before, and nothing at all from two words joined.
|
||
static void finishWord(AdaptiveTouch adaptive, String token, String before, Correction fix) {
|
||
String typed=token.isEmpty() ? null : token;
|
||
if(fix==null) { adaptive.finish(typed, before, null, false); return; }
|
||
String original=fix.getOriginal(), replacement=fix.getReplacement();
|
||
if(original.contains(" ") && !replacement.contains(" ")) { adaptive.forget(); return; }
|
||
boolean kept=replacement.equals(token) || replacement.endsWith(" "+token);
|
||
adaptive.finish(typed, before, kept ? null : replacement, original.contains(" "));
|
||
}
|
||
// On stderr, so the gate's lines stay one per sentence: when the personal centres came into use, and each context.
|
||
static int inUse(AdaptiveTouch adaptive) {
|
||
AdaptiveTouchModel.Context[] contexts=adaptive.getModel().getContexts();
|
||
for(int c=0;c<contexts.length;c++) if(contexts[c].getInUse()) return c;
|
||
return -1;
|
||
}
|
||
static void report(AdaptiveTouch adaptive, Map<String,String> o, int activeFrom, int startUse, CharSequence uses, int sentences) throws IOException {
|
||
String out=o.get("--profile-out");
|
||
if(out!=null) java.nio.file.Files.write(java.nio.file.Paths.get(out), adaptive.getModel().serialized());
|
||
System.err.printf(Locale.ROOT,"adaptive\tactive_from\t%d\tactive_end\t%b\tsentences\t%d%n",activeFrom,adaptive.isActive(),sentences);
|
||
System.err.println("uses\t"+startUse+"\t"+uses);
|
||
AdaptiveTouchModel m=adaptive.getModel();
|
||
for(int c=0;c<AdaptiveTouchModel.CONTEXTS;c++) {
|
||
AdaptiveTouchModel.Context x=m.getContexts()[c];
|
||
if(x.getGeometry()==0) continue;
|
||
double mx=0, my=0; int n=adaptive.getPlane()==null ? 0 : adaptive.getPlane().getLetters().length;
|
||
for(int s=0;s<n;s++) { mx+=m.offsetX(c,s); my+=m.offsetY(c,s); }
|
||
System.err.printf(Locale.ROOT,"context\t%d\tregime\t%d\taccepted\t%d\tweak\t%d\tpicked\t%d\tstrong\t%d\tsessions\t%d\tpromotions\t%d\tin_use\t%b\tlearning\t%b\tmean_offset\t%.3f\t%.3f%n",
|
||
c,x.getRegime(),x.getAccepted(),x.getWeak(),x.getPicked(),x.getStrong(),x.getSessions(),x.getPromotions(),x.getInUse(),x.getLearning(),n>0?mx/n:0,n>0?my/n:0);
|
||
}
|
||
}
|
||
// `memory MODEL SET LANG ...`: every language's replay in one process, each kept loaded, then the
|
||
// process's resident memory with all of them, against before the first.
|
||
static final List<Object> kept=new ArrayList<>();
|
||
static String memory() throws IOException {
|
||
StringBuilder b=new StringBuilder();
|
||
for(String l:java.nio.file.Files.readAllLines(java.nio.file.Paths.get("/proc/self/status")))
|
||
if(l.startsWith("VmRSS")||l.startsWith("RssAnon")||l.startsWith("RssFile")) b.append(l.replaceAll("\\s+"," ")).append("; ");
|
||
for(String l:java.nio.file.Files.readAllLines(java.nio.file.Paths.get("/proc/self/smaps_rollup")))
|
||
if(l.startsWith("Pss:")) b.append(l.replaceAll("\\s+"," "));
|
||
return b.toString();
|
||
}
|
||
public static void main(String[] args) throws Exception {
|
||
if(args[0].equals("memory")) {
|
||
System.out.println("memory\tbefore\t"+memory());
|
||
for(int i=1;i+2<args.length;i+=3) replay(new String[]{args[i],args[i+1],args[i+2]});
|
||
System.gc();
|
||
System.out.println("memory\tall loaded\t"+memory());
|
||
return;
|
||
}
|
||
replay(args);
|
||
}
|
||
static void replay(String[] args) throws Exception {
|
||
String lang=args[2], group=lang.equals("en") ? "test-" : lang+"-test-";
|
||
boolean gate=args.length>=4 && args[3].equals("--gate");
|
||
PrintWriter outputs=!gate && args.length>3 ? new PrintWriter(new FileWriter(args[3])) : null;
|
||
boolean hasIos=false;
|
||
TypingModel model=TypingModel.Companion.file(new File(args[0]),lang);
|
||
// `MODEL SET LANG OUT [GEOMETRY]`: with a measured geometry, any number of sentences.
|
||
KeyGrid grid=!gate && args.length>4 ? geometry(args[4]) : originalGeometry(lang); TypingWord state=new TypingWord(new SpatialDecoder(model), true);
|
||
// `--gate` options for Labs › Keyboard › Adaptive touch's checks (quality-gate.py --adaptive): a typist who aims
|
||
// off the centres, and Adaptive touch learning as the keyboard does, or reading a profile learned before.
|
||
Map<String,String> options=new HashMap<>();
|
||
for(int i=4;gate&&i+1<args.length;i+=2) options.put(args[i],args[i+1]);
|
||
String typist=options.get("--typist");
|
||
AdaptiveTouch adaptive=adaptive(options);
|
||
int sessionEvery=Integer.parseInt(options.getOrDefault("--sessions","0")), sentence=0, activeFrom=-1;
|
||
StringBuilder uses=new StringBuilder();
|
||
double[] now={0};
|
||
if(adaptive!=null) { state.setAdaptive(adaptive); adaptive.setClock(() -> now[0]); adaptive.beginSession(); }
|
||
int startUse=adaptive==null ? -1 : inUse(adaptive);
|
||
apostropheKey=lang.equals("fr")&&cells==null ? new KeyPoint(201+3*39.5,66.5+56*2) : null;
|
||
boolean apostropheOnLetters=lang.equals("fr");
|
||
kept.add(state);
|
||
List<Long> letters=new ArrayList<>(), spaces=new ArrayList<>();
|
||
int count=0, total=0, matches=0; int[] errors=new int[3], exact=new int[3];
|
||
// Strip hits, as iOS's harness counts them: the intended word among the slots once its last
|
||
// letter is typed, after its first two letters (words of three or more), and among the
|
||
// predictions after the space before it.
|
||
int[] hits=new int[6];
|
||
try (BufferedReader reader=new BufferedReader(new FileReader(args[1]))) {
|
||
String line;
|
||
while((line=reader.readLine())!=null) {
|
||
// Gate input is TSV so the host JVM needs no Android JSON implementation.
|
||
// No coordinates means exact centre taps, including explicit long-press letters.
|
||
String[] fields=gate ? line.split("\\t", -1) : null;
|
||
JSONObject r=gate ? null : new JSONObject(line);
|
||
if(!gate && !r.getString("id").equals(group+count)) throw new IllegalArgumentException("Unexpected row "+count);
|
||
String typed=gate ? fields[0] : r.getString("typed"); JSONArray taps=gate ? null : r.getJSONArray("taps");
|
||
String[] points=gate && fields.length==2 ? fields[1].split(" ") : null;
|
||
if((!gate && typed.length()!=taps.length()) || (points!=null && typed.length()!=points.length)) throw new IllegalArgumentException("Unaligned taps");
|
||
StringBuilder out=new StringBuilder(); state.reset("");
|
||
if(adaptive!=null) {
|
||
// Each sentence is a field of its own, typed a few seconds after the last.
|
||
now[0]+=5; adaptive.forget();
|
||
if(sessionEvery>0 && sentence>0 && sentence%sessionEvery==0) adaptive.beginSession();
|
||
}
|
||
String[] planned=gate ? null : r.getString("intended").toLowerCase(Locale.ROOT).split(" ");
|
||
Map<Integer,Integer> ends=new HashMap<>(), early=new HashMap<>();
|
||
String want=gate ? "" : r.optString("want","");
|
||
JSONArray endList=gate ? null : r.optJSONArray("ends");
|
||
if(endList!=null) for(int j=0, from=0;j<endList.length();j++) {
|
||
int end=endList.getInt(j); ends.put(end,j);
|
||
if(end-from>=3) early.put(from+2,j);
|
||
from=end+(end<want.length()&&want.charAt(end)==' '?1:0);
|
||
}
|
||
List<String> shown=Collections.emptyList();
|
||
// As the keyboard: a letter starts a word it reads only after a space, an opening
|
||
// mark or (French, Italian) an elision; anything else is typed as it is until the next
|
||
// space. An apostrophe ends the word as typed.
|
||
boolean tracked=true;
|
||
for(int i=0;i<typed.length();i++) {
|
||
char key=typed.charAt(i); double x, y;
|
||
boolean explicit=false;
|
||
if(!gate) { x=taps.getJSONArray(i).getDouble(0); y=taps.getJSONArray(i).getDouble(1); }
|
||
else if(points!=null) {
|
||
String[] xy=points[i].split(","); x=Double.parseDouble(xy[0]); y=Double.parseDouble(xy[1]);
|
||
} else {
|
||
KeyPoint p=grid.getCentres().get(Character.toLowerCase(key));
|
||
if(key==' ') { KeyRect space=grid.getSpace(); p=new KeyPoint((space.getLeft()+space.getRight())/2,space.getCentreY()); }
|
||
if(key=='\'') p=apostropheKey;
|
||
explicit=p==null && Character.isLetter(key); // IME long-press choice: w.explicit, no spatial evidence
|
||
x=p==null ? 0 : p.getX(); y=p==null ? 0 : p.getY();
|
||
}
|
||
if(typist!=null && !explicit && Character.isLetter(key) && grid.getCentres().containsKey(Character.toLowerCase(key))) {
|
||
// The typist's own aim moves the tap, and the key under it types.
|
||
double[] b=bias(typist, Character.toLowerCase(key), grid);
|
||
x+=b[0]; y+=b[1];
|
||
char under=letterAt(grid, x, y);
|
||
key=Character.isUpperCase(key) ? Character.toUpperCase(under) : under;
|
||
}
|
||
now[0]+=.25;
|
||
long start=System.nanoTime();
|
||
// As the keyboard: a touch on a letter key, or on French's apostrophe key among them, types
|
||
// the likelier neighbour when it is near enough (the engine leaves a word it isn't reading alone).
|
||
if(!explicit && (Character.isLetter(key)||(key=='\''&&apostropheOnLetters))) key=likelierKey(state,out.toString(),key,x,y,grid);
|
||
if(key!=' '&&!Character.isLetter(key)) {
|
||
if(adaptive!=null) adaptive.finish(state.getToken().isEmpty() ? null : state.getToken(), out.toString(), null, false);
|
||
out.append(key); state.reset(out.toString()); tracked=false; shown=Collections.emptyList();
|
||
} else if(key==' '&&!tracked) {
|
||
if(adaptive!=null) adaptive.forget();
|
||
out.append(' '); String before=out.toString(); state.reset(before); if(!gate) shown=predictions(state,before); tracked=true;
|
||
} else if(key!=' '&&state.getToken().isEmpty()&&!startsWord(state,out.toString())&&!(tracked&&out.length()==0)) {
|
||
if(adaptive!=null) adaptive.forget();
|
||
out.append(key); tracked=false; shown=Collections.emptyList();
|
||
} else if(key==' ') {
|
||
String token=state.getToken(), before=out.toString();
|
||
Correction fix=state.finish(' ',new KeyPoint(x,y),grid,word->word); // Labs › Smart quotes off, as by default
|
||
if(fix!=null) {
|
||
if(!out.toString().endsWith(fix.getOriginal())) throw new IllegalStateException("Correction off the text");
|
||
out.replace(out.length()-fix.getOriginal().length(),out.length(),fix.getReplacement());
|
||
}
|
||
if(adaptive!=null) finishWord(adaptive, token, before, fix);
|
||
out.append(' '); before=out.toString(); state.reset(before); if(!gate) shown=predictions(state,before);
|
||
} else {
|
||
tracked=true;
|
||
if(explicit) { state.explicit(String.valueOf(key)); if(adaptive!=null) adaptive.untapped(); }
|
||
else {
|
||
state.letter(String.valueOf(key),x,y,grid);
|
||
if(adaptive!=null) adaptive.typed(key,x,y,grid,true);
|
||
}
|
||
out.append(key); if(!gate) shown=strip(state);
|
||
}
|
||
if(gate) continue;
|
||
(key==' '?spaces:letters).add(System.nanoTime()-start);
|
||
Integer j;
|
||
if((j=early.get(i+1))!=null) { hits[4]+=hit(shown,planned[j])?1:0; hits[5]++; }
|
||
if((j=ends.get(i+1))!=null) { hits[0]+=hit(shown,planned[j])?1:0; hits[1]++; }
|
||
if(i<want.length()&&want.charAt(i)==' '&&(j=ends.get(i))!=null&&j+1<planned.length) {
|
||
hits[2]+=hit(shown,planned[j+1])?1:0; hits[3]++;
|
||
}
|
||
}
|
||
if(adaptive!=null && activeFrom<0 && adaptive.isActive()) activeFrom=sentence;
|
||
// Which context's centres were in use after each sentence (-1: the drawn ones).
|
||
if(adaptive!=null) uses.append(sentence>0 ? "," : "").append(inUse(adaptive));
|
||
sentence++;
|
||
if(gate) { System.out.println(out.toString().trim()); continue; }
|
||
String[] ref=words(r.getString("intended")); total+=ref.length; count++;
|
||
String ios=r.getString("ios_shared"); hasIos|=!ios.isEmpty();
|
||
if(outputs!=null) outputs.println(r.getString("id")+"\t"+out.toString().trim());
|
||
if (Arrays.equals(words(ios),words(out.toString()))) matches++;
|
||
String[] results={typed,ios,out.toString()};
|
||
for(int i=0;i<3;i++) { int err=edits(ref,words(results[i])); errors[i]+=err; if(err==0) exact[i]++; }
|
||
}
|
||
}
|
||
if(gate) { if(adaptive!=null) report(adaptive, options, activeFrom, startUse, uses, sentence); return; }
|
||
if(count!=2000&&args.length<=4) throw new IllegalArgumentException("Incomplete synthetic set: "+count);
|
||
if(outputs!=null) outputs.close();
|
||
String[] names={"raw","ios_shared","android_spatial"};
|
||
for(int i=0;i<3;i++) if(i!=1||hasIos)
|
||
System.out.printf(Locale.ROOT,"wer\t%s\t%d\t%d\t%.4f\t%d/%d\n",lang+"_"+names[i],errors[i],total,100.0*errors[i]/total,exact[i],count);
|
||
if(hasIos) System.out.printf("agreement\t%s\t%d/%d\n",lang,matches,count);
|
||
if(hits[1]>0) System.out.printf("strip\t%s\tword %d/%d\tnext %d/%d\tafter two letters %d/%d\n",lang,hits[0],hits[1],hits[2],hits[3],hits[4],hits[5]);
|
||
latency(lang+"_letter",letters); latency(lang+"_space",spaces);
|
||
}
|
||
}
|