hex/ios/HEXMobile/KeyboardSpeechPreparation.swift
Ryan Vogel b849b63f01
iOS: Multilingual model (Parakeet Ultra) experiment, off by default (#2197)
* iOS: Parakeet's preparation, compile record and load guard take a model name

A second Parakeet model (Parakeet Ultra, next commit) needs its own load guard
and compile record, and its own words while it downloads, without changing V2's.

- ParakeetLoadGuard(model:) and ParakeetCompileRecord(key:) name their
  UserDefaults keys; the defaults ("parakeet.loadStartedAt",
  "parakeet.loadInterrupted", "parakeet.compiledForSystem") are V2's keys as
  before, so V2's state carries over.
- ParakeetLoadGuard.forget() clears an interrupted load, for a person who asks
  to try again.
- ParakeetPreparationProgress takes the download's detail, defaulting to V2's
  "Downloading the speech model".
- ParakeetProgressFeed is no longer private to ParakeetTranscriber.swift.

Nothing V2 does changes: same keys, same words, same progress.

Verified: xcodebuild test on an iPhone 17 Pro Max iOS 26.4 simulator (Mac
Studio), 575 tests, 0 failures, 1 skipped, with the next commit applied.

* iOS: Experiments › Multilingual model (Parakeet) dictates 25 languages, mixed in a sentence

A TestFlight tester (iPhone 17 Pro Max, iOS 26.6.2, build 56) asked for Parakeet
Ultra: they mix Dutch phrases and English words in one sentence, which Apple
Speech, one locale at a time, gets wrong, and Ultra on desktop Hex gets right.

The experiment is off by default. While it's on, Hex dictates Parakeet Ultra's
25 languages (Moondream's post-training of NVIDIA Parakeet TDT 0.6B v3, CC BY
4.0) with FluidInference's Core ML build of it; other languages keep the engine
Hex picks without it.

- MultilingualParakeetSettings (HEXShared, App Group): the switch, Ultra's
  languages, and the rule both processes use: the language set, else the
  keyboard's language Automatic follows, else the iPhone's first, on iPhones
  with 6 GB or more.
- ParakeetUltraModel: the 18 files FluidAudio's v3 path reads, pinned to
  revision 95eaa59 with sizes and SHA-256 (632 MB), downloaded into
  Application Support (out of backups) with Range resume from a .partial and a
  digest check before each file gets its name, hashed in 4 MB chunks drained
  one at a time (without that the encoder's 594 MB stayed in memory during the
  check). FluidAudio 0.15.5 has no .ultra (0.17.7 added it) and its loader
  replaces a folder it can't load with v3's download, so Hex loads the four
  models itself and hands FluidAudio v3 AsrModels. The pin stays at 0.15.5, so
  V2 and everything else run the same FluidAudio as before.
- ParakeetUltraTranscriber: download through StallWatch (90 s, as V2), stopped
  if the switch goes off mid-way; load and transcribe as V2. Chosen only with
  1.5 GB left (os_proc_available_memory), as #2190 does for V2, and set aside
  after a load that ended Hex or found too little memory (its own
  ParakeetLoadGuard keys) until the switch is turned off and on; then home says
  Hex uses its usual model.
- Engine choice: DictationController.defaultTranscriber and prepareAtLaunch ask
  for Ultra first; with the switch off they only delete a download it left.
  multilingualParakeetChanged prepares the new engine now, or after the
  dictation in flight. Download failures count as interruptions, retried once
  back in the foreground.
- Keyboard: the model can't load in a keyboard, so while Ultra takes the
  dictation language, Dictate and the Hex key open Hex, as before iOS 26
  (KeyboardViewController), and KeyboardSpeechPreparation follows the app
  instead of downloading Apple's model. A warm session still dictates without
  leaving the app.
- Settings › Experiments › "Multilingual model (Parakeet)": "25 languages,
  even mixed in a sentence. 632.2 MB download. Keyboard dictation opens Hex.",
  disabled with "Needs an iPhone with 6 GB of memory or more" below that. On
  downloads it; off deletes it. The preparation bar (#2171) says "Downloading
  632.2 MB · Wi-Fi recommended". zh-Hans for every new string.
- Acknowledgements and ios/README.md credit Parakeet Ultra, NVIDIA Parakeet TDT
  0.6B v3 and FluidInference's conversion (CC BY 4.0).
- Onboarding's language line checks for "Parakeet V2" by name, not any
  "Parakeet", so Ultra isn't taken for English.

Measured on the Mac Studio (~/dev/experiments/2026-11-21-hex-multilingual-parakeet,
159 macOS say clips: Dutch-English sentences spoken by Xander and Ellen and
spliced with Samantha, pure Dutch, pure English): word error rate on the mixed
sentences 7.5% for Ultra against 26.9% for Apple Speech nl-NL
(DictationTranscriber) and ~80% for Apple Speech en-US and Parakeet V2; pure
Dutch 0.9% (Apple nl-NL 0.4%), pure English 0% (Apple en-US 0%). Core ML on the
Mac: compile 7.4 s (V2 11.4 s), same speed as V2.

Verified: xcodebuild test on an iPhone 17 Pro Max iOS 26.4 simulator, 575
tests, 0 failures, 1 skipped, with new cases in DictationControllerTests (off
by default, language and memory rules, separate guard, download words, pinned
files, re-prepare on toggle). In that simulator a fresh install with the switch
on downloaded, checked and loaded Ultra in under 10 s and became ready, and the
app's ParakeetUltraTranscriber transcribed the test clips (a throwaway case,
not committed). The simulator has no microphone here and runs Core ML on the
CPU: a real iPhone must confirm load memory, Neural Engine compile time, speed,
the keyboard opening Hex, and dictation of real speech.

* iOS: Acknowledgements credit Parakeet V2

Hex downloads NVIDIA Parakeet TDT 0.6B v2 (FluidInference's Core ML conversion)
to dictate English, and its licence, CC BY 4.0, asks for credit, but
Settings › Acknowledgements and the README named only the data Hex ships and,
since the previous commit, Parakeet Ultra.

- AcknowledgementsView and ios/README.md's Acknowledgements credit NVIDIA's
  model and FluidInference's conversion, both CC BY 4.0, with links, and say
  the conversion stores the encoder at reduced precision and Hex uses it
  unchanged.

FluidAudio stays at 0.15.5.

Verified: generic build (CODE_SIGNING_ALLOWED=NO) and xcodebuild test on an
iPhone 17 Pro Max simulator on the Mac Studio, all tests passing.
2026-11-21 09:29:13 -05:00

122 lines
5.2 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Foundation
import Observation
/// The speech model the Hex keyboard itself dictates with, so "ready" means the Hex key works
/// in other apps, not only that Hex's own model is ready.
///
/// On iOS 26 the keyboard transcribes inside itself with Apple Speech (KeyboardSpeech),
/// whatever Hex uses: Parakeet can't load within a keyboard's memory limit, and handing every
/// dictation to Hex would leave the app being typed in each time. So when Hex dictates with
/// Parakeet (an English iPhone without SpeechTranscriber, or a Parakeet model already cached),
/// Hex installs the keyboard's Apple Speech model too, with the call the keyboard makes
/// (AppleSpeechAssets.install: same language, same module, and it ends the keyboard's handoff
/// to Hex). When Hex itself dictates with Apple Speech, its own model is that same one.
/// Before iOS 26, and where Speech lists no language at all, the Hex key hands dictation to
/// Hex, so Hex's own model is the one that counts.
@MainActor
@Observable
final class KeyboardSpeechPreparation {
enum State: Equatable {
case checking
/// The keyboard uses what Hex prepares: Hex's own model decides.
case followsApp
case downloading(Double)
case ready
case failed(String)
}
private(set) var state: State = OnboardingFixture.isSnapshot ? .ready : .checking {
didSet {
if case .downloading = state { downloads = true }
}
}
/// Whether it downloaded the keyboard's model, so a model already in place (or the handoff
/// to Hex) doesn't count as half of onboarding's progress.
private(set) var downloads = false
@ObservationIgnored private var task: Task<Void, Never>?
var isReady: Bool {
state == .ready || state == .followsApp
}
/// Checks, and downloads if needed. Runs once unless "retry" (after a failure).
func start(retry: Bool = false, appEngine: @escaping @MainActor () -> String) {
guard !OnboardingFixture.isSnapshot else { return }
if task != nil, !retry { return }
if retry, isReady { return }
task?.cancel()
state = .checking
task = Task { await run(appEngine: appEngine) }
}
private func run(appEngine: @MainActor () -> String) async {
guard #available(iOS 26.0, *) else {
state = .followsApp
return
}
// Launch decides Hex's engine in a task of its own; give it a moment to answer.
for _ in 0..<30 where appEngine() == "Local speech" {
try? await Task.sleep(for: .milliseconds(100))
}
guard !Task.isCancelled else { return }
// Parakeet Ultra (Experiments › Multilingual model): the Hex key hands its dictations to Hex.
if appEngine() == "Apple Speech" || appEngine() == ParakeetUltraTranscriber.name {
state = .followsApp
return
}
// Automatic can move on to another language once one won't install: try that one.
for _ in 0..<3 {
guard await prepare() else { return }
}
}
/// One language's model. Returns true when Automatic moved on and the next one should be tried.
@available(iOS 26.0, *)
private func prepare() async -> Bool {
let settings = LanguageSettings()
guard let language = await AppleSpeechLanguages.resolve(settings: settings) else {
// Speech lists nothing here: the keyboard hands its dictations to Hex.
handOffToHex(settings)
return false
}
if await AppleSpeechAssets.steps.status(language) == .installed {
settings.clearKeyboardNeedsHex()
state = .ready
return false
}
state = .downloading(0)
do {
_ = try await AppleSpeechAssets.install(
language,
settings: settings,
log: { print("keyboard speech: \($0)") },
progress: { fraction in
Task { @MainActor [weak self] in
guard let self, case .downloading = self.state else { return }
self.state = .downloading(fraction)
}
}
)
guard !Task.isCancelled else { return false }
state = .ready
} catch is CancellationError {
} catch let unavailable as SpeechModelUnavailable where unavailable.reason == .notOnThisIPhone {
if unavailable.fallback != nil, unavailable.automatic { return true }
// Apple has no model for it on this iPhone: the keyboard hands its dictations to
// Hex, as it would after its own first try, so the Hex key works from the start.
handOffToHex(settings)
} catch {
state = .failed(UserFacingError.message(for: error, context: .model))
}
return false
}
/// The Hex key opens Hex, which dictates with its own model (KeyboardViewController reads
/// keyboardNeedsHex); marked again at each launch, as the mark lasts a day.
private func handOffToHex(_ settings: LanguageSettings) {
settings.markKeyboardNeedsHex()
state = .followsApp
// A download that ended in the handoff isn't part of onboarding's progress either.
downloads = false
}
}