mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* 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.
416 lines
16 KiB
Swift
416 lines
16 KiB
Swift
import FluidAudio
|
||
import Foundation
|
||
|
||
struct ModelPreparationProgress: Sendable {
|
||
let fractionCompleted: Double
|
||
let detail: String
|
||
}
|
||
|
||
protocol LocalTranscribing: Actor {
|
||
nonisolated var displayName: String { get }
|
||
var languageName: String { get }
|
||
/// The BCP 47 identifier of the language it transcribes.
|
||
var languageIdentifier: String { get }
|
||
|
||
func prepare(
|
||
progressHandler: @escaping @Sendable (ModelPreparationProgress) -> Void
|
||
) async throws
|
||
|
||
func transcribe(_ audioURL: URL) async throws -> String
|
||
func transcribe(_ audioURL: URL, vocabulary: [String]) async throws -> String
|
||
}
|
||
|
||
extension LocalTranscribing {
|
||
/// English unless the engine says otherwise.
|
||
var languageIdentifier: String { "en-US" }
|
||
|
||
/// Engines without a recognition hint ignore the list and transcribe exactly as before.
|
||
nonisolated func transcribe(_ audioURL: URL, vocabulary: [String]) async throws -> String {
|
||
try await transcribe(audioURL)
|
||
}
|
||
}
|
||
|
||
actor ParakeetTranscriber: LocalTranscribing {
|
||
enum TranscriberError: HexDescribedError {
|
||
case notPrepared
|
||
case emptyTranscript
|
||
case downloadFailed
|
||
case notEnoughMemory
|
||
|
||
var errorDescription: String? {
|
||
switch self {
|
||
case .notPrepared:
|
||
String(localized: "Parakeet V2 is not ready.")
|
||
case .emptyTranscript:
|
||
String(localized: "Parakeet did not detect any speech.")
|
||
case .downloadFailed:
|
||
String(localized: "Parakeet V2 didn't download. Check your connection and try again.")
|
||
case .notEnoughMemory:
|
||
String(localized: "Parakeet V2 needs more memory than Hex has here.")
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Whether this iPhone has the memory to load Parakeet V2: 6 GB iPhones report about
|
||
/// 5.5 GB, 4 GB ones (iPhone 11, 12, 13) under 4 GB.
|
||
nonisolated static var fitsInMemory: Bool {
|
||
ProcessInfo.processInfo.physicalMemory >= 5 << 30
|
||
}
|
||
|
||
/// What loading Parakeet V2 takes in Hex: its encoder is 425 MB on disk, 6-bit palettized,
|
||
/// and 1.19 GB of 16-bit weights once Core ML compiles it (the simulator's compiled program),
|
||
/// which an iPhone's Neural Engine holds unpacked before the A17; then the other three
|
||
/// models and a first transcription (70 MB more in the simulator).
|
||
nonisolated static let loadMemory: UInt64 = 1_400 << 20
|
||
|
||
/// Whether `available` (`os_proc_available_memory`) leaves room to load it. 0 means iOS
|
||
/// didn't say (the simulator).
|
||
nonisolated static func hasRoomToLoad(available: UInt64) -> Bool {
|
||
available == 0 || available >= loadMemory
|
||
}
|
||
|
||
/// How long the download may sit at one fraction before Hex stops waiting. Core ML's
|
||
/// compile, after it, reports nothing and can't be cancelled, so it isn't watched.
|
||
static let downloadStallLimit: Duration = .seconds(90)
|
||
|
||
private var manager: AsrManager?
|
||
|
||
nonisolated let displayName = "Parakeet V2"
|
||
let languageName = "English"
|
||
|
||
private nonisolated static var cacheDirectory: URL {
|
||
AsrModels.defaultCacheDirectory(for: .v2)
|
||
}
|
||
|
||
nonisolated static var hasCachedModel: Bool {
|
||
AsrModels.modelsExist(at: cacheDirectory, version: .v2)
|
||
}
|
||
|
||
func prepare(
|
||
progressHandler: @escaping @Sendable (ModelPreparationProgress) -> Void
|
||
) async throws {
|
||
guard manager == nil else { return }
|
||
|
||
let compiled = ParakeetCompileRecord()
|
||
let progress = ParakeetProgressFeed(
|
||
ParakeetPreparationProgress(downloads: !Self.hasCachedModel, compiledBefore: compiled.isCurrent),
|
||
emit: progressHandler
|
||
)
|
||
let ticker = Task {
|
||
while !Task.isCancelled {
|
||
progress.tick()
|
||
try? await Task.sleep(for: .milliseconds(250))
|
||
}
|
||
}
|
||
defer { ticker.cancel() }
|
||
|
||
if !Self.hasCachedModel {
|
||
try await download(progress)
|
||
}
|
||
|
||
// Only the load, where iOS can end Hex short of memory, counts for the guard: a
|
||
// download cut off by a quit or a suspended app ending resumes at the next one.
|
||
let loads = ParakeetLoadGuard()
|
||
// Too little left to load it: Hex would end, so it takes another engine instead.
|
||
guard Self.hasRoomToLoad(available: UInt64(max(0, os_proc_available_memory()))) else {
|
||
loads.setAside()
|
||
throw TranscriberError.notEnoughMemory
|
||
}
|
||
loads.begin()
|
||
var loaded = false
|
||
defer { loads.end(loaded: loaded) }
|
||
progress.update { $0.startLoading(at: Date.now.timeIntervalSinceReferenceDate) }
|
||
// `load` alone: `downloadAndLoad` loads (and on a first run compiles) every model
|
||
// once to check the download and again to return it.
|
||
let models = try await AsrModels.load(
|
||
from: Self.cacheDirectory,
|
||
version: .v2,
|
||
progressHandler: { event in
|
||
// FluidAudio ends each model's load with an empty compiling name.
|
||
guard case .compiling(let name) = event.phase, name.isEmpty else { return }
|
||
let now = Date.now.timeIntervalSinceReferenceDate
|
||
progress.update { $0.finishModel(at: now) }
|
||
}
|
||
)
|
||
let manager = AsrManager(config: .default)
|
||
try await manager.loadModels(models)
|
||
self.manager = manager
|
||
loaded = true
|
||
compiled.markCurrent()
|
||
progress.update { $0.finish() }
|
||
}
|
||
|
||
/// FluidAudio's repo download alone, which resumes each file from its `.partial`.
|
||
private func download(_ progress: ParakeetProgressFeed) async throws {
|
||
let fraction = ProgressReading()
|
||
let directory = Self.cacheDirectory.deletingLastPathComponent()
|
||
do {
|
||
try await StallWatch.run(
|
||
limit: Self.downloadStallLimit,
|
||
progress: { fraction.value },
|
||
operation: {
|
||
// FluidAudio's download reports 0–50%, leaving the rest for a compile.
|
||
try await ModelHub.download(.parakeetV2, to: directory, progressHandler: { event in
|
||
fraction.value = event.fractionCompleted
|
||
progress.update { $0.download(min(1, event.fractionCompleted * 2)) }
|
||
})
|
||
let vocabulary = Self.cacheDirectory.appendingPathComponent(ModelNames.ASR.vocabularyFile)
|
||
if !FileManager.default.fileExists(atPath: vocabulary.path) {
|
||
// The repo's listing brings it; this is for one that didn't.
|
||
let data = try await ModelHub.fetchFile(
|
||
from: ModelRegistry.resolveModel(Repo.parakeetV2.remotePath, ModelNames.ASR.vocabularyFile),
|
||
description: ModelNames.ASR.vocabularyFile
|
||
)
|
||
try data.write(to: vocabulary, options: .atomic)
|
||
}
|
||
}
|
||
)
|
||
} catch let error as DownloadError {
|
||
// FluidAudio's descriptions carry Hugging Face paths and HTML; say it plainly.
|
||
switch error {
|
||
case .invalidResponse, .rateLimited, .downloadFailed, .htmlErrorResponse, .invalidArtifact:
|
||
throw TranscriberError.downloadFailed
|
||
default:
|
||
throw error
|
||
}
|
||
}
|
||
}
|
||
|
||
func transcribe(_ audioURL: URL) async throws -> String {
|
||
guard let manager else {
|
||
throw TranscriberError.notPrepared
|
||
}
|
||
|
||
let decoderLayers = await manager.decoderLayerCount
|
||
var decoderState = TdtDecoderState.make(decoderLayers: decoderLayers)
|
||
let result = try await manager.transcribe(
|
||
audioURL,
|
||
decoderState: &decoderState
|
||
)
|
||
let text = result.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
|
||
guard !text.isEmpty else {
|
||
throw TranscriberError.emptyTranscript
|
||
}
|
||
return text
|
||
}
|
||
}
|
||
|
||
/// What Parakeet's preparation shows. The download moves with its bytes; Core ML says only
|
||
/// when each model starts and ends loading, and the first load on an iPhone compiles the
|
||
/// encoder for its Neural Engine for a minute or more, so each model's share fills on a time
|
||
/// estimate instead of sitting still.
|
||
nonisolated struct ParakeetPreparationProgress: Sendable, Equatable {
|
||
/// Seconds each model takes to load, in FluidAudio's order (preprocessor, encoder,
|
||
/// decoder, joint): the first time on an iPhone 14, and once Core ML has compiled them.
|
||
static let firstLoadSeconds: [Double] = [3, 60, 4, 4]
|
||
static let laterLoadSeconds: [Double] = [0.5, 3, 0.5, 0.5]
|
||
/// The bar's share for a download, when there is one.
|
||
static let downloadShare = 0.7
|
||
|
||
let downloads: Bool
|
||
let compiledBefore: Bool
|
||
/// What the bar says while the download runs.
|
||
let downloadDetail: String
|
||
private(set) var downloaded = 0.0
|
||
private(set) var loadStartedAt: TimeInterval?
|
||
private(set) var modelsLoaded = 0
|
||
/// The load's fraction at the last model Core ML finished, and when that was.
|
||
private var loadBase = 0.0
|
||
private var segmentStartedAt: TimeInterval = 0
|
||
private(set) var isFinished = false
|
||
|
||
init(
|
||
downloads: Bool,
|
||
compiledBefore: Bool,
|
||
downloadDetail: String = String(localized: "Downloading the speech model")
|
||
) {
|
||
self.downloads = downloads
|
||
self.compiledBefore = compiledBefore
|
||
self.downloadDetail = downloadDetail
|
||
}
|
||
|
||
mutating func download(_ fraction: Double) {
|
||
downloaded = max(downloaded, min(1, fraction))
|
||
}
|
||
|
||
mutating func startLoading(at time: TimeInterval) {
|
||
downloaded = 1
|
||
loadStartedAt = time
|
||
segmentStartedAt = time
|
||
}
|
||
|
||
mutating func finishModel(at time: TimeInterval) {
|
||
let shown = loadFraction(at: time)
|
||
modelsLoaded = min(modelsLoaded + 1, estimates.count)
|
||
let done = estimates.prefix(modelsLoaded).reduce(0, +) / expectedLoadSeconds
|
||
loadBase = min(1, max(shown, done))
|
||
segmentStartedAt = time
|
||
}
|
||
|
||
mutating func finish() {
|
||
isFinished = true
|
||
}
|
||
|
||
private var estimates: [Double] {
|
||
compiledBefore ? Self.laterLoadSeconds : Self.firstLoadSeconds
|
||
}
|
||
|
||
/// The estimate for the whole load, which the copy rounds.
|
||
var expectedLoadSeconds: Double { estimates.reduce(0, +) }
|
||
|
||
/// Between Core ML's reports the rest fills on the time the models left should take:
|
||
/// half of it by then, two thirds by twice that, and it keeps creeping however long a
|
||
/// slower iPhone takes, never reaching the end before Core ML says it's done.
|
||
private func loadFraction(at now: TimeInterval) -> Double {
|
||
let remaining = max(0.5, estimates.dropFirst(modelsLoaded).reduce(0, +))
|
||
let x = max(0, now - segmentStartedAt) / remaining
|
||
return loadBase + (1 - loadBase) * x / (x + 1)
|
||
}
|
||
|
||
func snapshot(at now: TimeInterval) -> ModelPreparationProgress {
|
||
if isFinished {
|
||
return ModelPreparationProgress(fractionCompleted: 1, detail: String(localized: "Ready"))
|
||
}
|
||
let downloadShare = downloads ? Self.downloadShare : 0
|
||
guard let loadStartedAt else {
|
||
if downloads, downloaded > 0 {
|
||
return ModelPreparationProgress(
|
||
fractionCompleted: downloadShare * downloaded,
|
||
detail: downloadDetail
|
||
)
|
||
}
|
||
return ModelPreparationProgress(fractionCompleted: 0, detail: String(localized: "Checking the speech model"))
|
||
}
|
||
let fraction = downloadShare + (1 - downloadShare) * loadFraction(at: now)
|
||
let detail: String
|
||
if compiledBefore {
|
||
detail = String(localized: "Loading the speech model")
|
||
} else if now - loadStartedAt < expectedLoadSeconds * 2 {
|
||
detail = String(localized: "Optimizing for this iPhone… about a minute")
|
||
} else {
|
||
detail = String(localized: "Still optimizing. The first time can take a few minutes.")
|
||
}
|
||
return ModelPreparationProgress(fractionCompleted: min(0.99, fraction), detail: detail)
|
||
}
|
||
}
|
||
|
||
/// Feeds `ParakeetPreparationProgress` to the handler, at most ten times a second (the
|
||
/// download alone reports thousands of times) and whenever its words change.
|
||
nonisolated final class ParakeetProgressFeed: @unchecked Sendable {
|
||
private let lock = NSLock()
|
||
private var state: ParakeetPreparationProgress
|
||
private var lastEmit: TimeInterval = 0
|
||
private var lastDetail = ""
|
||
private let emit: @Sendable (ModelPreparationProgress) -> Void
|
||
|
||
init(_ state: ParakeetPreparationProgress, emit: @escaping @Sendable (ModelPreparationProgress) -> Void) {
|
||
self.state = state
|
||
self.emit = emit
|
||
}
|
||
|
||
func update(_ change: (inout ParakeetPreparationProgress) -> Void) {
|
||
let now = Date.now.timeIntervalSinceReferenceDate
|
||
let snapshot: ModelPreparationProgress? = lock.withLock {
|
||
change(&state)
|
||
let snapshot = state.snapshot(at: now)
|
||
guard state.isFinished || snapshot.detail != lastDetail || now - lastEmit >= 0.1 else {
|
||
return nil
|
||
}
|
||
lastEmit = now
|
||
lastDetail = snapshot.detail
|
||
return snapshot
|
||
}
|
||
if let snapshot { emit(snapshot) }
|
||
}
|
||
|
||
func tick() {
|
||
update { _ in }
|
||
}
|
||
}
|
||
|
||
/// The system Core ML last compiled Parakeet for. Core ML keeps what it compiled for the
|
||
/// Neural Engine between launches, so only the first load (and the first after an iOS
|
||
/// update) is slow; this picks the words and estimate. In the app's own defaults.
|
||
nonisolated struct ParakeetCompileRecord {
|
||
static let v2Key = "parakeet.compiledForSystem"
|
||
private let key: String
|
||
private let defaults: UserDefaults
|
||
private let system: String
|
||
|
||
init(
|
||
key: String = v2Key,
|
||
defaults: UserDefaults = .standard,
|
||
system: String = ProcessInfo.processInfo.operatingSystemVersionString
|
||
) {
|
||
self.key = key
|
||
self.defaults = defaults
|
||
self.system = system
|
||
}
|
||
|
||
var isCurrent: Bool {
|
||
defaults.string(forKey: key) == system
|
||
}
|
||
|
||
func markCurrent() {
|
||
defaults.set(system, forKey: key)
|
||
}
|
||
}
|
||
|
||
/// Notes a Parakeet load that ended with Hex itself. iOS ends an app that passes its memory
|
||
/// limit while Core ML compiles the model (an iPhone 11 sat at "50%", then closed), and a
|
||
/// launch that loaded it again at once ended the same way every time. After that, Hex takes
|
||
/// another engine (`SpeechEngineChoice`): Apple's, where it has the language, else it waits
|
||
/// for a tap on Set up instead of loading Parakeet at launch. In the app's own defaults.
|
||
nonisolated struct ParakeetLoadGuard {
|
||
static let message = String(localized: "Hex closed while loading the speech model, likely short of memory. Close other apps, then tap Set up to try again.")
|
||
|
||
private let loadingKey: String
|
||
private let interruptedKey: String
|
||
private let defaults: UserDefaults
|
||
|
||
/// `model` names the keys: "parakeet" for V2, as before, "parakeetUltra" for Ultra.
|
||
init(model: String = "parakeet", defaults: UserDefaults = .standard) {
|
||
loadingKey = "\(model).loadStartedAt"
|
||
interruptedKey = "\(model).loadInterrupted"
|
||
self.defaults = defaults
|
||
}
|
||
|
||
/// Once per launch: a load still marked as running belonged to a process that ended.
|
||
func noteLaunch() {
|
||
guard defaults.object(forKey: loadingKey) != nil else { return }
|
||
defaults.removeObject(forKey: loadingKey)
|
||
defaults.set(true, forKey: interruptedKey)
|
||
}
|
||
|
||
var lastLoadWasInterrupted: Bool {
|
||
defaults.bool(forKey: interruptedKey)
|
||
}
|
||
|
||
func begin() {
|
||
defaults.set(Date().timeIntervalSince1970, forKey: loadingKey)
|
||
}
|
||
|
||
/// Too little memory left to load Parakeet: counts as an interrupted load, so Hex picks
|
||
/// another engine (`SpeechEngineChoice`) instead of loading it.
|
||
func setAside() {
|
||
defaults.set(true, forKey: interruptedKey)
|
||
}
|
||
|
||
/// A load that returned, loaded or not; only a loaded one clears the interruption.
|
||
func end(loaded: Bool) {
|
||
defaults.removeObject(forKey: loadingKey)
|
||
if loaded {
|
||
defaults.removeObject(forKey: interruptedKey)
|
||
}
|
||
}
|
||
|
||
/// Forgets an interrupted load, for a person who asks to try again.
|
||
func forget() {
|
||
defaults.removeObject(forKey: loadingKey)
|
||
defaults.removeObject(forKey: interruptedKey)
|
||
}
|
||
}
|
||
|
||
extension ParakeetTranscriber.TranscriberError: NoSpeechError {
|
||
var meansNoSpeech: Bool { self == .emptyTranscript }
|
||
}
|