mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-25 14:20:48 +08:00
iOS dictation: spoken numbers written in digits for every engine (Numbers as digits) (#2414)
Parakeet V2, the keyboard's default English engine since build 130, sometimes
writes a whole sentence in words ("The ratio is five point five.", "november
twenty second"). Apple's SpeechTranscriber writes digits. Across 80 dictated
sentences, Parakeet wrote words where Apple wrote digits in 53 in Ryan's cloned
voice and 11 in macOS voices; runs were deterministic
(experiments/2026-11-22-hex-numbers).
What changed:
- Add SpokenNumbers (ios/HEXShared/SpokenNumbers.swift), a self-contained
English text rule. It writes these in digits as Apple does: decimals,
percentages, numbers from ten up and compounds, years, money with "dollars",
two to nine before a plural noun or unit, ranges with a unit, times with
am/pm/o'clock, ordinals in dates, three or more spoken digits, and
minus/negative before a number. Where Apple writes wrong digits, the words
stay ("three thirty", "four ninety nine", "one and a half", "a second").
"one" on its own, fractions, scores, ordinals outside dates and
ambiguous runs are left for later. Text that already has digits is unchanged.
- It runs in CleanupTagger.cleanIfEnabled, after Spoken counts and before the
tagger, in every style but Verbatim, through DictationPipeline.numbersAsDigits
in the app (DictationController, read at start) and in-keyboard dictation.
- Add Settings > Dictation > Numbers as digits, on by default
(DictationNumberSettings in the App Group), with Simplified Chinese strings.
- Document it in ios/README.md beside Spoken counts.
Verified:
- xcodebuild test on the Mac Studio (iPhone 17 Pro simulator, iOS 27.2),
rebased on dev 3f353485: 898 tests, 0 failures, 4 skipped. New:
- SpokenCleanupRulesTests: 166 cases covering every raw text either engine
wrote for the 80 sentences in both voices; 24 more conversions; 45 that
must not change; other languages, Verbatim, switch off, default.
- CleanupTaggerTests: all 137 hand-written tagger sentences clean up the
same with the rule on.
- Corpus of 755 texts (LibriSpeech hypotheses from Parakeet V2/V3 and Apple,
synthetic English clips, tagger sentences, emoji messages): no sentence
without a spoken number changed; the 28 that changed all hold real counts.
- python3 scripts/code-shape.py passes.
- Settings > Dictation checked in the simulator, English and zh-Hans.
This commit is contained in:
@@ -707,7 +707,7 @@ final class KeyboardLocalDictation {
|
||||
let style = KeyboardBridge().style
|
||||
let vocabulary = CustomVocabularySettings().activeTerms
|
||||
// The app's steps (but Apple Intelligence's cleanup), its style, Format lists,
|
||||
// Spoken punctuation, End with a period and Lowercase included.
|
||||
// Spoken punctuation, Numbers as digits, End with a period and Lowercase included.
|
||||
let pipeline = DictationPipeline(
|
||||
style: style,
|
||||
language: locale,
|
||||
@@ -716,6 +716,7 @@ final class KeyboardLocalDictation {
|
||||
lowercase: DictationLowercaseSettings().isEnabled,
|
||||
formatLists: DictationListSettings().isEnabled,
|
||||
spokenPunctuation: DictationPunctuationSettings().isEnabled,
|
||||
numbersAsDigits: DictationNumberSettings().isEnabled,
|
||||
hinglish: HinglishSettings().isEnabled,
|
||||
greeklish: GreeklishSettings().isEnabled,
|
||||
endsWithPeriod: DictationPeriodSettings().isEnabled
|
||||
|
||||
@@ -54,6 +54,8 @@ final class DictationController {
|
||||
let formatLists: Bool
|
||||
/// Settings › Dictation › Spoken punctuation, read at start.
|
||||
let spokenPunctuation: Bool
|
||||
/// Settings › Dictation › Numbers as digits, read at start.
|
||||
let numbersAsDigits: Bool
|
||||
/// Settings › Dictation › End with a period, read at start.
|
||||
let endsWithPeriod: Bool
|
||||
/// Experiments › Hinglish, read at start.
|
||||
@@ -89,6 +91,7 @@ final class DictationController {
|
||||
private let lowercaseSettings: DictationLowercaseSettings
|
||||
private let listSettings: DictationListSettings
|
||||
private let punctuationSettings: DictationPunctuationSettings
|
||||
private let numberSettings: DictationNumberSettings
|
||||
private let periodSettings: DictationPeriodSettings
|
||||
private let hinglishSettings: HinglishSettings
|
||||
private let greeklishSettings: GreeklishSettings
|
||||
@@ -240,6 +243,7 @@ final class DictationController {
|
||||
lowercaseSettings: DictationLowercaseSettings = DictationLowercaseSettings(),
|
||||
listSettings: DictationListSettings = DictationListSettings(),
|
||||
punctuationSettings: DictationPunctuationSettings = DictationPunctuationSettings(),
|
||||
numberSettings: DictationNumberSettings = DictationNumberSettings(),
|
||||
periodSettings: DictationPeriodSettings = DictationPeriodSettings(),
|
||||
hinglishSettings: HinglishSettings = HinglishSettings(),
|
||||
greeklishSettings: GreeklishSettings = GreeklishSettings(),
|
||||
@@ -265,6 +269,7 @@ final class DictationController {
|
||||
self.lowercaseSettings = lowercaseSettings
|
||||
self.listSettings = listSettings
|
||||
self.punctuationSettings = punctuationSettings
|
||||
self.numberSettings = numberSettings
|
||||
self.periodSettings = periodSettings
|
||||
self.hinglishSettings = hinglishSettings
|
||||
self.greeklishSettings = greeklishSettings
|
||||
@@ -755,6 +760,7 @@ final class DictationController {
|
||||
let lowercase = lowercaseSettings.isEnabled
|
||||
let formatLists = listSettings.isEnabled
|
||||
let spokenPunctuation = punctuationSettings.isEnabled
|
||||
let numbersAsDigits = numberSettings.isEnabled
|
||||
let endsWithPeriod = periodSettings.isEnabled
|
||||
let hinglish = hinglishSettings.isEnabled
|
||||
let greeklish = greeklishSettings.isEnabled
|
||||
@@ -810,6 +816,7 @@ final class DictationController {
|
||||
lowercase: lowercase,
|
||||
formatLists: formatLists,
|
||||
spokenPunctuation: spokenPunctuation,
|
||||
numbersAsDigits: numbersAsDigits,
|
||||
endsWithPeriod: endsWithPeriod,
|
||||
hinglish: hinglish,
|
||||
greeklish: greeklish,
|
||||
@@ -908,6 +915,7 @@ final class DictationController {
|
||||
lowercase: session.lowercase,
|
||||
formatLists: session.formatLists,
|
||||
spokenPunctuation: session.spokenPunctuation,
|
||||
numbersAsDigits: session.numbersAsDigits,
|
||||
hinglish: session.hinglish,
|
||||
greeklish: session.greeklish,
|
||||
endsWithPeriod: session.endsWithPeriod
|
||||
|
||||
@@ -1881,6 +1881,26 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Numbers as digits" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "数字用阿拉伯数字"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"“Five point five” becomes 5.5" : {
|
||||
"localizations" : {
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "“five point five”会写成 5.5"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Messages" : {
|
||||
"shouldTranslate" : false
|
||||
},
|
||||
|
||||
@@ -9,6 +9,7 @@ struct DictationSettingsPage: View {
|
||||
@State private var lowercase = DictationLowercaseSettings().isEnabled
|
||||
@State private var formatLists = DictationListSettings().isEnabled
|
||||
@State private var spokenPunctuation = DictationPunctuationSettings().isEnabled
|
||||
@State private var numbersAsDigits = DictationNumberSettings().isEnabled
|
||||
@State private var endsWithPeriod = DictationPeriodSettings().isEnabled
|
||||
@State private var showsWhatISay = LiveDictationSettings().showsPreview
|
||||
@State private var typesAsISpeak = LiveDictationSettings().typesIntoField
|
||||
@@ -69,6 +70,15 @@ struct DictationSettingsPage: View {
|
||||
|
||||
SettingsDivider()
|
||||
|
||||
// Before Clean up what I say, on every path but Verbatim (`SpokenNumbers`).
|
||||
SettingsToggleRow(
|
||||
title: String(localized: "Numbers as digits"),
|
||||
detail: String(localized: "“Five point five” becomes 5.5"),
|
||||
isOn: $numbersAsDigits
|
||||
)
|
||||
|
||||
SettingsDivider()
|
||||
|
||||
// Inside the style, on every path but Verbatim (`TranscriptFormatter`).
|
||||
SettingsToggleRow(
|
||||
title: String(localized: "End with a period"),
|
||||
@@ -192,6 +202,9 @@ struct DictationSettingsPage: View {
|
||||
.onChange(of: spokenPunctuation) { _, enabled in
|
||||
DictationPunctuationSettings().isEnabled = enabled
|
||||
}
|
||||
.onChange(of: numbersAsDigits) { _, enabled in
|
||||
DictationNumberSettings().isEnabled = enabled
|
||||
}
|
||||
.onChange(of: endsWithPeriod) { _, enabled in
|
||||
DictationPeriodSettings().isEnabled = enabled
|
||||
}
|
||||
@@ -207,6 +220,7 @@ struct DictationSettingsPage: View {
|
||||
lowercase = DictationLowercaseSettings().isEnabled
|
||||
formatLists = DictationListSettings().isEnabled
|
||||
spokenPunctuation = DictationPunctuationSettings().isEnabled
|
||||
numbersAsDigits = DictationNumberSettings().isEnabled
|
||||
endsWithPeriod = DictationPeriodSettings().isEnabled
|
||||
showsWhatISay = LiveDictationSettings().showsPreview
|
||||
typesAsISpeak = LiveDictationSettings().typesIntoField
|
||||
|
||||
@@ -324,6 +324,31 @@ final class CleanupTaggerTests: XCTestCase {
|
||||
XCTAssertEqual(verbatim, "Test one, 2, 3.")
|
||||
}
|
||||
|
||||
/// Numbers as digits runs before the tagger, and cleans up the same: every hand-written
|
||||
/// sentence comes out as without it, then in digits ("two, sorry, three tickets" is "3
|
||||
/// tickets" either way).
|
||||
func testNumbersInDigitsCleanUpTheSame() async throws {
|
||||
let suite = "hex.tests.\(UUID().uuidString)"
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let settings = CleanupTaggerSettings(defaults: defaults)
|
||||
settings.isEnabled = true
|
||||
let tagger = CleanupTagger()
|
||||
let fixture = try Self.load(HandwrittenFixture.self, "cleanup-tagger-handwritten")
|
||||
var changed = 0
|
||||
for item in fixture.cases {
|
||||
let words = await CleanupTagger.cleanIfEnabled(
|
||||
item.input, style: .polished, language: "en-US", settings: settings, tagger: tagger
|
||||
)
|
||||
let digits = await CleanupTagger.cleanIfEnabled(
|
||||
item.input, style: .polished, language: "en-US", numbers: true, settings: settings, tagger: tagger
|
||||
)
|
||||
XCTAssertEqual(digits, SpokenNumbers.digits(in: words, language: "en-US"), "#\(item.id) \(item.input)")
|
||||
if digits != words { changed += 1 }
|
||||
}
|
||||
XCTAssertGreaterThan(changed, 0, "the sentences with a count before a noun")
|
||||
}
|
||||
|
||||
func testDictationStartPreparesOnlyWhenOnAndNotForVerbatim() throws {
|
||||
let suite = "hex.tests.\(UUID().uuidString)"
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
|
||||
@@ -747,6 +747,378 @@ final class SpokenCleanupRulesTests: XCTestCase {
|
||||
XCTAssertEqual(SpokenCleanupRules.spokenCounts(in: "Test one, 2, 3.", language: "fr-FR"), "Test one, 2, 3.")
|
||||
}
|
||||
|
||||
/// What Apple's SpeechTranscriber and Parakeet V2 wrote for 80 sentences with numbers
|
||||
/// (macOS 27.2.1; macOS voices Samantha and Reed, and Ryan's cloned voice from ElevenLabs:
|
||||
/// `experiments/2026-11-22-hex-numbers`), and what Hex writes from each in Polished with
|
||||
/// Numbers as digits on (Clean up what I say off). Parakeet now and then writes a whole
|
||||
/// sentence in words, most often in Ryan's voice; where the rule covers the kind, both
|
||||
/// engines' text comes out the same. Text already in digits keeps its form ("2,400", "$4.99",
|
||||
/// "3.30"), and the kinds left for later stay in words ("twelve fifty", "three to one").
|
||||
func testSpokenNumbersReadTheSameFromEitherEngine() async throws {
|
||||
let suite = "hex.tests.\(UUID().uuidString)"
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let cleanup = CleanupTaggerSettings(defaults: defaults)
|
||||
cleanup.isEnabled = false
|
||||
let pipeline = DictationPipeline(
|
||||
style: .polished, language: "en-US", formatLists: true, spokenPunctuation: true, numbersAsDigits: true
|
||||
)
|
||||
for (heard, written) in [
|
||||
// 1, decimal: The ratio is five point five.
|
||||
("The ratio is 5.5.", "The ratio is 5.5."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("The ratio is five point five.", "The ratio is 5.5."), // Parakeet Ryan
|
||||
// 2, decimal: Set the opacity to zero point two.
|
||||
("Set the opacity to 0.2.", "Set the opacity to 0.2."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("Set the opacity to zero point two.", "Set the opacity to 0.2."), // Parakeet Ryan
|
||||
// 3, decimal: It weighs three point seven five kilos.
|
||||
("It weighs 3.75 kilos.", "It weighs 3.75 kilos."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("It weighs three point seven five kilos.", "It weighs 3.75 kilos."), // Parakeet Ryan
|
||||
// 4, decimal: The rating went up to four point eight stars.
|
||||
("The rating went up to 4.8 stars.", "The rating went up to 4.8 stars."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("The rating went up to four point eight stars.", "The rating went up to 4.8 stars."), // Parakeet Ryan
|
||||
// 5, count-small: I have two dogs and three cats.
|
||||
("I have two dogs and three cats.", "I have 2 dogs and 3 cats."), // Parakeet Samantha/Ryan
|
||||
("I have 2 dogs and 3 cats.", "I have 2 dogs and 3 cats."), // Apple Samantha/Ryan
|
||||
// 6, count-small: We need one more chair.
|
||||
("We need one more chair.", "We need one more chair."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 7, count-small: Give me ten minutes.
|
||||
("Give me ten minutes.", "Give me 10 minutes."), // Parakeet Samantha/Ryan
|
||||
("Give me 10 minutes.", "Give me 10 minutes."), // Apple Samantha/Ryan
|
||||
// 8, count: There were twenty five people at the party.
|
||||
("There were 25 people at the party.", "There were 25 people at the party."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("There were twenty five people at the party.", "There were 25 people at the party."), // Parakeet Ryan
|
||||
// 9, count: Room three hundred and twelve is on the left.
|
||||
("Room 312 is on the left.", "Room 312 is on the left."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("Room three hundred and twelve is on the left.", "Room 312 is on the left."), // Parakeet Ryan
|
||||
// 10, count: We sold two thousand four hundred units last month.
|
||||
("We sold 2,400 units last month.", "We sold 2,400 units last month."), // Parakeet Samantha/Ryan
|
||||
("We sold 2400 units last month.", "We sold 2400 units last month."), // Apple Samantha/Ryan
|
||||
// 11, count: The town has fifteen thousand people.
|
||||
("The town has 15,000 people.", "The town has 15,000 people."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("The town has fifteen thousand people.", "The town has 15,000 people."), // Parakeet Ryan
|
||||
// 12, count: About one point two million people live there.
|
||||
("About 1.2 million people live there.", "About 1.2 million people live there."), // Parakeet Samantha
|
||||
("About 1200000 people live there.", "About 1200000 people live there."), // Apple Samantha/Ryan
|
||||
("About one point two million people live there.", "About 1.2 million people live there."), // Parakeet Ryan
|
||||
// 13, count: I walked eight thousand steps today.
|
||||
("I walked 8,000 steps today.", "I walked 8,000 steps today."), // Parakeet Samantha
|
||||
("I walked 8000 steps today.", "I walked 8000 steps today."), // Apple Samantha/Ryan
|
||||
("I walked eight thousand steps today.", "I walked 8000 steps today."), // Parakeet Ryan
|
||||
// 14, year: She was born in nineteen ninety nine.
|
||||
("She was born in 1999.", "She was born in 1999."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("She was born in nineteen ninety nine.", "She was born in 1999."), // Parakeet Ryan
|
||||
// 15, year: The plan for two thousand twenty six is ready.
|
||||
("The plan for 2026 is ready.", "The plan for 2026 is ready."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("The plan for twenty twenty six is ready.", "The plan for 2026 is ready."), // Parakeet Ryan
|
||||
// 16, year: Back in twenty twenty, everything closed.
|
||||
("Back in 2020, everything closed.", "Back in 2020, everything closed."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 17, percent: The battery is at twenty percent.
|
||||
("The battery is at 20%.", "The battery is at 20%."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("The battery is at twenty percent.", "The battery is at 20%."), // Parakeet Ryan
|
||||
// 18, percent: Sales grew by three point five percent.
|
||||
("Sales grew by 3.5%.", "Sales grew by 3.5%."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("Sales grew by three point five percent.", "Sales grew by 3.5%."), // Parakeet Ryan
|
||||
// 19, percent: I'm one hundred percent sure.
|
||||
("I'm 100% sure.", "I'm 100% sure."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("I'm one hundred percent sure.", "I'm 100% sure."), // Parakeet Ryan
|
||||
// 20, money: It costs five dollars.
|
||||
("It costs $5.", "It costs $5."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("It costs five dollars.", "It costs $5."), // Parakeet Ryan
|
||||
// 21, money: The app is four ninety nine a month.
|
||||
("The app is $4.99 a month.", "The app is $4.99 a month."), // Parakeet Samantha/Reed/Ryan
|
||||
("The app is 499 a month.", "The app is 499 a month."), // Apple Samantha/Reed/Ryan
|
||||
// 22, money: Can you lend me twenty bucks?
|
||||
("Can you lend me twenty bucks?", "Can you lend me 20 bucks?"), // Parakeet Samantha/Ryan
|
||||
("Can you lend me 20 bucks?", "Can you lend me 20 bucks?"), // Apple Samantha/Ryan
|
||||
// 23, money: The rent is two thousand dollars.
|
||||
("The rent is $2,000.", "The rent is $2,000."), // Parakeet Samantha/Ryan
|
||||
("The rent is $2000.", "The rent is $2000."), // Apple Samantha/Ryan
|
||||
// 24, money: The bill came to fifteen dollars and forty cents.
|
||||
("The bill came to $15.40.", "The bill came to $15.40."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("The bill came to fifteen dollars and forty cents.", "The bill came to $15.40."), // Parakeet Ryan
|
||||
// 25, money: Lunch was twelve fifty.
|
||||
("Lunch was 12.50.", "Lunch was 12.50."), // Parakeet Samantha
|
||||
("Lunch was 1250.", "Lunch was 1250."), // Apple Samantha/Ryan
|
||||
("Lunch was twelve fifty.", "Lunch was twelve fifty."), // Parakeet Ryan
|
||||
// 26, time: Let's meet at three thirty.
|
||||
("Let's meet at 3.30.", "Let's meet at 3.30."), // Parakeet Samantha/Reed/Ryan
|
||||
("Let's meet at 330.", "Let's meet at 330."), // Apple Samantha/Reed/Ryan
|
||||
// 27, time: The call is at five P.M.
|
||||
("The call is at 5 p.m.", "The call is at 5 p.m."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 28, time: I'll be there at quarter past two.
|
||||
("I'll be there at quarter past two.", "I'll be there at quarter past two."), // Parakeet Samantha/Ryan, Apple Samantha
|
||||
("I'll be there at quarter past 2.", "I'll be there at quarter past 2."), // Apple Ryan
|
||||
// 29, time: The train leaves at seven fifteen in the morning.
|
||||
("The train leaves at 7:15 in the morning.", "The train leaves at 7:15 in the morning."), // Parakeet Samantha
|
||||
("The train leaves at 7.15 in the morning.", "The train leaves at 7.15 in the morning."), // Apple Samantha/Ryan
|
||||
("The train leaves at seven fifteen in the morning.", "The train leaves at seven fifteen in the morning."), // Parakeet Ryan
|
||||
// 30, time: Wake me up at six A.M. tomorrow.
|
||||
("Wake me up at 6 a.m. tomorrow.", "Wake me up at 6 a.m. Tomorrow."), // Parakeet Samantha, Apple Samantha
|
||||
("Wake me up at six AM to morrow.", "Wake me up at 6 AM to morrow."), // Parakeet Ryan
|
||||
("Wake me up at 6 AM tomorrow.", "Wake me up at 6 AM tomorrow."), // Apple Ryan
|
||||
// 31, date: My birthday is November twenty second.
|
||||
("My birthday is November 22.", "My birthday is November 22."), // Parakeet Samantha
|
||||
("My birthday is November 22nd.", "My birthday is November 22nd."), // Apple Samantha/Ryan
|
||||
("My birthday is november twenty second.", "My birthday is november 22nd."), // Parakeet Ryan
|
||||
// 32, date: The deadline is March third.
|
||||
("The deadline is March 3.", "The deadline is March 3."), // Parakeet Samantha
|
||||
("The deadline is March third.", "The deadline is March 3rd."), // Apple Samantha
|
||||
("The deadline is march third.", "The deadline is march third."), // Parakeet Ryan, Apple Ryan
|
||||
// 33, date: We moved on the fourth of July.
|
||||
("We moved on the 4th of July.", "We moved on the 4th of July."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("We moved on the fourth of July.", "We moved on the 4th of July."), // Parakeet Ryan
|
||||
// 34, ordinal: She finished first in the race.
|
||||
("She finished first in the race.", "She finished first in the race."), // Parakeet Samantha/Ryan
|
||||
("She finished 1st in the race.", "She finished 1st in the race."), // Apple Samantha/Ryan
|
||||
// 35, ordinal: This is the third time I've asked.
|
||||
("This is the third time I've asked.", "This is the third time I've asked."), // Parakeet Samantha/Ryan
|
||||
("This is the 3rd time I've asked.", "This is the 3rd time I've asked."), // Apple Samantha/Ryan
|
||||
// 36, ordinal: He lives on the twenty first floor.
|
||||
("He lives on the 21st floor.", "He lives on the 21st floor."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("He lives on the twenty first floor.", "He lives on the twenty first floor."), // Parakeet Ryan
|
||||
// 37, digits: My number is five five five, one two three, four five six seven.
|
||||
("My number is 555-123-4567.", "My number is 555-123-4567."), // Parakeet Samantha/Reed, Apple Ryan
|
||||
("My number is 555 123-4567.", "My number is 555 123-4567."), // Apple Samantha/Reed
|
||||
("My number is five five five one two three four five six seven.", "My number is 555-123-4567."), // Parakeet Ryan
|
||||
// 38, digits: The code is four seven two nine.
|
||||
("The code is 4729.", "The code is 4729."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("The code is four seven two nine.", "The code is 4729."), // Parakeet Ryan
|
||||
// 39, digits: Call nine one one.
|
||||
("Call 911.", "Call 911."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 40, digits: My zip code is nine four one one zero.
|
||||
("My zip code is 94110.", "My zip code is 94110."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 41, measure: He's six foot two.
|
||||
("He's 6'2.", "He's 6'2."), // Parakeet Samantha
|
||||
("He's 6 foot two.", "He's 6 foot two."), // Apple Samantha/Ryan
|
||||
("He's six foot two.", "He's 6 foot two."), // Parakeet Ryan
|
||||
// 42, measure: I ran ten miles yesterday.
|
||||
("I ran 10 miles yesterday.", "I ran 10 miles yesterday."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("I ran ten miles yesterday.", "I ran 10 miles yesterday."), // Parakeet Ryan
|
||||
// 43, measure: I'm training for a five K.
|
||||
("I'm training for a 5K.", "I'm training for a 5K."), // Parakeet Samantha
|
||||
("I'm training for a 5 K.", "I'm training for a 5 K."), // Apple Samantha/Ryan
|
||||
("I'm training for a 5k.", "I'm training for a 5k."), // Parakeet Ryan
|
||||
// 44, measure: It's seventy two degrees outside.
|
||||
("It's 72 degrees outside.", "It's 72 degrees outside."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("It's seventy two degrees outside.", "It's 72 degrees outside."), // Parakeet Ryan
|
||||
// 45, measure: Add two cups of flour.
|
||||
("Add two cups of flour.", "Add 2 cups of flour."), // Parakeet Samantha/Ryan
|
||||
("Add 2 cups of flour.", "Add 2 cups of flour."), // Apple Samantha/Ryan
|
||||
// 46, measure: The screen is six point one inches.
|
||||
("The screen is 6.1 inches.", "The screen is 6.1 inches."), // Parakeet Samantha, Apple Samantha
|
||||
("The screen is six point one inches.", "The screen is 6.1 inches."), // Parakeet Ryan
|
||||
("The screen is 6.one inches.", "The screen is 6.one inches."), // Apple Ryan
|
||||
// 47, version: Update to iOS twenty seven point two.
|
||||
("Update to iOS 27.2.", "Update to iOS 27.2."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("Update to IOS twenty seven point two.", "Update to IOS 27.2."), // Parakeet Ryan
|
||||
// 48, version: Have you tried GPT five yet?
|
||||
("Have you tried GPT-5 yet?", "Have you tried GPT-5 yet?"), // Parakeet Samantha
|
||||
("Have you tried GPT 5 yet?", "Have you tried GPT 5 yet?"), // Apple Samantha/Ryan
|
||||
("Have you tried GPT5 yet?", "Have you tried GPT5 yet?"), // Parakeet Ryan
|
||||
// 49, version: I'm on version three point one point four.
|
||||
("I'm on version 3.1.4.", "I'm on version 3.1.4."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 50, version: The iPhone seventeen Pro is fast.
|
||||
("The iPhone 17 Pro is fast.", "The iPhone 17 Pro is fast."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 51, range: It takes five to ten minutes.
|
||||
("It takes 5 to 10 minutes.", "It takes 5 to 10 minutes."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("It takes five to ten minutes.", "It takes 5 to 10 minutes."), // Parakeet Ryan
|
||||
// 52, range: Kids aged eight to twelve can join.
|
||||
("Kids aged 8 to 12 can join.", "Kids aged 8 to 12 can join."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("Kids aged eight to twelve can join.", "Kids aged eight to twelve can join."), // Parakeet Ryan
|
||||
// 53, fraction: I'll be there in one and a half hours.
|
||||
("I'll be there in one and a half hours.", "I'll be there in one and a half hours."), // Parakeet Samantha/Reed/Ryan
|
||||
("I'll be there in one. 5 hours.", "I'll be there in one. 5 hours."), // Apple Samantha/Reed/Ryan
|
||||
// 54, fraction: Two thirds of the team agreed.
|
||||
("Two-thirds of the team agreed.", "Two-thirds of the team agreed."), // Parakeet Samantha/Ryan
|
||||
("Two thirds of the team agreed.", "Two thirds of the team agreed."), // Apple Samantha/Ryan
|
||||
// 55, fraction: Use half a cup of sugar.
|
||||
("Use half a cup of sugar.", "Use half a cup of sugar."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 56, negative: It's minus five degrees outside.
|
||||
("It's minus 5 degrees outside.", "It's minus 5 degrees outside."), // Parakeet Samantha
|
||||
("It's -5 degrees outside.", "It's -5 degrees outside."), // Apple Samantha/Ryan
|
||||
("It's minus five degrees outside.", "It's -5 degrees outside."), // Parakeet Ryan
|
||||
// 57, negative: The balance is negative forty dollars.
|
||||
("The balance is negative $40.", "The balance is negative $40."), // Parakeet Samantha
|
||||
("The balance is -$40.", "The balance is -$40."), // Apple Samantha
|
||||
("The balance is negative forty dollars.", "The balance is -$40."), // Parakeet Ryan
|
||||
("The balance is -40.", "The balance is -40."), // Apple Ryan
|
||||
// 58, score: The score was three to one.
|
||||
("The score was 3-1.", "The score was 3-1."), // Parakeet Samantha
|
||||
("The score was 3 to one.", "The score was 3 to one."), // Apple Samantha/Ryan
|
||||
("The score was three to one.", "The score was three to one."), // Parakeet Ryan
|
||||
// 59, score: Test one, two, three.
|
||||
("Test 1, 2, 3.", "Test 1, 2, 3."), // Parakeet Samantha
|
||||
("Test one, 2, 3.", "Test 1, 2, 3."), // Apple Samantha
|
||||
("Test one, two, three.", "Test 1, 2, 3."), // Parakeet Ryan, Apple Ryan
|
||||
// 60, word: One of them is broken.
|
||||
("One of them is broken.", "One of them is broken."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 61, word: No one came to the meeting.
|
||||
("No one came to the meeting.", "No one came to the meeting."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 62, word: That's the one I wanted.
|
||||
("That's the one I wanted.", "That's the one I wanted."), // Parakeet Samantha/Reed/Ryan, Apple Samantha/Reed/Ryan
|
||||
// 63, word: For once, it worked.
|
||||
("For once, it worked.", "For once, it worked."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("For once it worked.", "For once it worked."), // Parakeet Ryan
|
||||
// 64, word: To be honest, I won the game.
|
||||
("To be honest, I won the game.", "To be honest, I won the game."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 65, word: I want to go too.
|
||||
("I want to go too.", "I want to go too."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 66, word: Give me a second.
|
||||
("Give me a second.", "Give me a second."), // Parakeet Samantha/Ryan
|
||||
("Give me a 2nd.", "Give me a 2nd."), // Apple Samantha/Ryan
|
||||
// 67, word: I ate breakfast at eight.
|
||||
("I ate breakfast at 8.", "I ate breakfast at 8."), // Parakeet Samantha, Apple Samantha/Ryan
|
||||
("I ate breakfast at eight.", "I ate breakfast at eight."), // Parakeet Ryan
|
||||
// 68, word: We'll go through them one by one.
|
||||
("We'll go through them one by one.", "We'll go through them one by one."), // Parakeet Samantha/Ryan, Apple Samantha/Ryan
|
||||
// 69, decimal: Use Opus five point five for that.
|
||||
("Use Opus 5.5 for that.", "Use Opus 5.5 for that."), // Parakeet Samantha/Reed/Ryan, Apple Ryan
|
||||
("Use opus 5.5 for that.", "Use opus 5.5 for that."), // Apple Samantha/Reed
|
||||
// 70, decimal: Claude Opus five point five is out.
|
||||
("Claude Opus 5.5 is out.", "Claude Opus 5.5 is out."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("Claude Opus five point five is out.", "Claude Opus 5.5 is out."), // Parakeet Ryan
|
||||
// 71, decimal: It's about five point five.
|
||||
("It's about 5.5.", "It's about 5.5."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("It's about five point five.", "It's about 5.5."), // Parakeet Ryan
|
||||
// 72, decimal: Five point five.
|
||||
("5.5.", "5.5."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("Five point five", "5.5."), // Parakeet Ryan
|
||||
// 73, decimal: Sonnet four point five is cheaper.
|
||||
("Sonnet 4.5 is cheaper.", "Sonnet 4.5 is cheaper."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("Sonnet four point five is cheaper.", "Sonnet 4.5 is cheaper."), // Parakeet Ryan
|
||||
// 74, count: We shipped build one thirty this morning.
|
||||
("We shipped build 130 this morning.", "We shipped build 130 this morning."), // Parakeet Samantha/Reed, Apple Ryan
|
||||
("We ship build 130 this morning.", "We ship build 130 this morning."), // Apple Samantha/Reed
|
||||
("We shipped build one thirty this morning.", "We shipped build one thirty this morning."), // Parakeet Ryan
|
||||
// 75, count-small: I need two more minutes.
|
||||
("I need two more minutes.", "I need 2 more minutes."), // Parakeet Samantha/Reed/Ryan
|
||||
("I need 2 more minutes.", "I need 2 more minutes."), // Apple Samantha/Reed/Ryan
|
||||
// 76, count-small: There are three things to fix.
|
||||
("There are three things to fix.", "There are 3 things to fix."), // Parakeet Samantha/Reed/Ryan
|
||||
("There are 3 things to fix.", "There are 3 things to fix."), // Apple Samantha/Reed/Ryan
|
||||
// 77, count-small: We have four options.
|
||||
("We have four options.", "We have 4 options."), // Parakeet Samantha/Reed/Ryan
|
||||
("We have 4 options.", "We have 4 options."), // Apple Samantha/Reed/Ryan
|
||||
// 78, count-small: Wait five seconds.
|
||||
("Wait 5 seconds.", "Wait 5 seconds."), // Parakeet Samantha/Reed, Apple Samantha/Reed/Ryan
|
||||
("Wait five seconds.", "Wait 5 seconds."), // Parakeet Ryan
|
||||
// 79, decimal: We also need, for the voice, numbers, like five point five and stuff like that with Parakeet.
|
||||
("We also need, for the voice, numbers, like 5.5 and stuff like that with Parakeet.", "We also need, for the voice, numbers, like 5.5 and stuff like that with Parakeet."), // Parakeet Samantha/Reed
|
||||
("We also need, for the voice, numbers, like 5.5 and stuff like that with parakeet.", "We also need, for the voice, numbers, like 5.5 and stuff like that with parakeet."), // Apple Samantha/Reed
|
||||
("We also need for the voice numbers like 5.5 and stuff like that with Parakeet.", "We also need for the voice numbers like 5.5 and stuff like that with Parakeet."), // Parakeet Ryan
|
||||
("We also need for the voice numbers, like 5.5 and stuff like that with parakeet.", "We also need for the voice numbers, like 5.5 and stuff like that with parakeet."), // Apple Ryan
|
||||
// 80, decimal: Can you check whether the five point five model is faster than the four point five one, and send me the numbers by three thirty?
|
||||
("Can you check whether the 5.5 model is faster than the 4.5 one, and send me the numbers by 3.30?", "Can you check whether the 5.5 model is faster than the 4.5 one, and send me the numbers by 3.30?"), // Parakeet Samantha/Reed
|
||||
("Can you check whether the 5.5 model is faster than the 4.51 and send me the numbers by 330?", "Can you check whether the 5.5 model is faster than the 4.51 and send me the numbers by 330?"), // Parakeet Ryan, Apple Samantha/Reed/Ryan
|
||||
] {
|
||||
let numbered = await CleanupTagger.cleanIfEnabled(
|
||||
heard, style: .polished, language: "en-US", numbers: true, settings: cleanup
|
||||
)
|
||||
XCTAssertEqual(pipeline.format(numbered, language: "en-US"), written, heard)
|
||||
}
|
||||
}
|
||||
|
||||
func testSpokenNumbersBecomeDigits() {
|
||||
for (heard, written) in [
|
||||
("At one point two people left.", "At one point 2 people left."),
|
||||
("Between five and ten minutes.", "Between 5 and 10 minutes."),
|
||||
("Two or three days.", "2 or 3 days."),
|
||||
("One to two hours.", "1 to 2 hours."),
|
||||
("Meet at seven fifteen pm.", "Meet at 7:15 pm."),
|
||||
("Seven oh five am.", "7:05 am."),
|
||||
("At five o'clock.", "At 5 o'clock."),
|
||||
("It's one mile away.", "It's 1 mile away."),
|
||||
("It costs one dollar.", "It costs $1."),
|
||||
("Five million dollars.", "$5 million."),
|
||||
("Two thousand and five.", "2005."),
|
||||
("May second.", "May 2nd."),
|
||||
("On the first of may.", "On the 1st of may."),
|
||||
("On September thirtieth.", "On September 30th."),
|
||||
("Five point five dollars.", "$5.50."),
|
||||
("Call five five five, one two three, four five six seven.", "Call 555-123-4567."),
|
||||
("Built in nineteen oh five.", "Built in 1905."),
|
||||
("It's minus one.", "It's -1."),
|
||||
("Ten minus five.", "10 minus five."),
|
||||
("Twenty-five people.", "25 people."),
|
||||
("Two hundred people.", "200 people."),
|
||||
("Three point five million.", "3.5 million."),
|
||||
("Twenty one guns.", "21 guns."),
|
||||
("Six feet.", "6 feet."),
|
||||
] {
|
||||
XCTAssertEqual(SpokenNumbers.digits(in: heard, language: "en-US"), written, heard)
|
||||
}
|
||||
}
|
||||
|
||||
/// "one" alone, ordinals outside dates, fractions, and times, prices, ranges and scores
|
||||
/// without a marker or unit stay as said for now, as do digits and other languages.
|
||||
func testSpokenNumbersLeaveTheRestAsSaid() async throws {
|
||||
for heard in [
|
||||
"One of them is broken.",
|
||||
"No one came to the meeting.",
|
||||
"That's the one I wanted.",
|
||||
"For once, it worked.",
|
||||
"To be honest, I won the game.",
|
||||
"I want to go too.",
|
||||
"Give me a second.",
|
||||
"We'll go through them one by one.",
|
||||
"We need one more chair.",
|
||||
"Use half a cup of sugar.",
|
||||
"Two thirds of the team agreed.",
|
||||
"I'll be there in one and a half hours.",
|
||||
"She finished first in the race.",
|
||||
"This is the third time I've asked.",
|
||||
"Let's meet at three thirty.",
|
||||
"The app is four ninety nine a month.",
|
||||
"Lunch was twelve fifty.",
|
||||
"The score was three to one.",
|
||||
"Kids aged eight to twelve can join.",
|
||||
"I ate breakfast at eight.",
|
||||
"We shipped build one thirty this morning.",
|
||||
"I work nine to five.",
|
||||
"The five point plan.",
|
||||
"Back in the nineteen nineties.",
|
||||
"Just my two cents.",
|
||||
"Ten to five.",
|
||||
"One or two people came.",
|
||||
"We sold 2,400 units.",
|
||||
"The app is $4.99 a month.",
|
||||
"Meet at 7:15.",
|
||||
"He lives on the twenty first floor.",
|
||||
"Have you tried GPT five yet?",
|
||||
"The deadline is march third.",
|
||||
"Two plus two equals four.",
|
||||
"Five, six, seven.",
|
||||
"Five five.",
|
||||
"It's a two-way street.",
|
||||
"Take a ten-minute break.",
|
||||
"Quarter past two.",
|
||||
"Twenty past six.",
|
||||
"Two of us went.",
|
||||
"Those two are fine.",
|
||||
"The train leaves at seven fifteen.",
|
||||
"Two dozen eggs.",
|
||||
"A hundred people.",
|
||||
] {
|
||||
XCTAssertEqual(SpokenNumbers.digits(in: heard, language: "en-US"), heard)
|
||||
}
|
||||
XCTAssertEqual(SpokenNumbers.digits(in: "Cinco punto cinco.", language: "es-ES"), "Cinco punto cinco.")
|
||||
XCTAssertEqual(SpokenNumbers.digits(in: "The ratio is five point five.", language: "fr-FR"), "The ratio is five point five.")
|
||||
|
||||
let suite = "hex.tests.\(UUID().uuidString)"
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
let cleanup = CleanupTaggerSettings(defaults: defaults)
|
||||
cleanup.isEnabled = false
|
||||
let heard = "The ratio is five point five."
|
||||
let off = await CleanupTagger.cleanIfEnabled(heard, style: .polished, language: "en-US", settings: cleanup)
|
||||
XCTAssertEqual(off, heard, "Numbers as digits off")
|
||||
let verbatim = await CleanupTagger.cleanIfEnabled(
|
||||
heard, style: .verbatim, language: "en-US", numbers: true, settings: cleanup
|
||||
)
|
||||
XCTAssertEqual(verbatim, heard, "Verbatim keeps the model's words")
|
||||
XCTAssertTrue(DictationNumberSettings(defaults: defaults).isEnabled, "on by default")
|
||||
}
|
||||
|
||||
/// Every style but Verbatim keeps the address whole: no capital after its dots, none on
|
||||
/// it at a sentence start, and no full stop after an address said alone.
|
||||
func testStylesKeepAnAddressWhole() {
|
||||
|
||||
@@ -166,16 +166,20 @@ nonisolated final class CleanupTagger: @unchecked Sendable {
|
||||
style: DictationStyle,
|
||||
language: String? = nil,
|
||||
protectedTerms: [String] = [],
|
||||
numbers: Bool = false,
|
||||
settings: CleanupTaggerSettings = CleanupTaggerSettings(),
|
||||
tagger: CleanupTagger = .shared
|
||||
) async -> String {
|
||||
guard style != .verbatim, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
return text
|
||||
}
|
||||
let text = SpokenCleanupRules.spokenCounts(
|
||||
let counted = SpokenCleanupRules.spokenCounts(
|
||||
in: SpokenCleanupRules.spokenSymbols(in: text, language: language),
|
||||
language: language
|
||||
)
|
||||
// Before the tagger, so a number in digits is a word it never removes outside a
|
||||
// self-correction (`CleanupGuard`).
|
||||
let text = numbers ? SpokenNumbers.digits(in: counted, language: language) : counted
|
||||
guard settings.isEnabled else { return text }
|
||||
guard SpeechLanguagePicker.isEnglish(language) else {
|
||||
return SpokenCleanupRules.clean(text, language: language)
|
||||
|
||||
@@ -124,8 +124,9 @@ nonisolated struct GreeklishSettings {
|
||||
/// (`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), learned fixes, custom vocabulary, Clean up
|
||||
/// what I say (`CleanupTagger.cleanIfEnabled`, which guards its own memory in the keyboard),
|
||||
/// (Greek in Latin letters, while that one is on), 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,
|
||||
@@ -145,6 +146,9 @@ nonisolated struct DictationPipeline: Sendable {
|
||||
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
|
||||
@@ -202,7 +206,8 @@ nonisolated struct DictationPipeline: Sendable {
|
||||
spelled,
|
||||
style: style,
|
||||
language: language,
|
||||
protectedTerms: DictationCorrections.recognitionHints(vocabulary: vocabulary, corrections: corrections)
|
||||
protectedTerms: DictationCorrections.recognitionHints(vocabulary: vocabulary, corrections: corrections),
|
||||
numbers: numbersAsDigits
|
||||
)
|
||||
let refined = await refine?(tagged) ?? tagged
|
||||
let outcome = await DictationTranslator.translate(
|
||||
|
||||
@@ -0,0 +1,692 @@
|
||||
import Foundation
|
||||
|
||||
/// Settings › Dictation › Numbers as digits, in the shared App Group so in-keyboard dictation
|
||||
/// reads it too. On by default.
|
||||
nonisolated struct DictationNumberSettings {
|
||||
static let enabledKey = "settings.dictationNumbersAsDigits"
|
||||
|
||||
private let defaults: UserDefaults?
|
||||
|
||||
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
|
||||
self.defaults = defaults
|
||||
}
|
||||
|
||||
/// Numbers said in words are written in digits (`SpokenNumbers`), in English.
|
||||
var isEnabled: Bool {
|
||||
get { defaults?.object(forKey: Self.enabledKey) as? Bool ?? true }
|
||||
nonmutating set { defaults?.set(newValue, forKey: Self.enabledKey) }
|
||||
}
|
||||
}
|
||||
|
||||
/// English numbers said in words written in digits, as Apple's `SpeechTranscriber` writes them,
|
||||
/// with string rules and no model, so every speech model reads the same. Parakeet V2 switches a
|
||||
/// whole sentence into words now and then ("The ratio is five point five.", "november twenty
|
||||
/// second"), most often in a real voice: in Ryan's cloned voice it wrote words where Apple wrote
|
||||
/// digits in 53 of 80 sentences, against 11 of 80 in macOS voices (macOS 27.2.1, FluidAudio
|
||||
/// 0.15.5, `experiments/2026-11-22-hex-numbers`). Runs in `CleanupTagger.cleanIfEnabled` after
|
||||
/// `SpokenCleanupRules.spokenCounts` and before the tagger, in every style but Verbatim. Text
|
||||
/// that already has digits keeps them as written ("2,400", "$4.99", "7:15").
|
||||
///
|
||||
/// What becomes digits:
|
||||
/// - decimals ("five point five" 5.5, "zero point two" 0.2, "three point one point four" 3.1.4,
|
||||
/// "one point two million" 1.2 million), percentages ("twenty percent" 20%);
|
||||
/// - numbers from ten up and compounds ("twenty five" 25, "three hundred and twelve" 312,
|
||||
/// "fifteen thousand" 15,000; commas from 10,000, as Apple writes "8000" and "15,000");
|
||||
/// - years ("nineteen ninety nine", "twenty twenty six");
|
||||
/// - money with "dollars" ("five dollars" $5, "fifteen dollars and forty cents" $15.40);
|
||||
/// - two to nine right before a plural noun or a unit ("two dogs", "four options", "six foot"),
|
||||
/// and "one" only before a unit ("one mile"), as a decimal, a percentage or money;
|
||||
/// - ranges ending in a plural noun or unit ("five to ten minutes"), times with "am", "pm" or
|
||||
/// "o'clock" ("six am", "seven fifteen pm" 7:15), ordinals in dates ("November twenty second"
|
||||
/// November 22nd, "the fourth of July"), three or more spoken digits ("four seven two nine"
|
||||
/// 4729; ten as 555-123-4567), and "minus" or "negative" before a number (-5, -$40).
|
||||
///
|
||||
/// What stays as said, for now: "one" alone ("one of them", "no one"), times and prices without
|
||||
/// a marker ("three thirty", "four ninety nine", "twelve fifty"), ranges and scores without a
|
||||
/// unit ("eight to twelve", "three to one"), fractions ("two thirds", "one and a half"),
|
||||
/// ordinals outside dates ("finished first", "the twenty first floor", "a second"), small
|
||||
/// numbers before anything but a plural noun or unit ("at eight", "GPT five"), and any run of
|
||||
/// number words that could be read two ways ("one thirty", "seven fifteen"). Other languages are
|
||||
/// left as they are.
|
||||
nonisolated enum SpokenNumbers {
|
||||
static func digits(in text: String, language: String?) -> String {
|
||||
guard SpeechLanguagePicker.isEnglish(language), !text.isEmpty else { return text }
|
||||
let tokens = tokenize(text)
|
||||
guard tokens.contains(where: { isNumberish($0) || isOrdinal($0.word) }) else { return text }
|
||||
var edits: [(range: Range<String.Index>, text: String)] = []
|
||||
var index = 0
|
||||
while index < tokens.count {
|
||||
switch match(tokens, at: index) {
|
||||
case let .edit(first, last, written):
|
||||
edits.append((tokens[first].range.lowerBound..<tokens[last].range.upperBound, written))
|
||||
index = last + 1
|
||||
case let .skip(last):
|
||||
index = max(last, index) + 1
|
||||
case .none:
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
guard !edits.isEmpty else { return text }
|
||||
var result = ""
|
||||
var cursor = text.startIndex
|
||||
for edit in edits {
|
||||
result += text[cursor..<edit.range.lowerBound] + edit.text
|
||||
cursor = edit.range.upperBound
|
||||
}
|
||||
return result + text[cursor...]
|
||||
}
|
||||
|
||||
// MARK: Tokens
|
||||
|
||||
/// A word between spaces: the marks before it, the word, the marks after it.
|
||||
private struct Token {
|
||||
let range: Range<String.Index>
|
||||
let lead: String
|
||||
let core: String
|
||||
let trail: String
|
||||
let hasDigit: Bool
|
||||
var word: String { core.lowercased() }
|
||||
/// Nothing but the word: no mark after it ends the number.
|
||||
var open: Bool { trail.isEmpty }
|
||||
}
|
||||
|
||||
private static func tokenize(_ text: String) -> [Token] {
|
||||
var tokens: [Token] = []
|
||||
var index = text.startIndex
|
||||
while index < text.endIndex {
|
||||
guard !text[index].isWhitespace else {
|
||||
index = text.index(after: index)
|
||||
continue
|
||||
}
|
||||
var end = index
|
||||
while end < text.endIndex, !text[end].isWhitespace { end = text.index(after: end) }
|
||||
let chunk = text[index..<end]
|
||||
let lead = chunk.prefix { !$0.isLetter && !$0.isNumber }
|
||||
let rest = chunk.dropFirst(lead.count)
|
||||
let core = String(rest.reversed().drop { !$0.isLetter && !$0.isNumber }.reversed())
|
||||
tokens.append(Token(
|
||||
range: index..<end,
|
||||
lead: String(lead),
|
||||
core: core,
|
||||
trail: String(rest.dropFirst(core.count)),
|
||||
hasDigit: chunk.contains(where: \.isNumber)
|
||||
))
|
||||
index = end
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
|
||||
private enum Outcome {
|
||||
/// Tokens `first` through `last` become `text`.
|
||||
case edit(Int, Int, String)
|
||||
/// Tokens up to `last` stay as said.
|
||||
case skip(Int)
|
||||
case none
|
||||
}
|
||||
|
||||
// MARK: Words
|
||||
|
||||
private enum Kind {
|
||||
case digit(Int), teen(Int), tens(Int), tensUnit(Int), hundred, big(Int)
|
||||
}
|
||||
|
||||
private static let digitWords: [String: Int] = [
|
||||
"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
|
||||
]
|
||||
private static let teenWords: [String: Int] = [
|
||||
"ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16,
|
||||
"seventeen": 17, "eighteen": 18, "nineteen": 19,
|
||||
]
|
||||
private static let tensWords: [String: Int] = [
|
||||
"twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90,
|
||||
]
|
||||
private static let bigWords: [String: Int] = [
|
||||
"thousand": 1_000, "million": 1_000_000, "billion": 1_000_000_000, "trillion": 1_000_000_000_000,
|
||||
]
|
||||
private static let ordinals: [String: Int] = [
|
||||
"first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5, "sixth": 6, "seventh": 7, "eighth": 8,
|
||||
"ninth": 9, "tenth": 10, "eleventh": 11, "twelfth": 12, "thirteenth": 13, "fourteenth": 14,
|
||||
"fifteenth": 15, "sixteenth": 16, "seventeenth": 17, "eighteenth": 18, "nineteenth": 19,
|
||||
"twentieth": 20, "thirtieth": 30, "fortieth": 40, "fiftieth": 50, "sixtieth": 60, "seventieth": 70,
|
||||
"eightieth": 80, "ninetieth": 90, "hundredth": 100, "thousandth": 1_000,
|
||||
]
|
||||
private static let months: Set<String> = [
|
||||
"january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
|
||||
"november", "december",
|
||||
]
|
||||
/// Units after a number, singular or short: "six foot", "five K", "ten GB".
|
||||
private static let units: Set<String> = [
|
||||
"k", "km", "kg", "mph", "kph", "gb", "mb", "tb", "kb", "lb", "lbs", "oz", "ml", "mg", "cm", "mm", "ft",
|
||||
"mile", "foot", "inch", "kilo", "kilogram", "gram", "pound", "ounce", "degree", "liter", "litre",
|
||||
"gallon", "meter", "metre", "kilometer", "kilometre",
|
||||
]
|
||||
/// The units "one" becomes 1 before ("one mile"); not "foot" ("one foot in the door").
|
||||
private static let oneUnits: Set<String> = [
|
||||
"km", "kg", "mph", "gb", "mb", "tb", "kb", "lb", "oz", "mile", "inch", "kilo", "kilogram", "gram",
|
||||
"pound", "ounce", "degree", "liter", "litre", "gallon", "meter", "metre", "kilometer", "kilometre",
|
||||
]
|
||||
private static let irregularPlurals: Set<String> = [
|
||||
"people", "children", "men", "women", "feet", "teeth", "mice", "geese", "cattle",
|
||||
]
|
||||
/// Words that may stand between a number and its plural noun: "two more minutes".
|
||||
private static let bridges: Set<String> = [
|
||||
"more", "other", "extra", "new", "old", "big", "small", "little", "different", "separate",
|
||||
"additional", "whole", "full", "main", "quick", "short", "long", "free", "good", "great", "bad",
|
||||
"major", "minor", "key", "young", "large", "huge", "tiny",
|
||||
]
|
||||
/// Words ending in "s" that aren't plural nouns, or after which a number stays a word: verbs
|
||||
/// ("two equals"), fractions ("two thirds"), decades ("the nineteen nineties").
|
||||
private static let notPlural: Set<String> = [
|
||||
"this", "his", "hers", "its", "yes", "less", "unless", "perhaps", "always", "towards", "besides",
|
||||
"whereas", "across", "plus", "minus", "thus", "was", "has", "does", "goes", "gets", "says", "seems",
|
||||
"means", "makes", "equals", "times", "ours", "yours", "theirs", "sometimes", "lets", "afterwards",
|
||||
"nowadays", "looks", "sounds", "needs", "wants", "takes", "comes", "works", "feels", "stays",
|
||||
"becomes", "remains", "keeps", "tells", "gives", "knows", "thinks",
|
||||
]
|
||||
private static let fractions: Set<String> = [
|
||||
"half", "halves", "third", "thirds", "quarter", "quarters", "fourths", "fifths", "sixths", "sevenths",
|
||||
"eighths", "ninths", "tenths",
|
||||
]
|
||||
private static let decades: Set<String> = [
|
||||
"twenties", "thirties", "forties", "fifties", "sixties", "seventies", "eighties", "nineties",
|
||||
"hundreds", "thousands", "millions", "billions", "dozen", "dozens",
|
||||
]
|
||||
|
||||
private static func kind(_ word: String) -> Kind? {
|
||||
if let value = digitWords[word] { return .digit(value) }
|
||||
if let value = teenWords[word] { return .teen(value) }
|
||||
if let value = tensWords[word] { return .tens(value) }
|
||||
if word == "hundred" { return .hundred }
|
||||
if let value = bigWords[word] { return .big(value) }
|
||||
// "twenty-five", as some models write it.
|
||||
let parts = word.split(separator: "-")
|
||||
if parts.count == 2, let tens = tensWords[String(parts[0])], let unit = digitWords[String(parts[1])], unit > 0 {
|
||||
return .tensUnit(tens + unit)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func isNumberish(_ token: Token) -> Bool {
|
||||
!token.hasDigit && kind(token.word) != nil
|
||||
}
|
||||
|
||||
private static func isOrdinal(_ word: String) -> Bool {
|
||||
if ordinals[word] != nil { return true }
|
||||
let parts = word.split(separator: "-")
|
||||
return parts.count == 2 && tensWords[String(parts[0])] != nil && ordinals[String(parts[1])] != nil
|
||||
}
|
||||
|
||||
/// A single digit in a run or after "point": "oh" too.
|
||||
private static func spokenDigit(_ token: Token) -> Int? {
|
||||
guard !token.hasDigit else { return nil }
|
||||
return token.word == "oh" ? 0 : digitWords[token.word]
|
||||
}
|
||||
|
||||
// MARK: Matching
|
||||
|
||||
private static func match(_ t: [Token], at i: Int) -> Outcome {
|
||||
let token = t[i]
|
||||
guard !token.hasDigit else { return .none }
|
||||
// "November twenty second", "July fourth": "May" and "March" only with a capital.
|
||||
if months.contains(token.word), token.open,
|
||||
!["may", "march"].contains(token.word) || token.core.first?.isUppercase == true,
|
||||
let day = ordinal(t, at: i + 1) {
|
||||
return .edit(i + 1, day.end, t[i + 1].lead + day.text + t[day.end].trail)
|
||||
}
|
||||
// "the fourth of July".
|
||||
if token.word == "the", token.open, let day = ordinal(t, at: i + 1), t[day.end].open,
|
||||
day.end + 2 < t.count, t[day.end + 1].word == "of", t[day.end + 1].open,
|
||||
months.contains(t[day.end + 2].word) {
|
||||
return .edit(i + 1, day.end, t[i + 1].lead + day.text)
|
||||
}
|
||||
if token.word == "minus" || token.word == "negative", token.open, !followsNumber(t, i) {
|
||||
if case let .edit(first, last, written) = number(t, at: i + 1, forced: true), first == i + 1 {
|
||||
return .edit(i, last, token.lead + "-" + written)
|
||||
}
|
||||
return .none
|
||||
}
|
||||
if let run = digitRun(t, at: i) { return run }
|
||||
return number(t, at: i, forced: false)
|
||||
}
|
||||
|
||||
private static func followsNumber(_ t: [Token], _ i: Int) -> Bool {
|
||||
guard i > 0, t[i - 1].open else { return false }
|
||||
return t[i - 1].hasDigit || isNumberish(t[i - 1])
|
||||
}
|
||||
|
||||
/// A day said as an ordinal, 1st to 31st: "third", "twenty second", "thirty-first".
|
||||
private static func ordinal(_ t: [Token], at j: Int) -> (text: String, end: Int)? {
|
||||
guard j < t.count, !t[j].hasDigit else { return nil }
|
||||
let word = t[j].word
|
||||
var value: Int?
|
||||
var end = j
|
||||
if let single = ordinals[word] {
|
||||
value = single
|
||||
} else if let tens = tensWords[word], t[j].open, j + 1 < t.count, !t[j + 1].hasDigit,
|
||||
let unit = ordinals[t[j + 1].word], unit < 10 {
|
||||
value = tens + unit
|
||||
end = j + 1
|
||||
} else {
|
||||
let parts = word.split(separator: "-")
|
||||
if parts.count == 2, let tens = tensWords[String(parts[0])], let unit = ordinals[String(parts[1])], unit < 10 {
|
||||
value = tens + unit
|
||||
}
|
||||
}
|
||||
guard let value, (1...31).contains(value) else { return nil }
|
||||
return ("\(value)\(suffix(value))", end)
|
||||
}
|
||||
|
||||
private static func suffix(_ value: Int) -> String {
|
||||
if (11...13).contains(value % 100) { return "th" }
|
||||
switch value % 10 {
|
||||
case 1: return "st"
|
||||
case 2: return "nd"
|
||||
case 3: return "rd"
|
||||
default: return "th"
|
||||
}
|
||||
}
|
||||
|
||||
/// Three or more digits said one by one: "four seven two nine" 4729, "nine one one" 911,
|
||||
/// and ten (with or without commas between groups of 3, 3 and 4) as 555-123-4567.
|
||||
private static func digitRun(_ t: [Token], at i: Int) -> Outcome? {
|
||||
guard t[i].word != "oh", let first = spokenDigit(t[i]), !followsNumber(t, i) else { return nil }
|
||||
var digits = [first]
|
||||
var groups: [Int] = []
|
||||
var group = 1
|
||||
var end = i
|
||||
while end + 1 < t.count, let next = spokenDigit(t[end + 1]), t[end].open || t[end].trail == "," {
|
||||
if !t[end].open {
|
||||
groups.append(group)
|
||||
group = 0
|
||||
}
|
||||
digits.append(next)
|
||||
group += 1
|
||||
end += 1
|
||||
}
|
||||
groups.append(group)
|
||||
guard digits.count >= 3 else { return nil }
|
||||
if t[end].open, end + 1 < t.count {
|
||||
// "seven oh five am" is a time.
|
||||
if isMeridiem(t[end + 1]) { return nil }
|
||||
if isNumberish(t[end + 1]) || t[end + 1].hasDigit { return .skip(end) }
|
||||
}
|
||||
let joined = digits.map(String.init).joined()
|
||||
if digits.count == 10, groups == [10] || groups == [3, 3, 4] {
|
||||
let phone = Array(joined)
|
||||
return .edit(i, end, t[i].lead + String(phone[0..<3]) + "-" + String(phone[3..<6]) + "-"
|
||||
+ String(phone[6...]) + t[end].trail)
|
||||
}
|
||||
// A list said with commas ("five, six, seven") isn't one number.
|
||||
guard groups.count == 1 else { return nil }
|
||||
return .edit(i, end, t[i].lead + joined + t[end].trail)
|
||||
}
|
||||
|
||||
// MARK: Numbers
|
||||
|
||||
private struct Cardinal {
|
||||
var value: Int
|
||||
var end: Int
|
||||
var words: Int
|
||||
var isYear = false
|
||||
var hasScale = false
|
||||
/// "five million": the value and word of the last scale when it ends the number.
|
||||
var bigScale: (value: Int, word: String)?
|
||||
var bigScales = 0
|
||||
var ambiguous = false
|
||||
/// The value when the number is one digit word ("two").
|
||||
var single: Int?
|
||||
}
|
||||
|
||||
private enum Last { case none, unit, teen, tens, hundred, big, and }
|
||||
|
||||
/// "nineteen ninety nine", "twenty twenty six", "nineteen oh five".
|
||||
private static func year(_ t: [Token], at i: Int) -> Cardinal? {
|
||||
guard t[i].open, i + 1 < t.count, !t[i + 1].hasDigit else { return nil }
|
||||
let century: Int
|
||||
switch t[i].word {
|
||||
case "nineteen": century = 19
|
||||
case "twenty": century = 20
|
||||
default: return nil
|
||||
}
|
||||
let j = i + 1
|
||||
var rest: Int?
|
||||
var end = j
|
||||
func digit(after k: Int) -> Int? {
|
||||
guard t[k].open, k + 1 < t.count, !t[k + 1].hasDigit, case let .digit(value)? = kind(t[k + 1].word),
|
||||
value > 0 else { return nil }
|
||||
return value
|
||||
}
|
||||
switch kind(t[j].word) {
|
||||
case let .teen(value)?:
|
||||
rest = value
|
||||
case let .tens(value)?:
|
||||
rest = value
|
||||
if let unit = digit(after: j) {
|
||||
rest = value + unit
|
||||
end = j + 1
|
||||
}
|
||||
case let .tensUnit(value)?:
|
||||
rest = value
|
||||
default:
|
||||
if t[j].word == "oh", let unit = digit(after: j) {
|
||||
rest = unit
|
||||
end = j + 1
|
||||
}
|
||||
}
|
||||
guard let rest else { return nil }
|
||||
return Cardinal(value: century * 100 + rest, end: end, words: end - i + 1, isYear: true)
|
||||
}
|
||||
|
||||
private static func cardinal(_ t: [Token], at i: Int) -> Cardinal? {
|
||||
guard i < t.count, isNumberish(t[i]) else { return nil }
|
||||
var parsed: Cardinal
|
||||
if let year = year(t, at: i) {
|
||||
parsed = year
|
||||
} else {
|
||||
var total = 0
|
||||
var current = 0
|
||||
var last = Last.none
|
||||
var words = 0
|
||||
var end = i
|
||||
var j = i
|
||||
var hasScale = false
|
||||
var lastBig: (value: Int, word: String)?
|
||||
var bigScales = 0
|
||||
var ambiguous = false
|
||||
var zero = false
|
||||
scan: while j < t.count {
|
||||
let token = t[j]
|
||||
if token.hasDigit { break }
|
||||
if token.word == "and", last == .hundred || last == .big, token.open, j + 1 < t.count,
|
||||
isNumberish(t[j + 1]), additive(kind(t[j + 1].word)) {
|
||||
last = .and
|
||||
j += 1
|
||||
continue
|
||||
}
|
||||
guard let found = kind(token.word) else { break }
|
||||
let adds: Set<Last> = [.none, .hundred, .big, .and]
|
||||
switch found {
|
||||
case let .digit(value):
|
||||
if value == 0 {
|
||||
guard words == 0 else { ambiguous = true; break scan }
|
||||
zero = true
|
||||
} else {
|
||||
guard adds.contains(last) || last == .tens else { ambiguous = true; break scan }
|
||||
current += value
|
||||
}
|
||||
last = .unit
|
||||
case let .teen(value), let .tens(value), let .tensUnit(value):
|
||||
guard adds.contains(last) else { ambiguous = true; break scan }
|
||||
current += value
|
||||
if case .tens = found { last = .tens } else if case .teen = found { last = .teen } else { last = .unit }
|
||||
case .hundred:
|
||||
guard [.unit, .teen, .tens].contains(last), (1...99).contains(current) else {
|
||||
ambiguous = words > 0
|
||||
break scan
|
||||
}
|
||||
current *= 100
|
||||
last = .hundred
|
||||
hasScale = true
|
||||
case let .big(value):
|
||||
guard [.unit, .teen, .tens, .hundred].contains(last), current > 0,
|
||||
lastBig.map({ value < $0.value }) ?? true else {
|
||||
ambiguous = words > 0
|
||||
break scan
|
||||
}
|
||||
total += current * value
|
||||
current = 0
|
||||
last = .big
|
||||
hasScale = true
|
||||
lastBig = (value, token.word)
|
||||
bigScales += 1
|
||||
}
|
||||
words += 1
|
||||
end = j
|
||||
j += 1
|
||||
if zero || !token.open { break }
|
||||
}
|
||||
guard words > 0 else { return nil }
|
||||
parsed = Cardinal(value: total + current, end: end, words: words, hasScale: hasScale)
|
||||
parsed.bigScale = last == .big ? lastBig : nil
|
||||
parsed.bigScales = bigScales
|
||||
parsed.ambiguous = ambiguous
|
||||
if words == 1, case let .digit(value)? = kind(t[i].word) { parsed.single = value }
|
||||
}
|
||||
// Another number word right after, or before, makes it two numbers or a time: "three
|
||||
// thirty", "four ninety nine", "twenty twenty five hundred".
|
||||
if t[parsed.end].open, parsed.end + 1 < t.count, isNumberish(t[parsed.end + 1]) { parsed.ambiguous = true }
|
||||
if followsNumber(t, i), !t[i - 1].hasDigit { parsed.ambiguous = true }
|
||||
return parsed
|
||||
}
|
||||
|
||||
private static func additive(_ kind: Kind?) -> Bool {
|
||||
switch kind {
|
||||
case let .digit(value)?: value > 0
|
||||
case .teen?, .tens?, .tensUnit?: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
/// The last token of the run of number words from `i`.
|
||||
private static func clusterEnd(_ t: [Token], from i: Int) -> Int {
|
||||
var j = i
|
||||
while j + 1 < t.count, t[j].open, isNumberish(t[j + 1]) || t[j + 1].word == "point" { j += 1 }
|
||||
return j
|
||||
}
|
||||
|
||||
private static func written(_ number: Cardinal) -> String {
|
||||
if number.isYear { return String(number.value) }
|
||||
if let big = number.bigScale, number.bigScales == 1, big.value >= 1_000_000, number.value % big.value == 0 {
|
||||
return "\(number.value / big.value) \(big.word)"
|
||||
}
|
||||
return grouped(number.value)
|
||||
}
|
||||
|
||||
/// Commas from 10,000 up: Apple writes "8000" and "2400" but "15,000".
|
||||
private static func grouped(_ value: Int) -> String {
|
||||
let plain = String(value)
|
||||
guard value >= 10_000 else { return plain }
|
||||
var result = ""
|
||||
for (offset, character) in plain.reversed().enumerated() {
|
||||
if offset > 0, offset % 3 == 0 { result.append(",") }
|
||||
result.append(character)
|
||||
}
|
||||
return String(result.reversed())
|
||||
}
|
||||
|
||||
/// "point five", "point one point four" after a number, and a scale after one decimal
|
||||
/// ("one point two million").
|
||||
private static func decimal(_ t: [Token], after number: Cardinal, from i: Int) -> (text: String, end: Int, ambiguous: Bool)? {
|
||||
guard !number.isYear, number.bigScale == nil, t[number.end].open, number.end + 2 < t.count,
|
||||
t[number.end + 1].word == "point", t[number.end + 1].open, !t[number.end + 1].hasDigit else { return nil }
|
||||
// "at one point", "that one point".
|
||||
if number.value == 1, number.words == 1, i > 0,
|
||||
["at", "some", "that", "this", "any", "the", "one", "a"].contains(t[i - 1].word) { return nil }
|
||||
var text = String(number.value)
|
||||
var end = number.end
|
||||
var points = 0
|
||||
var j = number.end + 1
|
||||
while j + 1 < t.count, t[end].open, t[j].word == "point", t[j].open, !t[j].hasDigit {
|
||||
var digits = ""
|
||||
var k = j + 1
|
||||
while k < t.count, let digit = spokenDigit(t[k]) {
|
||||
digits += String(digit)
|
||||
end = k
|
||||
k += 1
|
||||
if !t[end].open { break }
|
||||
}
|
||||
guard !digits.isEmpty else { break }
|
||||
text += "." + digits
|
||||
points += 1
|
||||
j = k
|
||||
}
|
||||
guard points > 0 else { return nil }
|
||||
if points == 1, t[end].open, end + 1 < t.count, let big = bigWords[t[end + 1].word], big >= 1_000_000,
|
||||
!t[end + 1].hasDigit {
|
||||
text += " " + t[end + 1].word
|
||||
end += 1
|
||||
}
|
||||
let ambiguous = t[end].open && end + 1 < t.count && isNumberish(t[end + 1])
|
||||
return (text, end, ambiguous)
|
||||
}
|
||||
|
||||
private static func number(_ t: [Token], at i: Int, forced: Bool) -> Outcome {
|
||||
guard i < t.count, isNumberish(t[i]) else { return .none }
|
||||
if let time = clockTime(t, at: i) { return time }
|
||||
guard let number = cardinal(t, at: i) else { return .none }
|
||||
if number.ambiguous { return .skip(clusterEnd(t, from: i)) }
|
||||
var text = written(number)
|
||||
var end = number.end
|
||||
var isDecimal = false
|
||||
if let point = decimal(t, after: number, from: i) {
|
||||
if point.ambiguous { return .skip(clusterEnd(t, from: point.end)) }
|
||||
text = point.text
|
||||
end = point.end
|
||||
isDecimal = true
|
||||
}
|
||||
let lead = t[i].lead
|
||||
let next = end + 1
|
||||
let open = t[end].open && next < t.count
|
||||
// Digits right beside it: the model already wrote this number its way.
|
||||
if open, t[next].hasDigit { return .skip(end) }
|
||||
if i > 0, t[i - 1].open, t[i - 1].hasDigit { return .skip(end) }
|
||||
let plain = !isDecimal && !number.isYear && !number.hasScale
|
||||
if open {
|
||||
let word = t[next].word
|
||||
if word == "percent" { return .edit(i, next, lead + text + "%" + t[next].trail) }
|
||||
if word == "per", t[next].open, next + 1 < t.count, t[next + 1].word == "cent" {
|
||||
return .edit(i, next + 1, lead + text + "%" + t[next + 1].trail)
|
||||
}
|
||||
if word == "dollar" || word == "dollars" {
|
||||
return money(t, at: i, amount: text, isDecimal: isDecimal, dollars: next)
|
||||
}
|
||||
// "twenty first": an ordinal, outside dates for now.
|
||||
if isOrdinal(word) { return .skip(next) }
|
||||
if plain, (1...12).contains(number.value), isMeridiem(t[next]) || word == "o'clock" || word == "o’clock" {
|
||||
return .edit(i, end, lead + text)
|
||||
}
|
||||
if !forced, plain, number.value < 100, let range = range(t, number, at: i, end: end, text: lead + text) {
|
||||
return range
|
||||
}
|
||||
if isCountNoun(t, next) {
|
||||
if forced || !plain || number.value >= 10 { return .edit(i, end, lead + text) }
|
||||
if let single = number.single {
|
||||
let possessive = i > 0 && ["my", "your", "his", "her", "our", "their"].contains(t[i - 1].word)
|
||||
if single >= 2, !(word == "cents" && possessive) { return .edit(i, end, lead + text) }
|
||||
if single == 1, oneUnits.contains(word) { return .edit(i, end, lead + text) }
|
||||
}
|
||||
return .skip(end)
|
||||
}
|
||||
if fractions.contains(word) || decades.contains(word) { return .skip(end) }
|
||||
if word == "and", next + 2 < t.count, t[next + 1].word == "a", fractions.contains(t[next + 2].word) {
|
||||
return .skip(end)
|
||||
}
|
||||
}
|
||||
if forced || !plain || number.value >= 10 { return .edit(i, end, lead + text + t[end].trail) }
|
||||
return .skip(end)
|
||||
}
|
||||
|
||||
/// "five to ten minutes", "two or three days", "between five and ten minutes": the first
|
||||
/// number goes into digits with the second, which its own rule writes, only when a plural
|
||||
/// noun or unit follows. Without one it may be a score, a time or "nine to five", so both
|
||||
/// stay as said. "one or two" stays too.
|
||||
private static func range(_ t: [Token], _ first: Cardinal, at i: Int, end: Int, text: String) -> Outcome? {
|
||||
let link = end + 1
|
||||
let word = t[link].word
|
||||
let between = word == "and" && i > 0 && t[i - 1].word == "between"
|
||||
guard ["to", "through", "or", "past"].contains(word) || between, t[link].open,
|
||||
let second = cardinal(t, at: link + 1), !second.ambiguous else { return nil }
|
||||
var secondEnd = second.end
|
||||
var secondPlain = !second.isYear && !second.hasScale && second.value < 100
|
||||
if let point = decimal(t, after: second, from: link + 1) {
|
||||
secondEnd = point.end
|
||||
secondPlain = false
|
||||
}
|
||||
guard secondPlain else { return nil }
|
||||
let unitAfter = t[secondEnd].open && isCountNoun(t, secondEnd + 1)
|
||||
if word == "past" || !unitAfter || (word == "or" && first.single == 1) { return .skip(secondEnd) }
|
||||
return .edit(i, end, text)
|
||||
}
|
||||
|
||||
/// "seven fifteen pm" as 7:15, "seven oh five am" as 7:05: the marker stays as written.
|
||||
private static func clockTime(_ t: [Token], at i: Int) -> Outcome? {
|
||||
guard i + 2 < t.count, t[i].open, t[i + 1].open, !t[i + 1].hasDigit else { return nil }
|
||||
let hour: Int
|
||||
switch kind(t[i].word) {
|
||||
case let .digit(value)? where value > 0: hour = value
|
||||
case let .teen(value)? where value <= 12: hour = value
|
||||
default: return nil
|
||||
}
|
||||
var minutes: Int?
|
||||
var end = i + 1
|
||||
let unit: Int? = {
|
||||
guard i + 2 < t.count, !t[i + 2].hasDigit, case let .digit(value)? = kind(t[i + 2].word), value > 0 else {
|
||||
return nil
|
||||
}
|
||||
return value
|
||||
}()
|
||||
switch kind(t[i + 1].word) {
|
||||
case let .teen(value)?:
|
||||
minutes = value
|
||||
case let .tens(value)? where value <= 50:
|
||||
minutes = value
|
||||
if let unit {
|
||||
minutes = value + unit
|
||||
end = i + 2
|
||||
}
|
||||
case let .tensUnit(value)? where value < 60:
|
||||
minutes = value
|
||||
default:
|
||||
if t[i + 1].word == "oh", let unit {
|
||||
minutes = unit
|
||||
end = i + 2
|
||||
}
|
||||
}
|
||||
guard let minutes, t[end].open, end + 1 < t.count, isMeridiem(t[end + 1]) else { return nil }
|
||||
return .edit(i, end, t[i].lead + "\(hour):" + (minutes < 10 ? "0" : "") + "\(minutes)")
|
||||
}
|
||||
|
||||
private static func isMeridiem(_ token: Token) -> Bool {
|
||||
let plain = token.word.replacingOccurrences(of: ".", with: "")
|
||||
return !token.hasDigit && (plain == "am" || plain == "pm")
|
||||
}
|
||||
|
||||
/// "$5", "$15.40" (with "and forty cents"), "$1.2 million", "$5.50".
|
||||
private static func money(_ t: [Token], at i: Int, amount: String, isDecimal: Bool, dollars: Int) -> Outcome {
|
||||
var written = amount
|
||||
var end = dollars
|
||||
if isDecimal, let dot = written.firstIndex(of: "."), written.distance(from: dot, to: written.endIndex) == 2 {
|
||||
written += "0"
|
||||
}
|
||||
if !isDecimal, !written.contains(" "), t[dollars].open {
|
||||
var j = dollars + 1
|
||||
if j < t.count, t[j].word == "and", t[j].open { j += 1 }
|
||||
if let cents = cardinal(t, at: j), !cents.ambiguous, !cents.isYear, !cents.hasScale,
|
||||
(1...99).contains(cents.value), t[cents.end].open, cents.end + 1 < t.count,
|
||||
["cents", "cent"].contains(t[cents.end + 1].word) {
|
||||
written += "." + (cents.value < 10 ? "0" : "") + "\(cents.value)"
|
||||
end = cents.end + 1
|
||||
}
|
||||
}
|
||||
return .edit(i, end, t[i].lead + "$" + written + t[end].trail)
|
||||
}
|
||||
|
||||
/// A plural noun or a unit: "dogs", "people", "more minutes", "foot", "K".
|
||||
private static func isCountNoun(_ t: [Token], _ k: Int) -> Bool {
|
||||
guard k < t.count, !t[k].hasDigit, !t[k].core.isEmpty else { return false }
|
||||
let word = t[k].word
|
||||
if units.contains(word) { return true }
|
||||
if bridges.contains(word), t[k].open { return isPlural(t, k + 1) }
|
||||
return isPlural(t, k)
|
||||
}
|
||||
|
||||
private static func isPlural(_ t: [Token], _ k: Int) -> Bool {
|
||||
guard k < t.count, !t[k].hasDigit, t[k].core.first?.isLowercase == true,
|
||||
t[k].core.allSatisfy(\.isLetter) else { return false }
|
||||
let word = t[k].word
|
||||
if irregularPlurals.contains(word) { return true }
|
||||
guard word.count >= 3, word.hasSuffix("s"), !notPlural.contains(word), !fractions.contains(word),
|
||||
!decades.contains(word) else { return false }
|
||||
return !["ss", "us", "is"].contains { word.hasSuffix($0) }
|
||||
}
|
||||
}
|
||||
@@ -260,6 +260,31 @@ never at a launch by itself.
|
||||
or off). Other numbers stay ("Chapter one, two and three", "room 123", "test
|
||||
123 passed"). The tagger alone took a count in words for a self-correction
|
||||
("Test one two three" became "Test three."); `CleanupGuard` keeps it.
|
||||
- **Numbers as digits (Settings › Dictation, on by default; English, every style but
|
||||
Verbatim):** numbers said in words are written in digits, as Apple's
|
||||
`SpeechTranscriber` writes them, so every engine reads the same
|
||||
(`SpokenNumbers`, run by `CleanupTagger.cleanIfEnabled` after Spoken counts and before
|
||||
the tagger, so the tagger never removes a number in digits outside a self-correction).
|
||||
Parakeet V2 now and then writes a whole sentence in words ("The ratio is five point
|
||||
five.", "november twenty second"), mostly in a real voice: 53 of 80 test sentences in
|
||||
Ryan's cloned voice against 11 of 80 in macOS voices (macOS 27.2.1,
|
||||
`experiments/2026-11-22-hex-numbers`). It writes decimals ("5.5", "3.1.4", "1.2
|
||||
million"), percentages ("20%"), numbers from ten up and compounds ("25", "312",
|
||||
"15,000"; commas from 10,000, as Apple writes "8000"), years ("1999", "2026"), money
|
||||
with "dollars" ("$5", "$15.40"), two to nine before a plural noun or unit ("2 dogs", "6
|
||||
foot"), ranges ending in one ("5 to 10 minutes"), times with am, pm or o'clock ("6 am",
|
||||
"7:15 pm"), ordinals in dates ("November 22nd", "the 4th of July"; "May" and "March"
|
||||
only with a capital), three or more spoken digits ("4729", "555-123-4567"), and minus or
|
||||
negative before a number ("-5", "-$40"). Text already in digits keeps its form ("2,400",
|
||||
"$4.99"). Not yet: "one" alone ("one of them", "no one", "one more"), times and prices
|
||||
without a marker ("three thirty", "four ninety nine", "twelve fifty"), ranges and scores
|
||||
without a unit ("eight to twelve", "three to one"), fractions, ordinals outside dates
|
||||
("finished first", "twenty first floor", "a second"), small numbers before anything else
|
||||
("at eight", "GPT five"), and any run of number words that reads two ways ("one thirty").
|
||||
Other languages keep their words: each needs its own number words, compounds (German
|
||||
"fünfundzwanzig", French "quatre-vingt-dix") and separators ("5,5" and "15.000" in
|
||||
German, French, Spanish, Italian and Dutch). `SpokenCleanupRulesTests` holds the 80
|
||||
sentences as both engines wrote them in both voices.
|
||||
- **Mid-sentence dictation:** when the text before the cursor doesn't end a
|
||||
sentence (`.` `!` `?` `…` or a line break), the keyboard lowercases the
|
||||
dictation's first word, except "I" and its contractions, acronyms, words
|
||||
|
||||
Reference in New Issue
Block a user