hex/ios/HEXMobile/ParakeetTranscriber.swift
Ryan Vogel fbaf09648e iOS: end empty dictations quietly and keep error text human in the keyboard
Tapping Done (or ✕) in the keyboard's dictation screen without speaking
showed "Transcription failed: HEXKeyboard.(unknown context at $1…)": the
in-keyboard path printed the error's domain (a private Swift type name),
code and description for Apple Speech's "no words" result.

- New EmptyCapture rule (HEXShared): a capture under 0.3 s (or none at all)
  is a tap, and an engine's no-speech error or a cancellation means nothing
  was said; both end quietly. Engines say so through NoSpeechError
  (Parakeet's and Apple Speech's emptyTranscript, the keyboard's
  KeyboardSpeech.Failure.empty).
- KeyboardLocalDictation: Done before the microphone came up, or a capture
  too short to hold a word, returns to idle without transcribing (and a late
  "started" from WebKit stops the capture instead of opening a file);
  no-speech ends quietly; a transcription error from a cancelled or
  superseded job is dropped; every other failure shows a sentence from
  UserFacingError or the keyboard's own copy, while the probe log keeps the
  domain and code. KeyboardSpeech.Failure's descriptions are now sentences.
- DictationController (warm session and app): an engine's no-speech error
  returns to Ready with no message instead of failing.

Verified: xcodebuild test on the iPhone 18 Pro simulator after rebasing onto
origin/dev (bba07c64), 210 tests pass (1 skipped as before), including new
tests for the empty-capture rule and for a warm keyboard dictation whose
transcriber hears nothing (Ready, no message) next to one that fails (a
sentence). The in-keyboard WebKit capture path needs a physical iPhone.
2026-11-20 08:00:56 -05:00

113 lines
3.5 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: LocalizedError {
case notPrepared
case emptyTranscript
var errorDescription: String? {
switch self {
case .notPrepared:
"Parakeet V2 is not ready."
case .emptyTranscript:
"Parakeet did not detect any speech."
}
}
}
private var manager: AsrManager?
nonisolated let displayName = "Parakeet V2"
let languageName = "English"
nonisolated static var hasCachedModel: Bool {
AsrModels.modelsExist(
at: AsrModels.defaultCacheDirectory(for: .v2),
version: .v2
)
}
func prepare(
progressHandler: @escaping @Sendable (ModelPreparationProgress) -> Void
) async throws {
guard manager == nil else { return }
let models = try await AsrModels.downloadAndLoad(
version: .v2,
progressHandler: { progress in
progressHandler(
ModelPreparationProgress(
fractionCompleted: progress.fractionCompleted,
detail: Self.detail(for: progress.phase)
)
)
}
)
let manager = AsrManager(config: .default)
try await manager.loadModels(models)
self.manager = manager
}
private static func detail(for phase: DownloadPhase) -> String {
switch phase {
case .listing:
"Checking model files"
case .downloading(let completedFiles, let totalFiles):
"Downloading file \(min(completedFiles + 1, totalFiles)) of \(totalFiles)"
case .compiling(let modelName):
"Compiling \(modelName)"
}
}
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
}
}
extension ParakeetTranscriber.TranscriberError: NoSpeechError {
var meansNoSpeech: Bool { self == .emptyTranscript }
}