mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
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.
178 lines
7.3 KiB
Swift
178 lines
7.3 KiB
Swift
import FluidAudio
|
||
import Foundation
|
||
import os
|
||
|
||
/// Experiments › Multilingual model (Parakeet): Parakeet Ultra (`ParakeetUltraModel`) through
|
||
/// FluidAudio's v3 decoder, in Hex's own process. It hears its 25 languages without being told
|
||
/// which, mixed within a sentence, so `languageIdentifier` only names the dictation language
|
||
/// for the steps after it (formatting, lists, cleanup).
|
||
actor ParakeetUltraTranscriber: LocalTranscribing {
|
||
enum TranscriberError: HexDescribedError {
|
||
case notPrepared
|
||
case emptyTranscript
|
||
case downloadFailed
|
||
case notEnoughMemory
|
||
|
||
var errorDescription: String? {
|
||
switch self {
|
||
case .notPrepared:
|
||
String(localized: "Parakeet Ultra is not ready.")
|
||
case .emptyTranscript:
|
||
String(localized: "Parakeet did not detect any speech.")
|
||
case .downloadFailed:
|
||
String(localized: "Parakeet Ultra didn't download. Check your connection and try again.")
|
||
case .notEnoughMemory:
|
||
String(localized: "Parakeet Ultra needs more memory than Hex has here.")
|
||
}
|
||
}
|
||
}
|
||
|
||
static let name = "Parakeet Ultra"
|
||
/// `ParakeetLoadGuard`'s and `ParakeetCompileRecord`'s keys, apart from V2's.
|
||
static let loadGuardModel = "parakeetUltra"
|
||
static let compileRecordKey = "parakeetUltra.compiledForSystem"
|
||
|
||
/// What loading it takes in Hex, as `ParakeetTranscriber.loadMemory` for V2: the encoder
|
||
/// is 594 MB of int8 weights, which the Neural Engine may hold as 16-bit (1.2 GB) before
|
||
/// the A17, then the other three models (a joint four times V2's) and a first transcription.
|
||
nonisolated static let loadMemory: UInt64 = 1_500 << 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
|
||
}
|
||
|
||
nonisolated let displayName = ParakeetUltraTranscriber.name
|
||
let languageIdentifier: String
|
||
private var manager: AsrManager?
|
||
|
||
init(language: String) {
|
||
languageIdentifier = language
|
||
}
|
||
|
||
var languageName: String {
|
||
SpeechLanguagePicker.displayName(for: languageIdentifier)
|
||
}
|
||
|
||
/// The language the experiment dictates in now, or nil for the engine Hex uses without it:
|
||
/// off, an iPhone without the memory, a language it doesn't know, a load that ended Hex
|
||
/// (`ParakeetLoadGuard`, until the experiment is turned off and on), or less memory left
|
||
/// than loading takes (`os_proc_available_memory`, 0 where iOS sets no limit).
|
||
nonisolated static func chosenLanguage(
|
||
language: String? = MultilingualParakeetSettings().language(),
|
||
availableMemory: UInt64 = UInt64(max(0, os_proc_available_memory())),
|
||
setAside: Bool = ParakeetLoadGuard(model: loadGuardModel).lastLoadWasInterrupted
|
||
) -> String? {
|
||
guard let language, !setAside, hasRoomToLoad(available: availableMemory) else { return nil }
|
||
return language
|
||
}
|
||
|
||
/// "632.2 MB", kept on one line.
|
||
nonisolated static var downloadSize: String {
|
||
ByteCountFormatter.string(fromByteCount: ParakeetUltraModel.totalBytes, countStyle: .file)
|
||
.replacingOccurrences(of: " ", with: "\u{00A0}")
|
||
}
|
||
|
||
/// What the bar says while it downloads: the size, and that Wi-Fi is better for it.
|
||
nonisolated static var downloadDetail: String {
|
||
String(localized: "Downloading \(downloadSize) · Wi-Fi recommended")
|
||
}
|
||
|
||
func prepare(
|
||
progressHandler: @escaping @Sendable (ModelPreparationProgress) -> Void
|
||
) async throws {
|
||
guard manager == nil else { return }
|
||
|
||
let compiled = ParakeetCompileRecord(key: Self.compileRecordKey)
|
||
let downloads = !ParakeetUltraModel.isDownloaded()
|
||
let progress = ParakeetProgressFeed(
|
||
ParakeetPreparationProgress(
|
||
downloads: downloads,
|
||
compiledBefore: compiled.isCurrent,
|
||
downloadDetail: Self.downloadDetail
|
||
),
|
||
emit: progressHandler
|
||
)
|
||
let download: Task<Void, Error>? = downloads ? Task { try await Self.download(progress) } : nil
|
||
let ticker = Task {
|
||
while !Task.isCancelled {
|
||
progress.tick()
|
||
// Turned off mid-download: stop rather than finish a download it then deletes.
|
||
if download != nil, !MultilingualParakeetSettings().isEnabled {
|
||
download?.cancel()
|
||
}
|
||
try? await Task.sleep(for: .milliseconds(250))
|
||
}
|
||
}
|
||
defer { ticker.cancel() }
|
||
|
||
if let download {
|
||
try await withTaskCancellationHandler {
|
||
try await download.value
|
||
} onCancel: {
|
||
download.cancel()
|
||
}
|
||
}
|
||
|
||
// As V2: only the load, where iOS can end Hex short of memory, counts for the guard,
|
||
// and too little left to load it sets it aside for the engine Hex uses without it.
|
||
let loads = ParakeetLoadGuard(model: Self.loadGuardModel)
|
||
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) }
|
||
let models = try ParakeetUltraModel.load {
|
||
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() }
|
||
}
|
||
|
||
/// Resumes each file from its `.partial`; a download that stops moving for
|
||
/// `ParakeetTranscriber.downloadStallLimit` ends, as V2's does.
|
||
private static func download(_ progress: ParakeetProgressFeed) async throws {
|
||
let fraction = ProgressReading()
|
||
do {
|
||
try await StallWatch.run(
|
||
limit: ParakeetTranscriber.downloadStallLimit,
|
||
progress: { fraction.value },
|
||
operation: {
|
||
try await ParakeetUltraModel.download { value in
|
||
fraction.value = value
|
||
progress.update { $0.download(value) }
|
||
}
|
||
}
|
||
)
|
||
} catch is ParakeetUltraModel.DownloadError {
|
||
throw TranscriberError.downloadFailed
|
||
}
|
||
}
|
||
|
||
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: .whitespacesAndNewlines)
|
||
guard !text.isEmpty else {
|
||
throw TranscriberError.emptyTranscript
|
||
}
|
||
return text
|
||
}
|
||
}
|
||
|
||
extension ParakeetUltraTranscriber.TranscriberError: NoSpeechError {
|
||
var meansNoSpeech: Bool { self == .emptyTranscript }
|
||
}
|