hex/ios/HEXKeyboard/KeyboardParakeet.swift
Ryan Vogel 0d3176dc67
iOS Settings: Dictation › Model picks English or Multilingual for the keyboard (#2709)
* iOS keyboard: nothing opens Hex unless the person taps Open Hex

A dictation tap (the Hex key, Dictate, the bar's Hex mark, a hold on the
strip, two-thumb Dictate) opened Hex without saying so in four cases on
iOS 26 and later. Ryan asked that nothing in the keyboard takes people to
Hex unless they tapped something that says it will.

- Multilingual model: removed the hand-off. With Experiments › Multilingual
  model on and ready in Hex, every dictation in its 25 languages (English
  included) opened Hex unless the keyboard had the model loaded at that
  moment (any fresh keyboard process, the first compile, Speech model in
  keyboard off, Two-language dictation, a keyboard limit under 131 MB, a
  memory warning). The keyboard now dictates those languages itself, with
  the model once loaded and Apple's speech recognition until then, as
  English already did. Removed KeyboardSelfDictation.Reason.multilingual,
  MultilingualParakeetSettings.keyboardOpensHex and isModelReady (only that
  read it), KeyboardParakeetSettings.keyboardHasMultilingualModel and
  KeyboardParakeet.dictatesMultilingualHere. The Experiments row no longer
  says "Once ready, keyboard dictation opens Hex."
- Speech model missing twice, short of memory, Hex not set up: from iOS 26
  a dictation tap now shows one line saying why ("Download English in Hex
  to dictate", "Not enough memory to dictate here", "Finish setting up Hex
  to dictate") with Open Hex and a ✕, in the bar's top row and the full
  keyboard's strip (KeyboardDictationBlock), for 8 s. Only Open Hex opens
  Hex (to record there, as the tap used to). The second failure to get the
  speech model shows the line by itself; it goes once the keyboard can
  dictate again. The keyboard's error for that case uses the same words.
- With a warm session the bar's Hex mark dictated by opening Hex; it now
  dictates through the warm session as Dictate does, and VoiceOver names it
  for what it does (Dictate, Set up Hex, or before iOS 26 Open Hex). The Hex
  key's VoiceOver label says "Open Hex to dictate" only where it does.
- The translation note: a tap anywhere on it in the bar opened Hex. Now
  only its Open Hex chip opens Hex's Settings, and a ✕ puts it away (both
  keyboards); the strip notice's title shrinks to 0.7 to fit beside the ✕.

Before iOS 26 nothing changes for a dictation tap: KeyboardDictationBlock
.resolve is nil there and the tap opens Hex as before (Ryan decides).

A simulator-only App Group key (simulator.keyboardMemoryShort) stands in
for a keyboard short of memory, for screenshots.

Verified: build for the simulator; DictationSSOTTests, KeyboardBridgeTests,
SpeechModelInstallTests and the changed DictationControllerTests case pass
on basebook's iOS 27.2 simulator (new cases in DictationSSOTTests); every
line, both keyboards, light and dark, English and Chinese, on the real
keyboard in a host app on the simulator; code-shape --check passes.

* iOS: Hex gets the keyboard's Apple model ready when it dictates with the multilingual model

With Hex's engine on the multilingual model, KeyboardSpeechPreparation
took the keyboard's speech as following Hex (keyboardSpeechFollowsApp was
true for Parakeet Ultra) because the keyboard used to send those
dictations to Hex. Since the previous commit the keyboard dictates them
itself, with Apple's speech recognition until it has the multilingual
model loaded, so Hex now gets that language's Apple model ready for the
keyboard as it does with Parakeet V2. Without this, the keyboard would
have had to download it on its first dictation.

Verified: DictationSSOTTests' engine case updated to expect it; the full
suite runs on the Studio.

* iOS keyboard: say a language is unavailable instead of "Download it in Hex"; bar labels in Chinese

Two follow-ups the coordinator asked for on this pull request.

- When Hex found that Apple has no speech model for the dictation
  language on this iPhone (KeyboardSpeechPreparation's hand-off: Speech
  lists nothing, or the language isn't on this iPhone with nothing to fall
  back to), a dictation tap said "Download <language> in Hex to dictate",
  which downloading can't fix. Hex now marks that case
  (LanguageSettings.keyboardLanguageUnavailable, beside keyboardNeedsHex),
  the keyboard's reason is .languageUnavailable, and the line says
  "<Language> isn't available on this iPhone yet" with only a ✕: no Open
  Hex, since Hex can't download it either. The keyboard's own failures to
  get a model it should have keep "Download <language> in Hex to dictate"
  with Open Hex. A strip notice with no button hides its chip.
- The dictation bar's Dictate, Set up and Set up Hex labels were plain
  strings, so the keyboard showed them in English on a Chinese iPhone. They
  are localized now (听写, 开始设置, 设置 Hex were already in the catalog).

Verified: DictationSSOTTests (new cases for the unavailable line and
reason), KeyboardBridgeTests, SpeechModelInstallTests and
DictationControllerTests pass on basebook's iOS 27.2 simulator (143 tests).

* iOS docs: the keyboard's line when a language isn't available on the iPhone

Documents the previous commit: where Hex found Apple has no speech model for
the dictation language, the keyboard says so with only a ✕.

* iOS Settings: Dictation › Model picks English or Multilingual for the keyboard

Ryan asked for the keyboard's speech model to be chosen in Settings,
English or multilingual, now that the keyboard dictates the multilingual
model's languages itself (previous pull request).

- Settings › Dictation's speech model card gets Model: English ·
  Multilingual (SpeechModelChoice, SpeechModelChoiceRow) under Speech model
  in keyboard, on iPhones with 6 GB or more; under that the switch above
  already says it needs 6 GB and the row doesn't show. English stays the
  default. Multilingual is the existing setting
  (MultilingualParakeetSettings, experiments.multilingualParakeet), so Hex's
  own dictation follows it as it did from Experiments.
- Each choice says what it means before anything downloads: English, "For
  English. A 464.4 MB download, once, on Wi-Fi."; Multilingual, its 25
  languages by name in the iPhone's language and "A 632.2 MB download, once,
  as soon as you pick it. Hex dictates them with it too."; and both, that
  other languages use Apple's speech recognition and a downloaded model
  stays.
- Picking English no longer deletes a complete multilingual download, so
  switching back is instant (ParakeetUltraModel.removeUnlessComplete, also
  at launch); a part-way one still goes. English's model already stayed
  while Multilingual was on.
- With Multilingual picked, the card shows its download or failure
  (MultilingualModelStatus, whose Turn off is now Use English) and, with
  the keyboard switch on, what the keyboard does with it
  (KeyboardParakeetStatus.multilingualLine). The switch's detail no longer
  says "For English": "The keyboard dictates with the model below."
- Removed Experiments › Multilingual model (Parakeet) and its strings.
- Docs: dictation.md, settings-and-home.md, acknowledgements.

Verified: build for the simulator; DictationSSOTTests,
DictationControllerTests and KeyboardBridgeTests pass on basebook's iOS 27.2
simulator (129 tests, new cases for the multilingual status line, the
language names, and keeping a complete download); the card in English and
Multilingual, English and Simplified Chinese, from the app on the
simulator; code-shape --check passes.

* iOS Settings › Model keeps only the picked model, once the new one is ready

The coordinator decided against keeping both models (about 1.3 to 1.6 GB
for one the person switched away from). Only the picked model stays.

- SpeechModelChoice.unpicked decides what to remove: the other model goes
  only once the picked one is downloaded and has loaded once, in Hex or
  the keyboard, and never while Hex dictates with it, so nobody is left
  with neither and a failed or cancelled download leaves the old one in
  place. DictationController.keepOnlyThePickedSpeechModel runs it whenever
  Hex comes to the front (launch included) and once Hex has loaded the
  multilingual model.
- Until then the old model keeps dictating English in the keyboard
  (KeyboardParakeetPlan): with Multilingual picked and its model not here
  yet, English's model (readyV2); with English picked and its model not
  here yet, the multilingual one (new awaitingV2DownloadUsingUltra, which
  still lets English's model download by itself). Before, the keyboard
  fell back to Apple's speech recognition in both.
- The keyboard records that a model loaded (KeyboardParakeetSettings
  .hasLoadedOnce, App Group). Removing a model clears that, its compile
  record (ParakeetUltraModel.remove now forgets Ultra's) and the keyboard's
  state about it, and sets purgesCompiled: before its next load the
  keyboard removes its Core ML compiled copies
  (Library/Caches/<bundle>/com.apple.e5rt.e5bundlecache, where a probe
  keyboard's syslog on an iPhone 17 Pro showed them; 234 MB for English's
  model), so the picked one compiles again once (12 to 17 s, Apple's
  speech recognition meanwhile). The Neural Engine's own cache
  (com.apple.aned) and Hex's own compiled copy are left to iOS.
- The card says so: "Only the picked model stays on this iPhone: switching
  downloads the new one, and the old one goes once the new one is ready."
  The choices no longer say "once".

Storage: English about 700 MB (464 MB download, 234 MB compiled in the
keyboard); Multilingual about 0.9 to 1.2 GB (632 MB download, compiled
copies not measured); both for a while during a switch.

Verified: build for the simulator; DictationSSOTTests (plan fallbacks and
the removal table), DictationControllerTests and KeyboardBridgeTests on
basebook's iOS 27.2 simulator; the card in English and Chinese. Untested:
the removal and the keyboard's purge on a phone (no Neural Engine or real
compile in the simulator).
2026-11-24 17:28:50 -05:00

418 lines
20 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 CoreML
import Darwin
import FluidAudio
import Foundation
/// Settings › Dictation › Speech model in keyboard (on unless turned off): the keyboard's own dictation
/// transcribed with Parakeet on the Neural Engine, in the keyboard's process, so Hex needn't be
/// open or warm.
/// English uses Parakeet V2; a language Settings › Dictation › Model: Multilingual dictates uses Parakeet
/// Ultra. Both load from the App Group (`SpeechModelStore`), after the keyboard's first frame
/// and launch work (`warmUp`), and stay loaded while the keyboard's process lives, until a
/// memory warning. The first load compiles the model for the Neural Engine (17 s for V2, 12 s
/// for Ultra on an iPhone 17 Pro); dictation never waits for it. Whenever the experiment is off
/// or the model isn't loaded, on the Neural Engine and within the keyboard's memory
/// (`KeyboardParakeetBudget`), `KeyboardTranscription` uses Apple's speech recognition,
/// exactly as with the experiment off.
@MainActor
final class KeyboardParakeet {
static let shared = KeyboardParakeet()
struct Choice: Equatable {
let multilingual: Bool
/// BCP 47: the language the text goes through Hex's steps in.
let language: String
var directory: URL { multilingual ? SpeechModelStore.parakeetUltra : SpeechModelStore.parakeetV2 }
var engineName: String { multilingual ? "Parakeet Ultra (keyboard)" : "Parakeet V2 (keyboard)" }
var label: String { multilingual ? "parakeet-ultra" : "parakeet-v2" }
}
struct Transcript {
let text: String
let language: SpeechLanguage
let engine: String
}
private struct Loaded {
let multilingual: Bool
let manager: AsrManager
let seconds: Double
let cold: Bool
let at: Date
}
private var loaded: Loaded?
private var loadTask: Task<Void, Never>?
/// Models that didn't load or didn't run on the Neural Engine in this process.
private var setAside: Set<Bool> = []
private var memoryWarnedAt: Date?
private var isTranscribing = false
private var releasesAfterTranscription = false
private var lastNote = ""
/// iOS ends nothing for a load past this; the keyboard stops saying it's getting ready.
static let loadPatience: TimeInterval = 180
/// Evidence the model is on the Neural Engine: the keyboard's Neural Engine memory, which
/// rose 468 MB (V2) and 607 MB (Ultra) on the iPhone 17 Pro.
static let neuralEngineEvidence = 100 * KeyboardParakeetBudget.megabyte
/// After a memory warning, no new load in this process for this long.
static let reloadAfterWarning: TimeInterval = 300
/// A load this long compiled the model: on an iPhone 17 Pro a load Core ML had compiled
/// before took 0.3 s, one that compiled 11.6 s (Ultra) to 16.5 s (V2).
static let compilingLoad: TimeInterval = 5
/// The model the keyboard would transcribe with, or nil for Apple's speech recognition,
/// resolved from the shared `KeyboardParakeetPlan`.
nonisolated static func choice() -> Choice? {
guard let picked = KeyboardParakeetPlan.current().modelChoice else { return nil }
return Choice(multilingual: picked.model.isMultilingual, language: picked.language)
}
/// After the keyboard's first frame and launch work: notes the keyboard's memory limit for
/// Hex's download, then loads the model it would use, off the main thread, when it fits.
func warmUp() {
let measured = Self.memory()
if measured.available > 0 {
KeyboardParakeetSettings().recordKeyboardLimit(measured.footprint + measured.available)
}
guard let choice = Self.choice() else { return }
if loaded?.multilingual == choice.multilingual { return }
guard loadTask == nil, !setAside.contains(choice.multilingual) else { return }
if let warned = memoryWarnedAt, Date().timeIntervalSince(warned) < Self.reloadAfterWarning { return }
let memory = Self.memory()
let settings = KeyboardParakeetSettings()
guard KeyboardParakeetBudget.allowsLoad(footprint: memory.footprint, available: memory.available) else {
note("parakeet: \(choice.label) not loaded, short of memory \(memory)")
settings.setKeyboardState(.unavailable)
return
}
guard Self.hasNeuralEngine else {
note("parakeet: no Neural Engine here")
setAside.insert(choice.multilingual)
settings.setKeyboardState(.unavailable)
return
}
if loaded != nil { release(reason: "language changed") }
// Hex removed the model the person switched away from: its compiled copy goes too.
if settings.purgesCompiled {
settings.purgesCompiled = false
Self.purgeCompiledModels()
}
settings.setKeyboardState(.preparing)
KeyboardProbeLog.shared.write("parakeet: loading \(choice.label) \(memory)")
let started = Date()
loadTask = Task { [weak self] in
let neuralBefore = Self.memory().neural
do {
let manager = try await Self.load(choice)
let after = Self.memory()
let onEngine: Bool
if after.neural - neuralBefore >= Self.neuralEngineEvidence {
onEngine = true
} else {
// Before iOS 27 the Neural Engine's memory isn't the process's: ask Core ML.
onEngine = after.neural == 0 ? await Self.plansNeuralEngine(choice) : false
}
guard let self else { return }
self.loadTask = nil
let seconds = Date().timeIntervalSince(started)
guard onEngine else {
await manager.cleanup()
self.setAside.insert(choice.multilingual)
settings.setKeyboardState(.unavailable)
KeyboardProbeLog.shared.write("parakeet: \(choice.label) not on the Neural Engine, Apple's speech recognition \(Self.memory())")
return
}
let cold = seconds >= Self.compilingLoad
self.loaded = Loaded(multilingual: choice.multilingual, manager: manager, seconds: seconds, cold: cold, at: Date())
settings.setKeyboardState(.ready, multilingual: choice.multilingual)
settings.setLoadedOnce(true, multilingual: choice.multilingual)
KeyboardProbeLog.shared.write(
"parakeet: \(choice.label) loaded in \(String(format: "%.1f", seconds)) s (\(cold ? "cold" : "warm")) \(after)"
)
} catch {
guard let self else { return }
self.loadTask = nil
self.setAside.insert(choice.multilingual)
settings.setKeyboardState(.unavailable)
KeyboardProbeLog.shared.write("parakeet: \(choice.label) didn't load: \(error) \(Self.memory())")
}
}
Task { [weak self] in
try? await Task.sleep(for: .seconds(Self.loadPatience))
guard let self, self.loadTask != nil, self.loaded == nil else { return }
KeyboardParakeetSettings().setKeyboardState(.unavailable)
KeyboardProbeLog.shared.write("parakeet: \(choice.label) still loading after \(Int(Self.loadPatience)) s")
}
}
/// Transcribes `url` with the loaded model, or returns nil for Apple's speech recognition
/// (with the reason in the probe log): the experiment off, the model not loaded yet, another
/// transcription running, a recording longer than `KeyboardParakeetBudget.longestAudio` or
/// without the room it needs, nothing heard, or an error.
func transcribe(_ url: URL, audioSeconds: Double) async -> Transcript? {
guard let choice = Self.choice() else { return nil }
let before = Self.memory()
func fallback(_ reason: String) -> Transcript? {
KeyboardProbeLog.shared.write("parakeet: dictation engine=apple (\(reason)) audio=\(String(format: "%.1f", audioSeconds)) s \(before)")
return nil
}
guard let loaded, loaded.multilingual == choice.multilingual else {
return fallback(loadTask != nil ? "\(choice.label) still loading" : "\(choice.label) not loaded")
}
guard !isTranscribing else { return fallback("another transcription running") }
// FluidAudio holds the whole recording in memory; Apple's speech recognition streams it.
guard audioSeconds <= KeyboardParakeetBudget.longestAudio else {
return fallback("longer than \(Int(KeyboardParakeetBudget.longestAudio)) s")
}
guard KeyboardParakeetBudget.allowsTranscription(
footprint: before.footprint, available: before.available, audioSeconds: audioSeconds
) else {
return fallback("short of memory for \(String(format: "%.0f", audioSeconds)) s of audio")
}
isTranscribing = true
defer {
isTranscribing = false
if releasesAfterTranscription {
releasesAfterTranscription = false
release(reason: "memory warning")
}
}
let sampler = FootprintPeak()
sampler.start()
let started = Date()
do {
let manager = loaded.manager
let layers = await manager.decoderLayerCount
var state = TdtDecoderState.make(decoderLayers: layers)
let result = try await manager.transcribe(url, decoderState: &state)
let seconds = Date().timeIntervalSince(started)
let peak = sampler.stop()
let text = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else { return fallback("\(choice.label) heard nothing") }
KeyboardProbeLog.shared.write(String(
format: "parakeet: dictation engine=%@ limit=%.0f MB footprint before=%.1f MB peak=%.1f MB load=%.1f s (%@, %.0f s ago) transcribe=%.2f s audio=%.1f s neural=%.0f MB",
choice.label, Self.mb(before.footprint + before.available), Self.mb(before.footprint), Self.mb(peak),
loaded.seconds, loaded.cold ? "cold" : "warm", Date().timeIntervalSince(loaded.at), seconds, audioSeconds,
Self.mb(Self.memory().neural)
))
return Transcript(
text: text,
language: SpeechLanguage(locale: Locale(identifier: choice.language), module: .speech),
engine: choice.engineName
)
} catch {
_ = sampler.stop()
return fallback("\(choice.label) failed: \(error)")
}
}
/// iOS warned the keyboard about memory: the model goes, now or once its transcription
/// ends, and no new load starts in this process for `reloadAfterWarning`.
func handleMemoryWarning() {
memoryWarnedAt = Date()
guard loaded != nil else { return }
if isTranscribing {
releasesAfterTranscription = true
} else {
release(reason: "memory warning")
}
}
private func release(reason: String) {
guard let current = loaded else { return }
loaded = nil
Task { await current.manager.cleanup() }
if KeyboardParakeetSettings().isEnabled {
KeyboardParakeetSettings().setKeyboardState(nil)
}
KeyboardProbeLog.shared.write("parakeet: released (\(reason)) \(Self.memory())")
}
private func note(_ message: String) {
guard message != lastNote else { return }
lastNote = message
KeyboardProbeLog.shared.write(message)
}
/// Removes Core ML's compiled copies in the keyboard's Caches (`com.apple.e5rt.e5bundlecache`,
/// 234 MB for English's model on an iPhone 17 Pro), once Hex removed the model the person
/// switched away from (`KeyboardParakeetSettings.purgesCompiled`). Only before a load, with
/// nothing loaded: the picked model compiles again (12 to 17 s, Apple's speech recognition
/// meanwhile). The Neural Engine's own cache is iOS's (`com.apple.aned`), out of reach.
nonisolated static func purgeCompiledModels() {
let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
var folders = [caches.appendingPathComponent("com.apple.e5rt.e5bundlecache", isDirectory: true)]
if let bundle = Bundle.main.bundleIdentifier {
folders.append(caches.appendingPathComponent(bundle, isDirectory: true)
.appendingPathComponent("com.apple.e5rt.e5bundlecache", isDirectory: true))
}
for folder in folders where FileManager.default.fileExists(atPath: folder.path) {
let removed = (try? FileManager.default.removeItem(at: folder)) != nil
KeyboardProbeLog.shared.write("parakeet: compiled copies \(removed ? "removed" : "not removed") at \(folder.lastPathComponent)")
}
}
// MARK: - Loading
/// The four models as the app loads Parakeet (the preprocessor on the CPU, the rest on the
/// CPU and Neural Engine, never the GPU, which a keyboard may only use in the background
/// role), off the main thread; one chunk at a time.
nonisolated private static func load(_ choice: Choice) async throws -> AsrManager {
let models = try await Task.detached(priority: .utility) { try loadModels(choice) }.value
let manager = AsrManager(config: ASRConfig(parallelChunkConcurrency: 1))
try await manager.loadModels(models)
return manager
}
nonisolated private static func loadModels(_ choice: Choice) throws -> AsrModels {
let directory = choice.directory
func model(_ name: String, _ units: MLComputeUnits) throws -> MLModel {
let configuration = AsrModels.defaultConfiguration()
configuration.computeUnits = units
return try MLModel(contentsOf: directory.appendingPathComponent(name), configuration: configuration)
}
let preprocessor = try model(ModelNames.ASR.preprocessorFile, .cpuOnly)
let encoder = try model(ModelNames.ASR.encoderFile, .cpuAndNeuralEngine)
let decoder = try model(ModelNames.ASR.decoderFile, .cpuAndNeuralEngine)
let joint = try model(choice.multilingual ? ModelNames.ASR.jointV3File : ModelNames.ASR.jointFile, .cpuAndNeuralEngine)
let data = try Data(contentsOf: directory.appendingPathComponent(ModelNames.ASR.vocabularyFile))
var vocabulary: [Int: String] = [:]
for (key, token) in (try JSONSerialization.jsonObject(with: data) as? [String: String]) ?? [:] {
if let id = Int(key) { vocabulary[id] = token }
}
let configuration = AsrModels.defaultConfiguration()
return AsrModels(
encoder: encoder,
preprocessor: preprocessor,
decoder: decoder,
joint: joint,
configuration: configuration,
vocabulary: vocabulary,
version: choice.multilingual ? .v3 : .v2
)
}
nonisolated private static var hasNeuralEngine: Bool {
MLModel.availableComputeDevices.contains { device in
if case .neuralEngine = device { return true }
return false
}
}
/// Whether Core ML puts most of the encoder's work on the Neural Engine.
nonisolated private static func plansNeuralEngine(_ choice: Choice) async -> Bool {
let configuration = AsrModels.defaultConfiguration()
configuration.computeUnits = .cpuAndNeuralEngine
guard let plan = try? await MLComputePlan.load(
contentsOf: choice.directory.appendingPathComponent(ModelNames.ASR.encoderFile),
configuration: configuration
), case .program(let program) = plan.modelStructure else { return false }
var neural = 0.0
var total = 0.0
func walk(_ block: MLModelStructure.Program.Block) {
for operation in block.operations {
let weight = plan.estimatedCost(of: operation)?.weight ?? 0
total += weight
if case .neuralEngine = plan.deviceUsage(for: operation)?.preferred { neural += weight }
operation.blocks.forEach(walk)
}
}
program.functions.values.forEach { walk($0.block) }
return total > 0 && neural / total >= 0.5
}
// MARK: - Memory
struct Memory: CustomStringConvertible {
let footprint: Int
let available: Int
/// The Neural Engine's memory for this process, outside the footprint iOS limits.
let neural: Int
var description: String {
String(
format: "[limit %.0f MB, footprint %.1f MB, available %.1f MB, neural %.0f MB]",
KeyboardParakeet.mb(footprint + available), KeyboardParakeet.mb(footprint),
KeyboardParakeet.mb(available), KeyboardParakeet.mb(neural)
)
}
}
nonisolated static func memory() -> Memory {
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)
}
}
guard result == KERN_SUCCESS else { return Memory(footprint: 0, available: os_proc_available_memory(), neural: 0) }
return Memory(
footprint: Int(info.phys_footprint),
available: os_proc_available_memory(),
neural: Int(info.ledger_tag_neural_nofootprint + info.ledger_tag_neural_nofootprint_compressed)
)
}
nonisolated static func mb(_ bytes: Int) -> Double {
Double(bytes) / Double(KeyboardParakeetBudget.megabyte)
}
}
/// The highest footprint while a transcription runs, sampled every 20 ms.
private nonisolated final class FootprintPeak: @unchecked Sendable {
private let lock = NSLock()
private var peak = 0
private var timer: DispatchSourceTimer?
func start() {
let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility))
timer.schedule(deadline: .now(), repeating: .milliseconds(20), leeway: .milliseconds(5))
timer.setEventHandler { [weak self] in
self?.record(KeyboardParakeet.memory().footprint)
}
timer.resume()
self.timer = timer
}
private func record(_ footprint: Int) {
lock.withLock { peak = max(peak, footprint) }
}
func stop() -> Int {
timer?.cancel()
timer = nil
record(KeyboardParakeet.memory().footprint)
return lock.withLock { peak }
}
}
/// The keyboard's transcription: Parakeet where `KeyboardParakeet` can, else Apple's speech
/// recognition exactly as before (`KeyboardSpeech`). Returns the engine's name with the text.
@available(iOS 26.0, *)
enum KeyboardTranscription {
static func transcribe(_ url: URL, hints: [String], audioSeconds: Double) async throws -> (String, SpeechLanguage, String) {
if let parakeet = await KeyboardParakeet.shared.transcribe(url, audioSeconds: audioSeconds) {
noteLanguage(parakeet.language)
return (parakeet.text, parakeet.language, parakeet.engine)
}
let started = Date()
let (text, language) = try await KeyboardSpeech.transcribe(url, hints: hints)
if KeyboardParakeetSettings().isEnabled {
KeyboardProbeLog.shared.write(String(
format: "parakeet: dictation engine=apple transcribe=%.2f s audio=%.1f s %@",
Date().timeIntervalSince(started), audioSeconds, KeyboardParakeet.memory().description
))
}
let engine = language.module == .dictation ? "Apple Speech (keyboard, DictationTranscriber)" : "Apple Speech (keyboard)"
noteLanguage(language)
return (text, language, engine)
}
/// For Settings' Translate what I say, which checks the pair the keyboard translates.
private static func noteLanguage(_ language: SpeechLanguage) {
DictationTranslationSettings().noteKeyboardDictation(in: language.identifier, languages: LanguageSettings())
}
}