hex/android/benchmark/typing/swipe-bench.py
Ryan Vogel 52fde4b773
android: swipe typing (#2599)
* android: swipe typing (Keyboard › Swipe typing, on)

Slide from a letter through a word's letters and lift: the word goes in.
People asked for it at launch (four replies, "a must"); iPhone Hex has it.

What changed
- typing/SwipeDecoder.kt: iPhone Hex's SwipeDecoder (SHARK2-style shape
  matching with DTW, turn and pause evidence, the word-pair model) ported
  to Kotlin with the same parameters, reading the mapped HXTM model in
  place, so it may run off the main thread. Letters without a key read
  through the keys people swipe (ß on s, French œ/æ on o-e/a-e); iPhone
  drops those words. SwipeReader adds English's contractions and your
  personal-dictionary words and ranks rare names lower (not German, whose
  capitals list marks nouns).
- keyboard/KeyPlaneView.kt, SwipeTyping.kt: a letter touch that travels a
  key's pitch becomes a swipe; its key no longer types, a trail in the
  keys' ink follows the finger and the strip shows the word so far (read
  off the main thread every 70 ms). Lifting reads it on the main thread.
  A drag back to its own key is a tap that slid; another key going down
  finishes the swipe first. Shift/?123 slides, accents, the space bar's
  cursor and Delete's slide are unchanged.
- keyboard/KeyboardEngine.kt: the word goes in after a space unless the
  text ends in one or in opening punctuation, with a capital from shift or
  the sentence; the strip offers the next three readings. A tapped letter
  goes in after a pending space, closing marks against the word; space
  never autocorrects or text-replaces it. Delete right after takes the
  whole word back as Gboard's does (black box, API 36 emulator): the space
  before it stays, the strip offers the word again, and the next swipe
  there types its next reading. iPhone also takes the space; Gboard wins
  where they differ.
- Settings › Keyboard › Swipe typing (TypingPreferences.swipe, default on,
  as on iPhone and Gboard), English and Chinese strings.
- benchmark/typing: swipe_paths.py (the iPhone benchmark's path generator,
  ported; matches the Swift one to 5e-6 pitch), SwipeReplay.java and
  swipe-bench.py (host JVM or --device), README section with results.

Verified
- Same held-out paths as the iPhone replay: Android's decoder gives the
  identical top four for all 12,514 English and 12,346 Spanish swipes.
  First word right / typed or in the strip: en 96.9/99.6, es 94.3/99.4,
  de 95.9/99.4, nb 96.4/99.3, fr 95.2/99.3, it 96.0/99.3.
- API 36 emulator (app_process against the APK): 1.0-1.4 ms median and
  3.5-5.2 ms p99 per swipe.
- quality-gate.py all: report identical field for field to origin/dev's.
- testDebugUnitTest green; cases added to NeverSuggestTest and
  InsertionTest only.
- In Messages on the emulator, injected swipes: spacing, capitals,
  punctuation, Delete and swipe-again behave as above.

* android: swipe typing notes: iPhone's German pitch, ß words, the tap check

The iPhone replay disagreed with Android on German because iPhone's
TypingDecoder.Keys gives German's eleven-key rows a ten-column pitch
(38.3 pt for 34.8 pt keys); with it corrected the first readings agree on
all 13,206 swipes. Android's ß-through-s reading costs 0.1 point on the
held-out set, which has no ß, and reads 71.4% of ß words first (98.3% in
the strip) on accent-de.tsv, where iPhone reads none. The on/off tap check
in Messages: 29 of 30 sentences identical, the one difference a tap lost
right after the keyboard restarted, not reproduced on retyping.

Docs only.
2026-11-23 18:01:14 -05:00

81 lines
4.9 KiB
Python
Executable file

#!/usr/bin/env python3
"""Score swipe typing on synthetic paths: how often the first word is right, how often the word is typed or in
the strip (top 4), and the time per swipe. The paths are swipe_paths.py's, the same ones the iPhone replay reads,
from the held-out sentences; each is decoded by the keyboard's own SwipeReader (SwipeReplay.java) on the host
JVM, or with --device on an emulator or phone against the installed APK, as replay.sh runs the tap replay.
android/benchmark/typing/swipe-bench.py [LANG ...] [--noise typical] [--device SERIAL] [--out DIR]
"""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
HERE = Path(__file__).resolve().parent
ANDROID = HERE.parents[1]
MODELS = ANDROID / 'app/src/main/assets/typing'
LANGUAGES = ['en', 'es', 'de', 'nb', 'fr', 'it']
def paths(lang, noise, out):
"""The path set, made once per language and noise."""
target = out / f'{lang}-{noise}.tsv.gz'
if not target.is_file():
subprocess.run(['python3', HERE / 'swipe_paths.py', lang, target, '--noise', noise], check=True)
return target
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('languages', nargs='*', help=' '.join(LANGUAGES) + ' (default: all)')
parser.add_argument('--noise', default='typical', choices=['typical', 'neat', 'sloppy', 'none'])
parser.add_argument('--device', help='adb serial: run on the device against the installed APK')
parser.add_argument('--out', type=Path, default=ANDROID / 'build/swipe-bench')
args = parser.parse_args()
if not set(args.languages) <= set(LANGUAGES):
parser.error('languages: ' + ' '.join(LANGUAGES))
args.languages = args.languages or LANGUAGES
args.out.mkdir(parents=True, exist_ok=True)
jdk = Path(os.environ['JAVA_HOME']) / 'bin' if 'JAVA_HOME' in os.environ else Path('')
with tempfile.TemporaryDirectory() as scratch:
tmp = Path(scratch)
cp = tmp / 'classpath'
subprocess.run([ANDROID / 'gradlew', '-q', '-I', HERE / 'gate-classpath.gradle', ':app:typingGateClasspath',
'-x', 'prepareSpeechModel', '-PgateClasspath=' + str(cp)], cwd=ANDROID, check=True)
classes = tmp / 'classes'
subprocess.run([jdk / 'javac', '-encoding', 'UTF-8', '--release', '8', '-Xlint:-options', '-cp', cp.read_text(), '-d', classes,
HERE / 'SwipeReplay.java'], check=True)
if args.device:
adb = ['adb', '-s', args.device]
sdk = Path(os.environ['ANDROID_HOME'])
lib = sdk / 'platforms/android-36/android.jar'
tools = max((sdk / 'build-tools').iterdir())
subprocess.run([jdk / 'jar', 'cf', tmp / 'replay.jar', '-C', classes, '.'], check=True)
subprocess.run([tools / 'd8', '--min-api', '31', '--lib', lib, '--output', tmp / 'replay-dex.jar', tmp / 'replay.jar'], check=True)
dev = '/data/local/tmp/hex-swipe'
subprocess.run(adb + ['shell', 'mkdir', '-p', dev], check=True)
subprocess.run(adb + ['push', tmp / 'replay-dex.jar', dev + '/replay.jar'], check=True, capture_output=True)
subprocess.run(adb + ['push', MODELS / 'never-suggest.tsv', dev], check=True, capture_output=True)
apk = subprocess.check_output(adb + ['shell', 'pm', 'path', 'ly.anoma.hex'], text=True).strip().removeprefix('package:')
for lang in args.languages:
source = paths(lang, args.noise, args.out)
words = args.out / f'{lang}-{args.noise}-words.tsv'
if args.device:
for side in ['hextm', 'capitals', 'valid']:
subprocess.run(adb + ['shell', 'rm', '-f', f'{dev}/{lang}.{side}'], check=True)
if (MODELS / f'{lang}.{side}').is_file():
subprocess.run(adb + ['push', MODELS / f'{lang}.{side}', dev], check=True, capture_output=True)
subprocess.run(adb + ['push', source, f'{dev}/{source.name}'], check=True, capture_output=True)
report = subprocess.check_output(adb + ['shell', f'CLASSPATH={dev}/replay.jar:{apk} app_process /system/bin '
f'local.hex.bench.SwipeReplay {dev}/{lang}.hextm {lang} {dev}/{source.name} {dev}/words.tsv'], text=True)
subprocess.run(adb + ['shell', 'rm', f'{dev}/{source.name}'], check=True)
subprocess.run(adb + ['pull', dev + '/words.tsv', words], check=True, capture_output=True)
else:
report = subprocess.check_output([jdk / 'java', '-Xmx1g', '-Dfile.encoding=UTF-8', '-cp', str(classes) + os.pathsep + cp.read_text(),
'local.hex.bench.SwipeReplay', MODELS / f'{lang}.hextm', lang, source, words], text=True)
(args.out / f'{lang}-{args.noise}{"-device" if args.device else ""}.txt').write_text(report)
print(report, flush=True)
main()