hex/ios/HEXMobileTests/CleanupTaggerTests.swift
Ryan Vogel 1ede7bb792
iOS: Spanish clean-up, paste translated or as spoken, screen stays on while recording (#2046)
* iOS: keep the screen on while Hex records or transcribes

A Spanish-speaking TestFlight tester (build 20) asked that the screen not
turn off while recording. DictationController now sets
UIApplication.isIdleTimerDisabled whenever its phase is recording or
transcribing, and clears it when the phase leaves those states (done,
cancel, failure), so Auto-Lock comes back after every dictation. Nothing
else in Hex sets the flag.

Limits: iOS honors the flag only while Hex is the foreground app (the
handoff screen and in-app recording). A warm-session or in-keyboard
dictation happens with another app in front, and a keyboard extension has
no public API to keep the screen on, so those can still dim. No private API
or value(forKey:) workaround is used.

Verified: new DictationControllerTests.testRecordingAndTranscribingKeepTheScreenOn
(recording, transcribing, done, cancel, failed) and the rest of
DictationControllerTests pass on an iPhone 18 Pro simulator (iOS 27.2).

* iOS: Spanish, German and Norwegian rules for Clean up what I say

A Spanish-speaking TestFlight tester said the corrections part works badly
in Spanish. Clean up what I say ran its cleanup tagger only for English and
returned every other language untouched, so with the experiment on a Spanish
dictation kept its fillers and spoken corrections. The tagger stays
English-only: run directly on Spanish, it changed the meaning of 8 of 18
sentences, including dropped negations ("Te digo que no puedo ir." became
"Te puedo ir.", "O sea que al final no vienes." became "O sea que vienes.").

- New SpokenCleanupRules: for es, de and nb/nn/no, a filler between commas
  goes ("este", "o sea"), and a correction marker set off by commas ("digo",
  "perdón", "no", "no, espera", "mejor dicho"; "nein", "ich meine"; "nei",
  "nei vent", "jeg mener") drops the words it replaces. Those are counted
  back to the nearest earlier word that matches the repair's first word, or
  is of its kind (number, weekday, month, today or tomorrow), within the
  sentence and 8 words; with neither, nothing changes. "mejor dicho", "no
  mejor", "besser gesagt" and "rettere sagt" also count without commas.
  Like the tagger, it only removes words; CleanupReconstruction repairs
  commas and capitals.
- CleanupTagger.cleanIfEnabled runs those rules for non-English languages
  instead of returning the text unchanged. The model still never loads for
  them, and Verbatim still skips cleanup.
- TranscriptFormatter: the styles trim Spanish hesitations (eh, em, mmm;
  never "e") and German ones (äh, ähm, öhm; never "eh"), and capitalize a
  sentence that opens with ¿ or ¡.

Measured on 25 Spanish sentences I wrote, with Polished and the experiment
on (9 German and Norwegian ones too). Before, every sentence came out as
spoken. After, all 13 with fillers or corrections are cleaned ("Eh, nos
vemos mañana a las 3, digo, a las 4." -> "Nos vemos mañana a las 4.") and
all 12 that use the same words in their ordinary meaning stay unchanged
("Te digo que no puedo ir.", "Quiero este, el azul.", "Lo siento, perdón,
Ana.").

Verified: new SpokenCleanupRulesTests, updated
CleanupTaggerTests.testOtherLanguagesGetRulesNeverTheEnglishTagger (it
used to expect Norwegian "tirsdag, nei vent, torsdag" untouched), plus the
CleanupTagger, DictationController and TranscriptCleanup suites, all
passing on an iPhone 18 Pro simulator (iOS 27.2).

* iOS: Clean up what I say drops Spanish, German and Norwegian hesitations

In-keyboard dictation (iOS 26+) inserts Apple Speech's text without running
a style through TranscriptFormatter, so the Spanish and German hesitation
trim added to the styles in 71acb4f3 never reached it. The English tagger
removes "um" and "uh" in both places. SpokenCleanupRules now also drops the
language's hesitation sounds anywhere in the sentence, using the styles'
own list (TranscriptFormatter.fillerPattern): eh, em, mmm in Spanish; äh,
ähm, öhm in German; eh, ehm, øh, hm in Norwegian. A sound that asks or
exclaims ("¿eh?", "eh?", "¡Eh, tú!") stays.

Correction to 71acb4f3's message: on the 25 Spanish sentences, 14 (not 13)
came out cleaned and 11 (not 12) stayed unchanged; nothing else differs.

Verified: SpokenCleanupRulesTests (with "Mmm, creo que sí, eh, pero..." ->
"Creo que sí, pero...", "No te olvides, ¿eh?" and "Padre e hijo." kept,
Norwegian "Eh," and German "Äh," removed, German "eh egal" kept) and
CleanupTaggerTests pass on an iPhone 18 Pro simulator (iOS 27.2).

* iOS: choose per dictation whether Translate what I say pastes translated

A Spanish-speaking TestFlight tester liked Translate what I say but always
speaks Spanish and only sometimes wants the English. Until now translation
was all or nothing, set in Experiments.

- DictationTranslationSettings.pastesTranslation (App Group key
  experiments.translateDictation.pastesTranslation, default true, so
  existing users still get translations) is a switch that keeps the last
  choice. translateIfEnabled skips translation while it says as spoken, in
  the app (warm session, handoff, Action Button) and in in-keyboard
  dictation alike.
- TranslationPasteChoice names both sides in English, like the rest of
  Hex's copy: "Paste in English" / "Paste in Spanish" ("Paste as spoken"
  when the dictation language is unknown, "Norwegian" without "Bokmål").
  It exists only while the experiment is on, the keyboard has Full Access,
  and you dictate in a language other than the target.
- Full keyboard: the Hex key menu gets two rows under Language, each with a
  checkmark, and the space bar reads "Español → English" while dictations
  paste translated.
- Dictation bar: the language tray gets a "Paste in English" chip, lit
  while translating, and the language label reads "Español → English". The
  label now has layout priority so it isn't cut to "Español → E…".
- Settings: a "Paste in English" toggle under Insert in mirrors the switch.
  Turning the experiment on resets it to translated.
- Simulator fixtures: --translate-to <code> and --paste-as-spoken.

Verified: new TranslationPasteSwitchTests (titles and visibility, the
remembered choice, as spoken skipping translation, the model's label, and
the Hex key menu's rows, their checkmarks and their callback). Full
xcodebuild test: 230 tests, 0 failures, 1 skipped (AppleSpeechClipTests).
Rendered on an iPhone 18 Pro simulator (iOS 27.2): full-keyboard-style in
light and dark, translated and as spoken, without translation (unchanged),
full-keyboard-idle, keyboard-language, keyboard-warm, keyboard-recording and
experiments. The simulator can't actually translate (Apple's
LanguageAvailability says es -> en is unsupported there), so a translated
paste is unverified on device.
2026-11-20 14:39:28 +00:00

367 lines
18 KiB
Swift

import UIKit
import XCTest
@testable import HEX
/// Clean up what I say: the Swift tokenizer, Core ML model, and reconstruction against
/// fixtures generated by the tagger's reference pipeline (`train/ios_fixtures.py` in the
/// training experiment): Hugging Face's BertTokenizer, ONNX int8 and the fp32 PyTorch
/// checkpoint at the 0.98 threshold, and `js/reconstruct.js`.
final class CleanupTaggerTests: XCTestCase {
private struct HandwrittenFixture: Decodable {
struct Case: Decodable {
let id: Int
let category: String
let input: String
/// ONNX int8 labels at the threshold, rebuilt with the reference reconstruct.
let expected: String
/// The hand-written ideal cleanup.
let target: String
let labels: [Int]
let pDelete: [Double]
let checkpointLabels: [Int]
let checkpointPDelete: [Double]
}
let threshold: Double
let cases: [Case]
}
private struct TokenizerFixture: Decodable {
struct Case: Decodable {
let word: String
let ids: [Int32]
}
let cases: [Case]
}
private struct ReconstructFixture: Decodable {
struct Case: Decodable {
let words: [String]
let labels: [Int]
let output: String
}
let cases: [Case]
}
/// An ONNX label may differ only for a word whose ONNX P(DELETE) is this close to the
/// threshold: ONNX quantizes activations to int8, Core ML only the weights.
private static let borderline = 0.015
// MARK: Parity
func testHandwrittenSetMatchesTheReferencePipeline() throws {
let fixture = try Self.load(HandwrittenFixture.self, "cleanup-tagger-handwritten")
XCTAssertEqual(fixture.threshold, CleanupTagger.deleteThreshold)
let tagger = CleanupTagger()
var onnxMismatches: [String] = []
var checkpointMismatches: [String] = []
var exactVersusONNX = 0
var exactVersusTarget = 0
var words = 0
var gapONNX = 0.0
var gapCheckpoint = 0.0
for item in fixture.cases {
let split = CleanupTagger.words(in: item.input)
XCTAssertEqual(split.count, item.labels.count, "#\(item.id) splits into the reference's words")
let probabilities = try tagger.deleteProbabilities(for: split)
let labels = probabilities.map { $0 > CleanupTagger.deleteThreshold ? 1 : 0 }
let output = try tagger.clean(item.input)
words += split.count
for index in split.indices {
gapONNX = max(gapONNX, abs(probabilities[index] - item.pDelete[index]))
gapCheckpoint = max(gapCheckpoint, abs(probabilities[index] - item.checkpointPDelete[index]))
if labels[index] != item.labels[index] {
onnxMismatches.append(String(
format: "#%d %@: Core ML %.4f, ONNX %.4f, fp32 %.4f",
item.id, split[index], probabilities[index], item.pDelete[index], item.checkpointPDelete[index]
))
XCTAssertLessThan(
abs(item.pDelete[index] - CleanupTagger.deleteThreshold), Self.borderline,
"#\(item.id) '\(split[index])' disagrees with ONNX away from the threshold"
)
}
if labels[index] != item.checkpointLabels[index] {
checkpointMismatches.append("#\(item.id) \(split[index])")
}
}
if output == item.expected {
exactVersusONNX += 1
} else {
XCTAssertNotEqual(labels, item.labels, "#\(item.id): same labels must rebuild the same text")
}
if output == item.target {
exactVersusTarget += 1
}
}
XCTAssertEqual(checkpointMismatches, [], "Core ML labels match the fp32 checkpoint's")
XCTAssertLessThanOrEqual(onnxMismatches.count, 2)
print("""
CLEANUP-TAGGER parity: \(fixture.cases.count) sentences, \(words) words at \(CleanupTagger.deleteThreshold)
exact match vs ONNX int8 pipeline: \(exactVersusONNX)/\(fixture.cases.count)
exact match vs hand-written targets: \(exactVersusTarget)/\(fixture.cases.count)
label mismatches vs ONNX int8: \(onnxMismatches.count) \(onnxMismatches)
label mismatches vs fp32 checkpoint: \(checkpointMismatches.count)
max |dP| vs ONNX \(String(format: "%.4f", gapONNX)), vs fp32 \(String(format: "%.4f", gapCheckpoint))
""")
}
// MARK: Tokenizer
func testTokenizerMatchesHuggingFace() throws {
let fixture = try Self.load(TokenizerFixture.self, "cleanup-tokenizer")
let tokenizer = try Self.tokenizer()
var failures: [String] = []
for item in fixture.cases where tokenizer.encode(item.word) != item.ids {
let scalars = item.word.unicodeScalars.map { String($0.value, radix: 16) }.joined(separator: " ")
failures.append("\(scalars): \(tokenizer.encode(item.word)) != \(item.ids)")
}
XCTAssertEqual(failures, [], "\(failures.count) of \(fixture.cases.count) words")
}
func testTokenizerSplitsSpecialTokensAndStripsAccents() throws {
let tokenizer = try Self.tokenizer()
XCTAssertEqual(tokenizer.encode("[CLS]"), [CleanupTokenizer.clsID])
XCTAssertEqual(tokenizer.encode("x[SEP]y"), tokenizer.encode("x") + [CleanupTokenizer.sepID] + tokenizer.encode("y"))
XCTAssertEqual(tokenizer.encode("Café"), tokenizer.encode("cafe"))
XCTAssertEqual(tokenizer.encode("e\u{301}clair"), tokenizer.encode("eclair"))
XCTAssertEqual(tokenizer.encode(String(repeating: "a", count: 101)), [CleanupTokenizer.unknownID])
XCTAssertEqual(tokenizer.encode("4pm?"), tokenizer.encode("4pm") + tokenizer.encode("?"))
XCTAssertEqual(tokenizer.encode("\u{200B}"), [])
}
// MARK: Reconstruction
func testReconstructionMatchesTheJavaScriptReference() throws {
let fixture = try Self.load(ReconstructFixture.self, "cleanup-reconstruct")
var failures: [String] = []
for item in fixture.cases {
let output = CleanupReconstruction.reconstruct(item.words, deletes: item.labels.map { $0 == 1 })
if output != item.output {
failures.append("\(item.words) \(item.labels): \(output) != \(item.output)")
}
}
XCTAssertEqual(failures, [], "\(failures.count) of \(fixture.cases.count) cases")
}
func testReconstructionRepairsPunctuationAndCapitals() {
func rebuild(_ text: String, _ deletes: [Int]) -> String {
CleanupReconstruction.reconstruct(text.split(separator: " ").map(String.init), deletes: deletes.map { $0 == 1 })
}
XCTAssertEqual(
rebuild("Hey Tim, um, are you available on Friday at 3pm, actually 4pm?", [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0]),
"Hey Tim, are you available on Friday at 4pm?"
)
XCTAssertEqual(rebuild("Can you, um, send it", [0, 0, 1, 0, 0]), "Can you send it")
XCTAssertEqual(rebuild("Thanks, um. See you", [0, 1, 0, 0]), "Thanks. See you")
XCTAssertEqual(rebuild("Um, so we go", [1, 0, 0, 0]), "So we go")
XCTAssertEqual(rebuild("We left... um, early", [0, 0, 1, 0]), "We left early")
XCTAssertEqual(rebuild("Call me at 5, um,", [0, 0, 0, 0, 1]), "Call me at 5")
XCTAssertEqual(rebuild("See you, uh.", [0, 0, 1]), "See you.")
// JavaScript cases the first UTF-16 unit: an emoji is never capitalized, ß becomes SS.
XCTAssertEqual(rebuild("Um, 😀ok", [1, 0]), "😀ok")
XCTAssertEqual(rebuild("Um, ßtraße", [1, 0]), "SStraße")
XCTAssertEqual(rebuild("Um, iPhone", [1, 0]), "iPhone")
XCTAssertEqual(rebuild("um uh", [1, 1]), "")
}
// MARK: Chunks
func testChunksKeepWholeWordsWithinTheModelLength() {
XCTAssertEqual(
CleanupTagger.chunks([[7, 8], [], [9]]),
[CleanupTagger.Chunk(ids: [101, 7, 8, 9, 102], firstTokens: [1, nil, 3])]
)
let chunks = CleanupTagger.chunks(Array(repeating: [5, 6], count: 70))
XCTAssertEqual(chunks.count, 2)
XCTAssertEqual(chunks.map(\.firstTokens.count), [63, 7])
XCTAssertTrue(chunks.allSatisfy { $0.ids.count <= CleanupTagger.maxTokens && $0.ids.first == 101 && $0.ids.last == 102 })
let long = CleanupTagger.chunks([[1], Array(repeating: 4, count: 200)])
XCTAssertEqual(long.map(\.ids.count), [3, CleanupTagger.maxTokens])
}
func testLongTranscriptsAreTaggedInChunks() throws {
let fixture = try Self.load(HandwrittenFixture.self, "cleanup-tagger-handwritten")
let text = fixture.cases.prefix(30).map(\.input).joined(separator: " ")
let words = CleanupTagger.words(in: text)
let tagger = CleanupTagger()
let probabilities = try tagger.deleteProbabilities(for: words)
XCTAssertEqual(probabilities.count, words.count)
XCTAssertGreaterThan(words.count, 200)
let cleaned = try tagger.clean(text)
XCTAssertLessThan(cleaned.count, text.count)
XCTAssertGreaterThan(cleaned.count, text.count / 2)
}
// MARK: Dictation entry point
func testCleanIfEnabledRunsOnlyWhenOnAndNeverForVerbatim() async throws {
let suite = "hex.tests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let settings = CleanupTaggerSettings(defaults: defaults)
let tagger = CleanupTagger()
let spoken = "Let's ship it Tuesday, no wait, Thursday."
XCTAssertFalse(settings.isEnabled, "off by default")
var result = await CleanupTagger.cleanIfEnabled(spoken, style: .polished, settings: settings, tagger: tagger)
XCTAssertEqual(result, spoken)
XCTAssertFalse(tagger.isLoaded, "nothing loads while the experiment is off")
settings.isEnabled = true
result = await CleanupTagger.cleanIfEnabled(spoken, style: .verbatim, settings: settings, tagger: tagger)
XCTAssertEqual(result, spoken)
result = await CleanupTagger.cleanIfEnabled(" ", style: .casual, settings: settings, tagger: tagger)
XCTAssertEqual(result, " ")
XCTAssertFalse(tagger.isLoaded)
tagger.prepare()
XCTAssertTrue(tagger.isLoaded)
for style in [DictationStyle.polished, .casual, .notes] {
result = await CleanupTagger.cleanIfEnabled(spoken, style: style, settings: settings, tagger: tagger)
XCTAssertEqual(result, "Let's ship it Thursday.", "\(style)")
}
result = await CleanupTagger.cleanIfEnabled("I mean what I say.", style: .polished, settings: settings, tagger: tagger)
XCTAssertEqual(result, "I mean what I say.", "a sentence with nothing to remove comes back as said")
}
/// The English tagger never runs on another language: on Spanish it dropped negations
/// ("Te digo que no puedo ir" became "Te puedo ir"). Spanish, German and Norwegian get
/// word rules; the rest stay as heard.
func testOtherLanguagesGetRulesNeverTheEnglishTagger() async throws {
let suite = "hex.tests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let settings = CleanupTaggerSettings(defaults: defaults)
settings.isEnabled = true
let tagger = CleanupTagger()
for (language, spoken, cleaned) in [
("nb-NO", "Vi sender den tirsdag, nei vent, torsdag.", "Vi sender den torsdag."),
("es-MX", "Te digo que no puedo ir.", "Te digo que no puedo ir."),
("es-ES", "Nos vemos a las 3, digo, a las 4.", "Nos vemos a las 4."),
("de-DE", "Wir treffen uns um 3, nein, um 4.", "Wir treffen uns um 4."),
("fr-FR", "On se voit mardi, non, jeudi.", "On se voit mardi, non, jeudi."),
] {
CleanupTagger.prepareIfEnabled(style: .polished, language: language, settings: settings, tagger: tagger)
let result = await CleanupTagger.cleanIfEnabled(spoken, style: .polished, language: language, settings: settings, tagger: tagger)
XCTAssertEqual(result, cleaned, language)
let verbatim = await CleanupTagger.cleanIfEnabled(spoken, style: .verbatim, language: language, settings: settings, tagger: tagger)
XCTAssertEqual(verbatim, spoken, "\(language) Verbatim")
}
XCTAssertFalse(tagger.isLoaded, "no other language loads the model")
let english = await CleanupTagger.cleanIfEnabled(
"Let's ship it Tuesday, no wait, Thursday.", style: .polished, language: "en-GB", settings: settings, tagger: tagger
)
XCTAssertEqual(english, "Let's ship it Thursday.")
}
func testDictationStartPreparesOnlyWhenOnAndNotForVerbatim() throws {
let suite = "hex.tests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let settings = CleanupTaggerSettings(defaults: defaults)
let tagger = CleanupTagger()
CleanupTagger.prepareIfEnabled(style: .polished, settings: settings, tagger: tagger)
XCTAssertFalse(tagger.isLoaded)
settings.isEnabled = true
CleanupTagger.prepareIfEnabled(style: .verbatim, settings: settings, tagger: tagger)
XCTAssertFalse(tagger.isLoaded)
CleanupTagger.prepareIfEnabled(style: .casual, settings: settings, tagger: tagger)
XCTAssertTrue(tagger.isLoaded)
}
func testALateCleanupKeepsTheTranscriptAndStillLoads() async throws {
let tagger = CleanupTagger()
let spoken = "Can you send it to John, I mean Mike?"
let late = await tagger.clean(spoken, within: 0)
XCTAssertEqual(late, spoken)
XCTAssertTrue(tagger.isLoaded, "the late run finishes loading for the next dictation")
let warm = await tagger.clean(spoken, within: 5)
XCTAssertEqual(warm, "Can you send it to Mike?")
}
func testMemoryWarningReleasesTheModel() throws {
let tagger = CleanupTagger()
XCTAssertEqual(try tagger.clean("Let's ship it Tuesday, no wait, Thursday."), "Let's ship it Thursday.")
XCTAssertTrue(tagger.isLoaded)
NotificationCenter.default.post(name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
XCTAssertFalse(tagger.isLoaded)
XCTAssertEqual(try tagger.clean("Let's ship it Tuesday, no wait, Thursday."), "Let's ship it Thursday.")
}
// MARK: Measurements
/// Simulator numbers only (Core ML runs on the CPU there). Printed for the report.
func testLatencyAndFootprint() throws {
let fixture = try Self.load(HandwrittenFixture.self, "cleanup-tagger-handwritten")
let tagger = CleanupTagger()
let before = Self.footprintMB()
var start = CFAbsoluteTimeGetCurrent()
tagger.prepare()
XCTAssertTrue(tagger.isLoaded)
let load = (CFAbsoluteTimeGetCurrent() - start) * 1000
start = CFAbsoluteTimeGetCurrent()
_ = try tagger.clean(fixture.cases[0].input)
let first = (CFAbsoluteTimeGetCurrent() - start) * 1000
let loaded = Self.footprintMB()
var times: [Double] = []
for _ in 0..<3 {
for item in fixture.cases {
start = CFAbsoluteTimeGetCurrent()
_ = try tagger.clean(item.input)
times.append((CFAbsoluteTimeGetCurrent() - start) * 1000)
}
}
let afterRuns = Self.footprintMB()
times.sort()
let median = times[times.count / 2]
let p95 = times[times.count * 95 / 100]
tagger.unload()
XCTAssertFalse(tagger.isLoaded)
let released = Self.footprintMB()
XCTAssertLessThan(median, CleanupTagger.timeBudget * 1000)
XCTAssertLessThan(first, CleanupTagger.timeBudget * 1000, "a prepared model cleans the first dictation in budget")
print(String(
format: "CLEANUP-TAGGER latency (simulator): load %.1f ms, first sentence after load %.1f ms; per sentence median %.2f ms, p95 %.2f ms, max %.2f ms over %d runs",
load, first, median, p95, times.last ?? 0, times.count
))
print(String(
format: "CLEANUP-TAGGER footprint (simulator): before %.1f MB, loaded %.1f MB (+%.1f), after runs %.1f MB (+%.1f), after unload %.1f MB",
before, loaded, loaded - before, afterRuns, afterRuns - before, released
))
}
// MARK: Helpers
private static func tokenizer() throws -> CleanupTokenizer {
let url = try XCTUnwrap(
CleanupTagger.resourceURL(CleanupTagger.vocabularyName, withExtension: "txt"),
"the vocabulary ships in the keyboard extension"
)
return try CleanupTokenizer(vocabulary: String(contentsOf: url, encoding: .utf8))
}
private static func load<T: Decodable>(_ type: T.Type, _ name: String) throws -> T {
let url = try XCTUnwrap(Bundle(for: CleanupTaggerTests.self).url(forResource: name, withExtension: "json"))
return try JSONDecoder().decode(T.self, from: Data(contentsOf: url))
}
private static func footprintMB() -> Double {
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
let result = withUnsafeMutablePointer(to: &info) {
$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
}
}
return result == KERN_SUCCESS ? Double(info.phys_footprint) / 1_048_576 : -1
}
}