mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS keyboard: a failure from Hex shows for seconds, not forever, and the Hex key retries it X testers on build 56 and earlier: "The keyboard keeps either bringing me back to the app or telling me another app is using the microphone" (@itsjling) and "The another app is using audio message seems inaccurate cause it's showing for me all the time although it's working fine" (@RedaSjakur). Cause, reproduced on build 56 (2ef08aa4) in an iOS 27.2 simulator on the Mac Studio (no microphone input): Hex's dictation failed ("Hex couldn't start the microphone. Try again."), Hex was then closed, and a minute later the Hex keyboard's strip in Settings' search field still said so. Hex writes its snapshot only while it runs, so a failed snapshot (heartbeat 0, no time) stayed in the App Group, and KeyboardViewModel read any .failed snapshot as failed whatever its age. The code path is unchanged on origin/dev. With a warm session up it was worse: Hex stayed in .failed, consumeKeyboardCommand ignored every start unless the phase was .ready, and the full keyboard's Hex key (isWarm = Full Access && warm available) kept sending starts to it, so nothing recorded until Hex was opened. The keyboard's own failure snapshot also reads as available for its 6 s, so a Hex key tap right after an in-keyboard failure went to a warm session that doesn't exist. Now: - KeyboardSnapshot.messageAt: when Hex wrote the message (DictationController stamps a failure when its phase becomes failed, and keyboardMessage when set; the keyboard's own failure stamps its snapshot). The keyboard drops a message, and reads a failure as offline, 8 s after it (messageShownFor), and at once for a snapshot with no time (an earlier build's). Whether a warm session is up and any result stay as they were. - KeyboardViewModel.dictatesThroughHex (Full Access, warm available, not failed), used by the full keyboard's Hex key and its touch-down capture: after a failure both keyboards dictate in the keyboard, as the Dictation bar already did. - Hex takes a keyboard start while failed when the failure was the microphone for a keyboard dictation with the model loaded (captureFailed): the next Hex key is its Try again. Model failures still wait for Hex to get ready again. Not changed: the 32 MB memory threshold and keyboardNeedsHex, the two ways the Hex key opens Hex. In the simulator the handoffs logged "speech model missing here" after the keyboard's own asset check failed ("anomaly.hex.mobile.keyboard is not subscribed to assistant.en_US") on a sim whose Hex had never installed a model, which is the intended path; a device's reason needs its probe log. Verified: new KeyboardBridgeTests.testAFailureHexWroteAWhileAgoIsOver and DictationControllerTests.testAWarmSessionsMicrophoneFailureIsRetriedFromTheKeyboard; KeyboardBridgeTests and DictationControllerTests pass (79 tests, 0 failures, iPhone 17 Pro iOS 27.2 simulator). In the simulator with this build, the same failure no longer shows in the keyboard a minute later. * iOS keyboard: the Hex key's audio session calls leave the main thread X tester @leeladhar (iPhone 16 Pro Max, build 56 or earlier): "the keyboard freezes while using apps sometimes ... the only way to close the keyboard is to close the app completely". Not reproduced in the iOS 27.2 simulator on build 56 (2ef08aa4) or origin/dev: 24 host visits (Messages, Contacts, Settings search) with typing, the Hex key and globe switches kept one keyboard process, no crash or hang report, footprint 29-40 MB with no growth. The device cause isn't confirmed. The likeliest one left on origin/dev is the last synchronous audio server round trips on the keyboard's main thread: every Hex key touch-down set the session's category, read and preferred its inputs (KeyboardLocalDictation.microphone(for:)), asked isOtherAudioPlaying, and read the Speech Recognition status for the probe log, all before the page could start. These wait on the audio server (and TCC) with no timeout; a build 56 crash report from TestFlight shows Hex's own main thread parked in such a call (setPreferredSampleRate waiting on SetBatchProperties). #2185 moved the one on the launch path for the same reason. While blocked, no key, Done or globe responds, and the keyboard can't dismiss. Now begin() runs those on the keyboard's audio session queue (after any earlier capture's release there) and starts the page when they return, unless the job was dropped, stopped or replaced meanwhile. Done before the page was asked to start ends quietly at once instead of leaving the page to start a capture nobody wants. Verified: builds clean; in an iPhone 17 Pro iOS 27.2 simulator (WebKit's mock audio device) the Hex key's touch-down capture still starts and is kept: "first audio +124 ms after touch-down (... getUserMedia +83 ...)", 13.5 s recorded as 643,072 frames at 48 kHz (no gap), then transcription as before. * iOS keyboard: the capture page resumes an audio context iOS suspended mid-dictation TestFlight tester on X (iPhone 13 Pro Max, iOS 27, build 56 or earlier): "in progress recording dropped when I took a screenshot". What a screenshot does to an in-keyboard dictation, in an iPhone 17 Pro iOS 27.2 simulator on the Mac Studio (WebKit's mock audio device records there): - The host only going inactive doesn't stop it: with Control Center pulled down for 4 s mid-dictation the page kept sending audio (700,416 frames at 48 kHz over a 14.8 s recording, no gap). - A screenshot taken with Cmd-Shift-3 hid the keyboard and the probe log said "keyboard hidden while recording: finishing with what was said" at the shutter. The simulator can only take one through its hardware keyboard, which also turns on keyboard minimization, so it doesn't show which of the two hid it. On an iPhone, iOS 26 and 27 open the screenshot's full-screen preview over the app, and a keyboard that hides is torn down and its WebKit processes suspended, so a dictation can't keep recording through that. - On build 56 a keyboard hidden mid-recording lost the dictation: viewWillDisappear only dropped a touch-down capture, and the recording went with the view controller (reproduced in #2163). Since #2163 on origin/dev it stops, keeps what was said, and the text goes into the same field when the keyboard comes back within 30 s, else is offered as Paste dictation. The one way left for a capture to end early with the keyboard still up is the page's audio context: iOS may suspend or interrupt it for other audio and the page never resumed it, so no more audio came and the 6 s watchdog ended the dictation. The page now resumes a context that isn't running every 250 ms while it records, and stops trying when the capture stops. Not changed: a keyboard hidden by a screenshot's preview still ends the recording (with its text kept, as above). Verified: builds clean; in the simulator the touch-down capture still starts and records through Control Center with no gap (numbers above). * iOS: a spoken count reads "Test 1, 2, 3." on every speech model TestFlight (@kevin_miller, Nov 20, build 56 =2ef08aa4): "Test 1, 2, 3" came out "Test three." / "Test 3" from the keyboard's in-keyboard dictation and "test 123" in the app's Dictate box. What each speech model writes (macOS 27.2.1 on the Mac Studio, `say` clips, 4 voices): Apple's SpeechTranscriber (in-keyboard dictation) writes "Test one, 2, 3.", "Test, one, two, three.", "Testing 123.", "Counting one, two, three, four."; DictationTranscriber writes "Test 123", "Counting 1234"; Parakeet v2 through FluidAudio 0.15.5 (the app) writes "Test 1, 2, 3", "Testing 123" (no pauses), "1, 2, 3, testing". Responsible steps: - "Test three." / "Test 3": at build 56 Clean up what I say deleted every word over P(DELETE) 0.98 with no guard. The real Core ML model gives the count words but the last 0.97-0.999 ("Test one two three." -> "Test three.", "Test 1, 2, 3." -> "Test 1, 3."): it reads a count as a self-correction. CleanupGuard (#2132, after build 56) already keeps every count on origin/dev; this commit adds tests that pin it. - "test 123": Parakeet and DictationTranscriber write "123" themselves; no Hex step merges digits. Apple Intelligence's cleanup (same prompt, macOS 27.2 model) kept "Test 1, 2, 3." in 3 of 3 runs per input. - The paths still disagreed on origin/dev: the keyboard inserted "Test one, 2, 3." where the app inserted "Test 1, 2, 3.". Change: SpokenCleanupRules.spokenCounts, run by CleanupTagger.cleanIfEnabled right after spoken symbols (every style but Verbatim, English, Clean up what I say on or off, before the tagger, in the app and in-keyboard dictation), writes a count in digits: three numbers or more counting up from one, in words or digits, with only a comma or a space between them ("one, 2, 3", "one two three" -> "1, 2, 3"), and "123"... right after "test"/"testing" when it ends its clause ("Test 123" -> "Test 1, 2, 3"; "test 123 passed", "room 123", "Counting 1234" stay). Decision: the "123" split is limited to test/testing because a bare "123" is usually a real number. Format lists already never makes a list of a count (each item would be empty); tests prove it. README gains the Spoken counts paragraph. Verified on the iOS 27.2 simulator (Mac Studio), real Core ML tagger: TranscriptCleanupGuardTests 9, CleanupGuardTests 6, SpokenCleanupRulesTests 19, HinglishRomanizerTests 7, SpokenListsTests 10, InformalContractionTests 4, FrenchSpacingTests 3, CleanupTaggerTests 15, DictationControllerTests 50: 123 tests, 0 failures. New: testSpokenCountsBecomeDigits, testOtherNumbersStayAsSaid, testCountsAreNoList, testCountsKeepEveryNumberFromEverySpeechModel (also shows the guardless tagger's "Test three."), testACountReadsTheSameFromTheAppAndTheKeyboard (app with Parakeet's text vs keyboard with both Apple modules' text, every style, Lowercase).
432 lines
22 KiB
Swift
432 lines
22 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 }
|
|
// The reference pipeline has no CleanupGuard: rebuild from the model's own labels.
|
|
let output = CleanupReconstruction.reconstruct(split, deletes: labels.map { $0 == 1 })
|
|
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."
|
|
|
|
XCTAssertTrue(settings.isEnabled, "on by default")
|
|
settings.isEnabled = false
|
|
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")
|
|
}
|
|
|
|
/// Spoken "@" runs in every style but Verbatim, with the experiment off too, so both the
|
|
/// app's and the keyboard's dictation get it.
|
|
func testSpokenAtSignsApplyWithTheExperimentOffButNotInVerbatim() 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 = "Mail it to john at the rate gmail dot com."
|
|
|
|
settings.isEnabled = false
|
|
for style in [DictationStyle.polished, .casual, .notes] {
|
|
let result = await CleanupTagger.cleanIfEnabled(spoken, style: style, language: "en-IN", settings: settings, tagger: tagger)
|
|
XCTAssertEqual(result, "Mail it to john@gmail.com.", "\(style)")
|
|
}
|
|
let verbatim = await CleanupTagger.cleanIfEnabled(spoken, style: .verbatim, language: "en-IN", settings: settings, tagger: tagger)
|
|
XCTAssertEqual(verbatim, spoken)
|
|
let spanish = await CleanupTagger.cleanIfEnabled(spoken, style: .polished, language: "es-ES", settings: settings, tagger: tagger)
|
|
XCTAssertEqual(spanish, spoken)
|
|
XCTAssertFalse(tagger.isLoaded, "the experiment's model stays unloaded")
|
|
}
|
|
|
|
/// 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.")
|
|
}
|
|
|
|
/// A count said as a microphone test keeps every number and reads the same whichever speech
|
|
/// model heard it: Apple's SpeechTranscriber writes "Test one, 2, 3.", DictationTranscriber
|
|
/// "Test 123" and Parakeet "Test 1, 2, 3" (macOS 27.2, `say` voices). The tagger alone is
|
|
/// sure every count word but the last is a self-correction, which made "Test three." in
|
|
/// in-keyboard dictation before `CleanupGuard` (TestFlight, Nov 20).
|
|
func testCountsKeepEveryNumberFromEverySpeechModel() 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 words = CleanupTagger.words(in: "Test one two three.")
|
|
let alone = try tagger.deleteProbabilities(for: words).map { $0 > CleanupTagger.deleteThreshold }
|
|
XCTAssertEqual(CleanupReconstruction.reconstruct(words, deletes: alone), "Test three.", "the tagger without its guard")
|
|
XCTAssertEqual(try tagger.clean("Test one two three."), "Test one two three.", "the guard keeps a count in words")
|
|
|
|
for enabled in [true, false] {
|
|
settings.isEnabled = enabled
|
|
for (heard, cleaned) in [
|
|
("Test one, 2, 3.", "Test 1, 2, 3."),
|
|
("Test one two three.", "Test 1, 2, 3."),
|
|
("Test, one, two, three.", "Test, 1, 2, 3."),
|
|
("Test 123", "Test 1, 2, 3"),
|
|
("Test 1, 2, 3", "Test 1, 2, 3"),
|
|
("Testing 123", "Testing 1, 2, 3"),
|
|
("Counting one, two, three, four.", "Counting 1, 2, 3, 4."),
|
|
("One, two, three, testing.", "1, 2, 3, testing."),
|
|
("1, 2, 3, testing", "1, 2, 3, testing"),
|
|
] {
|
|
let result = await CleanupTagger.cleanIfEnabled(
|
|
heard, style: .polished, language: "en-US", settings: settings, tagger: tagger
|
|
)
|
|
XCTAssertEqual(result, cleaned, "\(heard), cleanup \(enabled)")
|
|
}
|
|
}
|
|
let verbatim = await CleanupTagger.cleanIfEnabled("Test one, 2, 3.", style: .verbatim, settings: settings, tagger: tagger)
|
|
XCTAssertEqual(verbatim, "Test one, 2, 3.")
|
|
}
|
|
|
|
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()
|
|
|
|
settings.isEnabled = false
|
|
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
|
|
}
|
|
}
|