hex/ios/HEXShared/DictationTranslation.swift
Ryan Vogel ee34feb49b iOS: dictate in every language Apple Speech has on device
A Norwegian TestFlight tester's iPhone silently fell back to English:
Hex picked the first preferred language SpeechTranscriber supports, and
SpeechTranscriber has no Norwegian, Danish, Swedish or Hebrew. Testers
also asked for Spanish and German.

What changed:
- SpeechLanguagePicker picks the dictation language: an explicit choice
  wins (SpeechTranscriber where it has the language, else
  DictationTranscriber); Automatic takes the first preferred iPhone
  language either module has, SpeechTranscriber first for the same
  language, then the region's locale, then en-US. Nynorsk tries Bokmal.
- AppleSpeechModule wraps SpeechTranscriber and DictationTranscriber
  (preset longDictation) for the same SpeechAnalyzer flow and asset
  download; the app's AppleSpeechTranscriber and in-keyboard dictation
  both use it and AppleSpeechLanguages, so they resolve the same language
  and share downloaded assets.
- Settings > Dictation language (iOS 26): Automatic plus every locale
  either module supports, by name, saved in the App Group
  (settings.dictationLanguage). Picking one prepares its model now, or
  after the dictation in flight. The setup card's Speech model row names
  the real language ("Norwegian Bokmal · Apple").
- English-only steps follow the language: the cleanup tagger skips other
  languages; Apple Intelligence cleanup runs only when the model supports
  the language; filler trimming is per language (English "er" was eating
  Norwegian "er" = "is"; Portuguese "um" is a word); translation's source
  is the dictation language instead of a guess.
- Replaced: AppleSpeechTranscriber.preferredLocale()/isAvailable with
  preferredLanguage()/shouldUse(_:). An iPhone without SpeechTranscriber
  still dictates English with Parakeet, as before.

Verified: xcodebuild test on the iPhone 18 Pro simulator (iOS 27.2),
189 tests, 0 failures, including new picker, language-change, filler and
tagger tests; Release generic-iOS build with CODE_SIGNING_ALLOWED=NO
succeeds. The simulator can't transcribe (SpeechTranscriber unavailable,
DictationTranscriber "Model not available"); the same Swift files built
for macOS 26 transcribed say clips word for word: de-DE and es-ES via
SpeechTranscriber, nb-NO and he-IL via DictationTranscriber (no
punctuation from DictationTranscriber under any preset). Not tried on a
physical iPhone.
2026-11-20 07:52:32 -05:00

62 lines
2.6 KiB
Swift

import Foundation
import NaturalLanguage
@preconcurrency import Translation
/// Experiment (Translate what I say): speak one language, insert another. Translation
/// runs on the iPhone with Apple's Translation framework once the language pack is
/// downloaded in Hex; with no pack, the original transcript goes in unchanged.
struct DictationTranslationSettings {
private enum Key {
static let enabled = "experiments.translateDictation"
static let target = "experiments.translateDictation.target"
}
private let defaults: UserDefaults?
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
self.defaults = defaults
}
var isEnabled: Bool {
get { defaults?.bool(forKey: Key.enabled) ?? false }
nonmutating set { defaults?.set(newValue, forKey: Key.enabled) }
}
/// BCP 47 language code, such as `ja`.
var targetLanguage: String {
get { defaults?.string(forKey: Key.target) ?? "ja" }
nonmutating set { defaults?.set(newValue, forKey: Key.target) }
}
}
enum DictationTranslator {
/// The translated text, or nil when the experiment is off, the speech is already in
/// the target language, or the pack isn't downloaded. `source` is the dictation
/// language; without one the text's language is guessed.
@MainActor
static func translateIfEnabled(
_ text: String,
source: Locale.Language? = nil,
settings: DictationTranslationSettings = DictationTranslationSettings()
) async -> String? {
guard settings.isEnabled, #available(iOS 26.0, *) else { return nil }
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, let source = source ?? detectedLanguage(of: trimmed) else { return nil }
let target = Locale.Language(identifier: settings.targetLanguage)
guard source.languageCode != target.languageCode else { return nil }
guard await LanguageAvailability().status(from: source, to: target) == .installed else { return nil }
do {
let session = TranslationSession(installedSource: source, target: target)
let response = try await session.translate(trimmed)
let translated = response.targetText.trimmingCharacters(in: .whitespacesAndNewlines)
return translated.isEmpty ? nil : translated
} catch {
return nil
}
}
static func detectedLanguage(of text: String) -> Locale.Language? {
guard let language = NLLanguageRecognizer.dominantLanguage(for: text) else { return nil }
return Locale.Language(identifier: language.rawValue)
}
}