mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-27 07:58:01 +01:00
* docs: define the Hex words file (.hexwords), version 1, with shared cases Ryan approved sharing vocabulary and word replacements between the desktop, iPhone and Android apps through a file the person moves themselves. Three builders start from this in parallel, so the format is written down and frozen first, with cases all three apps must pass. - docs/specs/hex-words.md: every field and limit, how text is cleaned and compared, the reading order with its refusal and skip reasons, versions, what each app writes, the merge rules (desktop and phone) and Undo, the file's name and type on each platform, and what a reader must never do. - tests/fixtures/hex-words: read.json (54 cases over files/, from small to hostile: not UTF-8, 10,000 levels deep, duplicate keys, lone surrogates, 8 MiB + 1 byte generated), merge.json (24 desktop and phone cases), write.json (6 cases) and hex-words.schema.json (JSON Schema 2020-12 for writer output). files/ is byte-exact (-text -whitespace). - docs/README.md links the spec. No app code changes. The typing config (.mhexconfig) stays separate: its parts need evidence and Full Access, and it describes one phone's keyboard. Verified: the expected results were produced by a throwaway Python reference reader, merger and writer (not committed) and read through by hand; every write.json output and the valid read results re-written validate against the schema with jsonschema 4.26, and five malformed writer outputs are rejected; a file with every list at its limits in 4-byte characters is 6.5 MiB, under the 8 MiB cap; markdownlint-cli2 is clean on the new docs. * docs(hex-words): Android parses with its own strict parser org.json is lenient and neither it nor android.util.JsonReader runs in the app's JVM unit tests, which is where the shared cases run. Verified: markdownlint-cli2 clean. * iOS: read, merge and write Hex words files (.hexwords), with the shared cases Adds ios/HEXShared/HexWords/, the iPhone's implementation of docs/specs/hex-words.md: - HexWordsCheck: the spec's check pass, one non-recursive walk over the bytes before JSONSerialization: more than 8 levels (tooDeep), a repeated key compared byte for byte after decoding escapes (duplicateKey), and everything strict RFC 8259 forbids that JSONSerialization lets through, escaped lone surrogates included (notJSON). - HexWordsReader: size, BOM, UTF-8 (checked by a lossless round trip), empty, check pass, then JSONSerialization. Objects stay NSDictionary, because bridging keys that differ only in normalization into one Swift dictionary would trap. Booleans are told from numbers by CFBoolean, so "learned": 1 is badField and "version": true is badVersion. Lengths count unicodeScalars, letters are general category L or N, whitespace is the spec's exact list, and the key lowercases scalar by scalar then maps final sigma to sigma. - HexWordsMerge: the phone column of the merge table. - HexWordsWriter: the phone's export, by the reader's own rules and order. - WordReplacementsSettings and HexWordsImport (Add and Undo) in the App Group. HexWordsSharedCasesTests loads tests/fixtures/hex-words in place (a folder resource in project.yml) and runs every read case, the phone's merge and write cases (the desktop's are the desktop's), Undo after each merge, and a small JSON Schema check of what the writer writes. Checked on anomastudio (iOS 27.2 simulator, simlanes): read.json 54/54, merge.json 11/11 phone cases, write.json 2/2 phone cases. * docs(hex-words): pin refusal order and out-of-range numbers; clarify writer order and phone scope The Android builder found three places where implementations could disagree: - Two problems in one file: the spec said 'the first met' but no case pinned it. It now says where each problem is met, and three cases pin it (duplicate key first, too deep first, syntax error first). - A number a 64-bit float can't hold (1e400, a 400-digit integer): serde_json refuses it, while other parsers read it as infinity. It is now notJSON wherever it appears, with two cases. - A writer checks a full list's limit first, in the reader's order. Also written down: on a phone, Word replacements apply to the app's and the keyboard's dictations (never translated ones), and on Android learned fixes are 'in use' only while Learn from my fixes is on. Verified: the reference reader (now a single sequential check pass) regenerates read.json with only the five new cases changed; merge.json and write.json are unchanged; markdownlint-cli2 is clean. * iOS words files: refuse numbers no 64-bit float holds; refusal order as the spec pins it Spec update9fa746aa6: a number a 64-bit float can't hold (1e400, a 400-digit integer) is notJSON wherever it is. JSONSerialization would read it, so the check pass converts each number token and refuses one that isn't finite. The walk already refused for the first problem met (a key at its second appearance, the bracket past 8 levels, or where the text stops being strict JSON); the doc comment now says so. Checked on anomastudio (iOS 27.2 simulator): read.json 59/59 with the new first-problem-* and number-out-of-range* cases. * iOS: Word replacements, opening and exporting Hex words files, behind Custom vocabulary Word replacements: a new list (heard -> write, up to 1,000, the words file's limits, no empty or blank outputs yet) under Settings > Dictation > Custom vocabulary, shown and applied only while that switch is on. They apply in DictationPipeline, so in the app and in-keyboard dictation alike, right before the learned fixes with DictationCorrections.apply's matching (now taking up to 8 words for them), and win over a learned fix with the same heard words. Learned fixes are never changed. A dictation Translate what I say translates gets none; one that goes in as spoken does. Opening: Info.plist (project.yml) exports anomaly.hex.words (public.json, .hexwords, application/vnd.anomaly.hex-words+json) and owns it as a document type copied in (LSSupportsOpeningDocumentsInPlace NO). HexInbox, a small inbox shaped for another file kind later (#2529), copies the file privately, reads it, shows HexWordsReviewSheet over whatever is on screen and deletes both copies when the sheet closes; it logs counts and reasons only. The sheet shows what is added, already there, clashes (Keep mine by default), what this iPhone can't use, what the file skipped, a switch per part, and offers to turn Custom vocabulary on. Strings from the file are Text(verbatim:), direction-isolated and shortened. Add shows a one-line confirmation with Undo; "Undo last import" stays in settings until either list changes or another file is imported. Export: Export words opens a sheet with "Include fixes Hex learned" (off), what is left out and why, then the share sheet with hex-words.hexwords, deleted after sharing. ShareSheet.present gains an optional completion. Every new string has English and Simplified Chinese. Docs: dictation.md and settings-and-home.md. Checked on anomastudio (iOS 27.2 simulator): HexWordsSharedCasesTests (read 59/59, merge 11/11 phone, write 2/2 phone), WordReplacementsTests, CustomVocabulary, DictationLearning, DictationSSOT, DictationController, Greeklish and TranscriptCleanup tests all pass. * iOS words files: Android's words and pages; madeBy.version from the bundle Ryan approved Android's words screens, so the iPhone now uses the same English and Simplified Chinese (Android's words_* strings) and the same shape: - Custom vocabulary's card gets Word replacements and Words file rows (and Undo last import while an import can be undone) instead of the inline editor and the Export words sheet, which are removed. - Word replacements page: Android's intro, fields, problems and list. - Words file page: Open a words file... (Files picker into HexInbox), Export with Include fixes Hex learned (only while a learned fix is in use) and Share..., and the exported / left-out line. - Review sheet: a full page with Android's title, made-by line, counts ("2 new · 1 already there · 1 different from yours"), Yours: / This file:, Keep mine / Use this one, the not-usable and skipped sentences, Add and Cancel; then "Words added" with the one-line confirmation, Undo and Done; refusals in Android's sentences. Add no longer waits for the Custom vocabulary switch: as on Android the words are added and unused until it is on. Differences iOS forces: "phone" reads "iPhone"; no Save to... row (the share sheet's Save to Files does it); the app's own remove button and segmented control; the existing "Vocabulary" key keeps its zh 词汇表. madeBy.version comes from HexWordsWriter.appVersion(), the bundle's CFBundleShortVersionString (MARKETING_VERSION, 9.0.0 today); testWriterWritesTheBundlesVersion checks it, and testReviewSheetWords the English plurals. Built on anomastudio (build-for-testing, iOS 27.2 simulator SDK). The unit tests for this commit wait on the simulator queue, which simlanes is holding (swap gate). * docs(hex-words): a phone's spelling-replacement that repeats an earlier one is a duplicate The iPhone builder asked what happens when two terms in one file share a spelling: on a phone both would become replacements with the same heard words. The spec only covered a spelling against the file's own replacements. Now: the earlier one wins (the file's own replacements come first), and a later one is notApplied as duplicate. One new phone merge case. Verified: the reference merger regenerates merge.json with only the new case added (25 cases); read.json and write.json unchanged; markdownlint clean. * iOS words files: a file that can't be opened says Android's "couldn't open" sentence HexWordsReader.read(contentsOf:) returned the empty refusal when a file couldn't be opened, so the sheet said "it's empty". It now returns nil there, and the sheet says Android's words_refused_cant_open, "Hex couldn't open that file." (zh: Hex 无法打开该文件。), with Done. The inbox logs it as couldn't be opened. Also merges hex-words-format86d51c7bd(a phone's spelling-replacement that repeats an earlier one is a duplicate); HexWordsMerge already marks any repeat of an earlier heard key as duplicate. Built on anomastudio (build-for-testing, iOS 27.2 simulator SDK); unit tests wait for a simulator lease. * iOS words files: delete iOS 27's Inbox copy; Android's new blank-output sentence - HexInbox recognised only Documents/Inbox as iOS's copy of an opened file. On iOS 27 the copy lands in tmp/<bundle id>-Inbox, so it stayed behind after the sheet closed (seen in the simulator session). Both folders are now treated as Hex's Inbox, for deleting after the sheet and for the launch sweep. - The deletionNotSupported sentence now matches Android's approved correction: "1 replacement writes nothing, or only spaces or line breaks, which this iPhone can't do yet: %@" (plural "%lld replacements write ..."), zh "%lld 项替换不写入任何内容,或只写入空格或换行,这台 iPhone 暂时做不到:%@". The old "remove words instead of writing something" was false for "new paragraph". Checked in the simbox (iPhone 18 Pro, iOS 27.2): read 59/59, merge 12/12 phone, write 2/2 phone, testWriterWritesTheBundlesVersion, testReviewSheetWords and the existing suites pass; desktop.hexwords opened, Add, Undo; both file copies gone after Add and after Cancel. * iOS docs: restore dictation.md's later sections The Android-wording commit (fa93175d9) rewrote ios/docs/dictation.md from a read that stopped partway, which dropped every section after Dictation language. This puts back dev's file whole and keeps only the new Word replacements and Hex words files section, so the diff against dev is that section alone (57 lines added, none removed).
378 lines
17 KiB
Swift
378 lines
17 KiB
Swift
import Foundation
|
||
|
||
/// Settings › Dictation › Lowercase, in the shared App Group. Off by default.
|
||
nonisolated struct DictationLowercaseSettings {
|
||
private enum Key {
|
||
static let enabled = "settings.dictationLowercase"
|
||
}
|
||
|
||
private let defaults: UserDefaults?
|
||
|
||
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
|
||
self.defaults = defaults
|
||
}
|
||
|
||
/// Everything dictation writes is lowercased after its style, custom vocabulary included,
|
||
/// as desktop's Lowercase step does (`str::to_lowercase` on the final text).
|
||
var isEnabled: Bool {
|
||
get { defaults?.bool(forKey: Key.enabled) ?? false }
|
||
nonmutating set { defaults?.set(newValue, forKey: Key.enabled) }
|
||
}
|
||
}
|
||
|
||
/// Settings › Dictation › End with a period, in the shared App Group so in-keyboard dictation
|
||
/// reads it too. On by default. Off, no line ends with a full stop, though "?" and "!" stay
|
||
/// (`TranscriptFormatter.format(_:style:language:lists:endsWithPeriod:)`).
|
||
nonisolated struct DictationPeriodSettings {
|
||
static let enabledKey = "settings.dictationEndWithPeriod"
|
||
|
||
private let defaults: UserDefaults?
|
||
|
||
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
|
||
self.defaults = defaults
|
||
}
|
||
|
||
var isEnabled: Bool {
|
||
get { defaults?.object(forKey: Self.enabledKey) as? Bool ?? true }
|
||
nonmutating set { defaults?.set(newValue, forKey: Self.enabledKey) }
|
||
}
|
||
}
|
||
|
||
/// Experiments › Hinglish (Hindi in Latin letters), in the shared App Group so in-keyboard
|
||
/// dictation reads it too. Off by default. While it is on, Hindi dictation is written in Latin
|
||
/// letters (`HinglishRomanizer`) and Hindi is called Hinglish in the language menus.
|
||
nonisolated struct HinglishSettings {
|
||
static let enabledKey = "experiments.hinglish"
|
||
static let launchArgument = "--experiment-hinglish"
|
||
/// Hindi's name in the Hex key's language menu and Settings › Dictation language while on.
|
||
static let languageName = "Hinglish"
|
||
/// The language it is for: Apple Speech's Hindi, also what the keyboard offers to switch to.
|
||
static let language = "hi-IN"
|
||
|
||
private let defaults: UserDefaults?
|
||
|
||
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
|
||
self.defaults = defaults
|
||
}
|
||
|
||
var isEnabled: Bool {
|
||
get { defaults?.bool(forKey: Self.enabledKey) ?? false }
|
||
nonmutating set { defaults?.set(newValue, forKey: Self.enabledKey) }
|
||
}
|
||
|
||
/// "Hinglish" for Hindi while the experiment is on; nil for other languages, or while off.
|
||
func name(for language: String) -> String? {
|
||
isEnabled && Self.isHindi(language) ? Self.languageName : nil
|
||
}
|
||
|
||
static func isHindi(_ language: String?) -> Bool {
|
||
guard let language else { return false }
|
||
return Locale(identifier: language).language.languageCode?.identifier == "hi"
|
||
}
|
||
|
||
/// Simulator scenes pass `--experiment-hinglish` to turn the experiment on.
|
||
func applyLaunchArguments(_ arguments: [String] = ProcessInfo.processInfo.arguments) {
|
||
if arguments.contains(Self.launchArgument) {
|
||
isEnabled = true
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Experiments › Greeklish (Greek in Latin letters), in the shared App Group so in-keyboard
|
||
/// dictation reads it too. Off by default. While it is on, Greek dictation is written in Latin
|
||
/// letters (`GreeklishRomanizer`) and Greek is called Greeklish in the language menus.
|
||
nonisolated struct GreeklishSettings {
|
||
static let enabledKey = "experiments.greeklish"
|
||
static let launchArgument = "--experiment-greeklish"
|
||
/// Greek's name in the Hex key's language menu and Settings › Dictation language while on.
|
||
static let languageName = "Greeklish"
|
||
/// The language it is for: Apple Speech's Greek, also what the keyboard offers to switch to.
|
||
static let language = "el-GR"
|
||
|
||
private let defaults: UserDefaults?
|
||
|
||
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
|
||
self.defaults = defaults
|
||
}
|
||
|
||
var isEnabled: Bool {
|
||
get { defaults?.bool(forKey: Self.enabledKey) ?? false }
|
||
nonmutating set { defaults?.set(newValue, forKey: Self.enabledKey) }
|
||
}
|
||
|
||
/// "Greeklish" for Greek while the experiment is on; nil for other languages, or while off.
|
||
func name(for language: String) -> String? {
|
||
isEnabled && Self.isGreek(language) ? Self.languageName : nil
|
||
}
|
||
|
||
static func isGreek(_ language: String?) -> Bool {
|
||
guard let language else { return false }
|
||
return Locale(identifier: language).language.languageCode?.identifier == "el"
|
||
}
|
||
|
||
/// Simulator scenes pass `--experiment-greeklish` to turn the experiment on.
|
||
func applyLaunchArguments(_ arguments: [String] = ProcessInfo.processInfo.arguments) {
|
||
if arguments.contains(Self.launchArgument) {
|
||
isEnabled = true
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The steps between the speech model and the text Hex inserts, the same wherever Hex
|
||
/// dictates: `DictationController` (the app, the keyboard's warm session and cold start, the
|
||
/// Action Button, Control Center and Siri) and in-keyboard dictation
|
||
/// (`KeyboardLocalDictation`), so a style and Lowercase apply on every path.
|
||
///
|
||
/// In order: Hinglish (Hindi in Latin letters, while that experiment is on) or Greeklish
|
||
/// (Greek in Latin letters, while that one is on), Word replacements, learned fixes, custom vocabulary, Numbers as
|
||
/// digits and Clean up what I say (`CleanupTagger.cleanIfEnabled`, which guards its own memory
|
||
/// in the keyboard),
|
||
/// `refine` (Clean up with Apple Intelligence, only in the app), translation, the style
|
||
/// (`TranscriptFormatter`, with Format lists' `SpokenLists` and Spoken punctuation's
|
||
/// `SpokenPunctuation` inside it), the spellings again,
|
||
/// Lowercase, then French spacing (`FrenchSpacing`, in every style but Verbatim). The style,
|
||
/// Lowercase and French spacing are string rules with no model, so in-keyboard dictation needs
|
||
/// no more memory to run them.
|
||
nonisolated struct DictationPipeline: Sendable {
|
||
var style: DictationStyle
|
||
/// The dictation language (BCP 47).
|
||
var language: String
|
||
/// Custom vocabulary's terms; empty while it is off.
|
||
var vocabulary: [String] = []
|
||
/// Learn how I type's dictation fixes; empty while it is off.
|
||
var corrections: [DictationCorrection] = []
|
||
/// Word replacements, before the learned fixes; empty while Custom vocabulary is off.
|
||
var replacements: [DictationCorrection] = []
|
||
var lowercase = false
|
||
/// Settings › Dictation › Format lists (`SpokenLists`), inside the style.
|
||
var formatLists = false
|
||
/// Settings › Dictation › Spoken punctuation (`SpokenPunctuation`), inside the style.
|
||
var spokenPunctuation = false
|
||
/// Settings › Dictation › Numbers as digits (`SpokenNumbers`), before Clean up what I say's
|
||
/// tagger, in every style but Verbatim.
|
||
var numbersAsDigits = false
|
||
/// Experiments › Hinglish: Hindi is written in Latin letters before every other step, so
|
||
/// learned fixes, vocabulary and the style see the Latin words.
|
||
var hinglish = false
|
||
/// Experiments › Greeklish: Greek is written in Latin letters there too.
|
||
var greeklish = false
|
||
/// Settings › Dictation › End with a period; off, no line ends with a full stop.
|
||
var endsWithPeriod = true
|
||
/// Translate what I say's translator; nil is Apple's. Tests stand in for it.
|
||
var translationEngine: TranslationEngine?
|
||
|
||
/// Snapshot of processing preferences captured once when a dictation starts, shared by
|
||
/// `DictationController` and `KeyboardLocalDictation` so neither path re-reads defaults mid-flight.
|
||
struct Preferences: Equatable, Sendable {
|
||
var style: DictationStyle
|
||
var vocabulary: [String] = []
|
||
var corrections: [DictationCorrection] = []
|
||
var replacements: [DictationCorrection] = []
|
||
var lowercase = false
|
||
var formatLists = false
|
||
var spokenPunctuation = false
|
||
var numbersAsDigits = false
|
||
var hinglish = false
|
||
var greeklish = false
|
||
var endsWithPeriod = true
|
||
|
||
/// Custom vocabulary plus the learned fixes' meant words, for speech recognition hints.
|
||
var recognitionHints: [String] {
|
||
DictationCorrections.recognitionHints(vocabulary: vocabulary, corrections: corrections)
|
||
}
|
||
|
||
static func current(
|
||
style: DictationStyle,
|
||
vocabulary: CustomVocabularySettings = CustomVocabularySettings(),
|
||
corrections: [DictationCorrection] = [],
|
||
replacements: WordReplacementsSettings = WordReplacementsSettings(),
|
||
lowercase: DictationLowercaseSettings = DictationLowercaseSettings(),
|
||
lists: DictationListSettings = DictationListSettings(),
|
||
punctuation: DictationPunctuationSettings = DictationPunctuationSettings(),
|
||
numbers: DictationNumberSettings = DictationNumberSettings(),
|
||
hinglish: HinglishSettings = HinglishSettings(),
|
||
greeklish: GreeklishSettings = GreeklishSettings(),
|
||
period: DictationPeriodSettings = DictationPeriodSettings()
|
||
) -> Preferences {
|
||
Preferences(
|
||
style: style,
|
||
vocabulary: vocabulary.activeTerms,
|
||
corrections: corrections,
|
||
replacements: replacements.activeCorrections,
|
||
lowercase: lowercase.isEnabled,
|
||
formatLists: lists.isEnabled,
|
||
spokenPunctuation: punctuation.isEnabled,
|
||
numbersAsDigits: numbers.isEnabled,
|
||
hinglish: hinglish.isEnabled,
|
||
greeklish: greeklish.isEnabled,
|
||
endsWithPeriod: period.isEnabled
|
||
)
|
||
}
|
||
}
|
||
|
||
init(
|
||
style: DictationStyle,
|
||
language: String,
|
||
vocabulary: [String] = [],
|
||
corrections: [DictationCorrection] = [],
|
||
replacements: [DictationCorrection] = [],
|
||
lowercase: Bool = false,
|
||
formatLists: Bool = false,
|
||
spokenPunctuation: Bool = false,
|
||
numbersAsDigits: Bool = false,
|
||
hinglish: Bool = false,
|
||
greeklish: Bool = false,
|
||
endsWithPeriod: Bool = true,
|
||
translationEngine: TranslationEngine? = nil
|
||
) {
|
||
self.style = style
|
||
self.language = language
|
||
self.vocabulary = vocabulary
|
||
self.corrections = corrections
|
||
self.replacements = replacements
|
||
self.lowercase = lowercase
|
||
self.formatLists = formatLists
|
||
self.spokenPunctuation = spokenPunctuation
|
||
self.numbersAsDigits = numbersAsDigits
|
||
self.hinglish = hinglish
|
||
self.greeklish = greeklish
|
||
self.endsWithPeriod = endsWithPeriod
|
||
self.translationEngine = translationEngine
|
||
}
|
||
|
||
init(
|
||
preferences: Preferences,
|
||
language: String,
|
||
translationEngine: TranslationEngine? = nil
|
||
) {
|
||
self.init(
|
||
style: preferences.style,
|
||
language: language,
|
||
vocabulary: preferences.vocabulary,
|
||
corrections: preferences.corrections,
|
||
replacements: preferences.replacements,
|
||
lowercase: preferences.lowercase,
|
||
formatLists: preferences.formatLists,
|
||
spokenPunctuation: preferences.spokenPunctuation,
|
||
numbersAsDigits: preferences.numbersAsDigits,
|
||
hinglish: preferences.hinglish,
|
||
greeklish: preferences.greeklish,
|
||
endsWithPeriod: preferences.endsWithPeriod,
|
||
translationEngine: translationEngine
|
||
)
|
||
}
|
||
|
||
/// Each step's text, for Record typing logs.
|
||
struct Stages: Equatable, Sendable {
|
||
/// What the speech model heard, in Latin letters for Hinglish or Greeklish: what
|
||
/// learning compares the inserted text with.
|
||
var heard: String
|
||
/// After Word replacements and learned fixes.
|
||
var fixed: String
|
||
/// After custom vocabulary.
|
||
var spelled: String
|
||
/// After Clean up what I say.
|
||
var tagged: String
|
||
/// After `refine`.
|
||
var cleaned: String
|
||
var translated: String?
|
||
/// Why it went in as spoken while Translate what I say was on.
|
||
var translationFailure: TranslationFailure?
|
||
/// What Hex inserts.
|
||
var formatted: String
|
||
}
|
||
|
||
/// `translationSource` is the dictation language as Apple Speech names it; nil reads
|
||
/// `language`.
|
||
@MainActor
|
||
func run(
|
||
_ spoken: String,
|
||
translationSource: Locale.Language? = nil,
|
||
refine: ((String) async -> String)? = nil
|
||
) async -> Stages {
|
||
let translation = DictationTranslationSettings()
|
||
let romanizesHindi = hinglish && HinglishSettings.isHindi(language)
|
||
let romanizesGreek = greeklish && GreeklishSettings.isGreek(language)
|
||
// Apple translates Hindi from Devanagari and Greek from Greek letters, not the
|
||
// experiments' Latin: a dictation that may go into another language keeps its script,
|
||
// romanized only if it goes in as spoken.
|
||
let translatesLatin = (romanizesHindi && translation.isEnabled
|
||
&& !HinglishSettings.isHindi(translation.targetLanguage))
|
||
|| (romanizesGreek && translation.isEnabled
|
||
&& !GreeklishSettings.isGreek(translation.targetLanguage))
|
||
let heard = romanizesHindi ? HinglishRomanizer.romanize(spoken)
|
||
: romanizesGreek ? GreeklishRomanizer.romanize(spoken)
|
||
: spoken
|
||
// Word replacements never touch a dictation that is translated: while Translate what I
|
||
// say would translate this one they wait, and apply only if it goes in as spoken. A Word
|
||
// replacement wins over a learned fix with the same heard words.
|
||
let source = translationSource ?? Locale(identifier: language).language
|
||
let mayTranslate = translation.isEnabled
|
||
&& source.languageCode != Locale.Language(identifier: translation.targetLanguage).languageCode
|
||
let replacements = mayTranslate ? [] : self.replacements
|
||
let replacedKeys = Set(replacements.map { DictationText.phraseKey($0.heard) })
|
||
let replaced = DictationCorrections.apply(
|
||
replacements,
|
||
to: translatesLatin ? spoken : heard,
|
||
maxWords: WordReplacementsSettings.maxWords
|
||
)
|
||
let fixed = DictationCorrections.apply(
|
||
corrections.filter { !replacedKeys.contains(DictationText.phraseKey($0.heard)) },
|
||
to: replaced
|
||
)
|
||
let spelled = SoundAlikeSpelling.apply(vocabulary, to: VocabularySpelling.apply(vocabulary, to: fixed), language: language)
|
||
let tagged = await CleanupTagger.cleanIfEnabled(
|
||
spelled,
|
||
style: style,
|
||
language: language,
|
||
protectedTerms: DictationCorrections.recognitionHints(vocabulary: vocabulary, corrections: corrections),
|
||
numbers: numbersAsDigits
|
||
)
|
||
let refined = await refine?(tagged) ?? tagged
|
||
let outcome = await DictationTranslator.translate(
|
||
refined,
|
||
source: source,
|
||
settings: translation,
|
||
engine: translationEngine
|
||
)
|
||
let translated = outcome.text
|
||
let romanized = translatesLatin && translated == nil
|
||
? (romanizesGreek ? GreeklishRomanizer.romanize(refined) : HinglishRomanizer.romanize(refined))
|
||
: refined
|
||
let cleaned = mayTranslate && translated == nil
|
||
? DictationCorrections.apply(self.replacements, to: romanized, maxWords: WordReplacementsSettings.maxWords)
|
||
: romanized
|
||
// A translation is formatted in the language it is now in.
|
||
let formatLanguage = translated == nil ? language : translation.targetLanguage
|
||
return Stages(
|
||
heard: heard,
|
||
fixed: fixed,
|
||
spelled: spelled,
|
||
tagged: tagged,
|
||
cleaned: cleaned,
|
||
translated: translated,
|
||
translationFailure: outcome.failure,
|
||
formatted: format(translated ?? cleaned, language: formatLanguage)
|
||
)
|
||
}
|
||
|
||
/// `text` in the style, then the vocabulary's and learned fixes' spellings again (a style
|
||
/// can lowercase a term or capitalize a sentence start: "iPhone" -> "IPhone"), then
|
||
/// Lowercase, with Unicode's context-aware mapping, so a word-final Σ becomes ς ("ΟΔΟΣ" ->
|
||
/// "οδος"), where Swift's `lowercased()` always gives σ, then, in French, the spaces before
|
||
/// `? ! ; :` and inside `« »` that the styles take out (`FrenchSpacing`; Verbatim keeps the
|
||
/// model's).
|
||
func format(_ text: String, language: String?) -> String {
|
||
let styled = TranscriptFormatter.format(
|
||
text,
|
||
style: style,
|
||
language: language,
|
||
lists: formatLists,
|
||
punctuation: spokenPunctuation,
|
||
endsWithPeriod: endsWithPeriod
|
||
)
|
||
let spelled = VocabularySpelling.apply(vocabulary + DictationCorrections.spellings(corrections), to: styled)
|
||
let cased = lowercase ? spelled.lowercased(with: nil) : spelled
|
||
return style == .verbatim ? cased : FrenchSpacing.apply(cased, language: language)
|
||
}
|
||
}
|