iOS: format dictated lists, and write out gonna and wanna (#2131)

* iOS: format dictated lists and spoken line breaks

An X tester asked for spoken bullet and numbered lists to come out
formatted. Settings › Dictation › Format lists (on by default,
DictationListSettings, App Group key settings.dictationFormatLists)
runs SpokenLists inside every style but Verbatim, after the fillers
and before the style's punctuation, in English and Spanish:

- "first … second …" (also 1st/2nd, primero/segundo, en primer lugar),
  "number/step/item/point one …", and "one, … two, …" become 1. lines;
- "bullet", "bullet point", "next item", "dash" (viñeta, guion) said
  twice or more become "- " lines, as the Notes style writes bullets;
- "new line" / "new paragraph" (nueva línea, nuevo párrafo, salto de
  línea) break lines, matching desktop's Labs › Spoken formatting words.

Guards keep prose: markers count up from one, two or more non-empty
items, each marker at a clause start, a bare number needs its comma,
and nouns like "the first time", "second guess", "a new line of",
"bullet points" stay. Casual now keeps a list item's capital.
Desktop has no deterministic list formatter (its OpenCode prompt asks
for "1. …" lists); the numbering matches that.

Verified: xcodebuild test on an iOS 27.2 simulator, 395 tests, 0
failures, including SpokenListsTests (lists in both languages, 62
prose sentences unchanged, lead-in plus list, every style, the
pipeline switch and Lowercase). The list inputs are Apple Speech's
own transcripts of spoken lists (SpeechTranscriber on macOS 27.2).

* iOS: Polished writes out gonna, wanna, gotta, kinda, lemme

A tester on X asked Hex to correct the "wanna" and "gonna" that
Apple's speech models write since iOS 27 (macOS 27.2's
SpeechTranscriber writes "I'm gonna call you later." too). The
Polished style (the default) now writes "going to", "want to",
"got to", "kind of" and "let me", in English only, before it
capitalizes sentences. Casual and Verbatim keep the words as heard.

Never inside straight or curly quotes, and never on a capitalized
word mid-sentence (a name or title such as "Gonna Fly Now"); one
that starts a sentence or a list item keeps its capital ("Going to").

Verified: InformalContractionTests in TranscriptCleanupTests (Polished
expansions, quotes, names, Spanish untouched, Casual and Verbatim
unchanged, list items), xcodebuild test on an iOS 27.2 simulator.
This commit is contained in:
Ryan Vogel
2026-11-21 03:01:16 +00:00
committed by GitHub
parent c930f1e9cd
commit 71b5a8ecf0
9 changed files with 982 additions and 10 deletions
+3 -2
View File
@@ -386,14 +386,15 @@ final class KeyboardLocalDictation {
let locale = language.identifier
let style = KeyboardBridge().style
let vocabulary = CustomVocabularySettings().activeTerms
// The app's steps (but Apple Intelligence's cleanup), its style and Lowercase
// included.
// The app's steps (but Apple Intelligence's cleanup), its style, Format lists
// and Lowercase included.
let pipeline = DictationPipeline(
style: style,
language: locale,
vocabulary: vocabulary,
corrections: fixes,
lowercase: DictationLowercaseSettings().isEnabled,
formatLists: DictationListSettings().isEnabled,
hinglish: HinglishSettings().isEnabled
)
let steps = await pipeline.run(heard, translationSource: language.locale.language)
+8
View File
@@ -50,6 +50,8 @@ final class DictationController {
let usesCleanup: Bool
/// Settings › Dictation › Lowercase, read at start.
let lowercase: Bool
/// Settings › Dictation › Format lists, read at start.
let formatLists: Bool
/// Experiments › Hinglish, read at start.
let hinglish: Bool
let vocabularyTerms: [String]
@@ -76,6 +78,7 @@ final class DictationController {
private let cleanupSettings: AppleIntelligenceCleanupSettings
private let customVocabularySettings: CustomVocabularySettings
private let lowercaseSettings: DictationLowercaseSettings
private let listSettings: DictationListSettings
private let hinglishSettings: HinglishSettings
private let typingJournalSettings: TypingJournalSettings
private let learnedDictationCorrections: @MainActor () -> [DictationCorrection]
@@ -181,6 +184,7 @@ final class DictationController {
cleanupSettings: AppleIntelligenceCleanupSettings = AppleIntelligenceCleanupSettings(),
customVocabularySettings: CustomVocabularySettings = CustomVocabularySettings(),
lowercaseSettings: DictationLowercaseSettings = DictationLowercaseSettings(),
listSettings: DictationListSettings = DictationListSettings(),
hinglishSettings: HinglishSettings = HinglishSettings(),
typingJournalSettings: TypingJournalSettings = TypingJournalSettings(),
learnedDictationCorrections: (@MainActor () -> [DictationCorrection])? = nil,
@@ -198,6 +202,7 @@ final class DictationController {
self.cleanupSettings = cleanupSettings
self.customVocabularySettings = customVocabularySettings
self.lowercaseSettings = lowercaseSettings
self.listSettings = listSettings
self.hinglishSettings = hinglishSettings
self.typingJournalSettings = typingJournalSettings
self.learnedDictationCorrections = learnedDictationCorrections ?? {
@@ -743,6 +748,7 @@ final class DictationController {
let effectiveStyle = styleOverride ?? style
let usesCleanup = cleanupSettings.isEnabled
let lowercase = lowercaseSettings.isEnabled
let formatLists = listSettings.isEnabled
let hinglish = hinglishSettings.isEnabled
let language = transcriptionLanguageID
CleanupTagger.prepareIfEnabled(style: effectiveStyle, language: language)
@@ -794,6 +800,7 @@ final class DictationController {
style: effectiveStyle,
usesCleanup: usesCleanup,
lowercase: lowercase,
formatLists: formatLists,
hinglish: hinglish,
vocabularyTerms: vocabularyTerms,
personalCorrections: personalCorrections,
@@ -882,6 +889,7 @@ final class DictationController {
vocabulary: session.vocabularyTerms,
corrections: session.personalCorrections,
lowercase: session.lowercase,
formatLists: session.formatLists,
hinglish: session.hinglish
)
let stages = await pipeline.run(rawText) { tagged in
+20
View File
@@ -1413,6 +1413,26 @@
}
}
},
"Format lists" : {
"localizations" : {
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "整理列表"
}
}
}
},
"Say “first, second” or “bullet” for a list" : {
"localizations" : {
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "说“first, second”或“bullet”即可分行列出"
}
}
}
},
"Messages" : {
"shouldTranslate" : false
},
+14
View File
@@ -7,6 +7,7 @@ struct DictationSettingsPage: View {
@State private var cleanupTagger = CleanupTaggerSettings().isEnabled
@State private var customVocabulary = CustomVocabularySettings().isEnabled
@State private var lowercase = DictationLowercaseSettings().isEnabled
@State private var formatLists = DictationListSettings().isEnabled
var body: some View {
SettingsPageScaffold(title: "Dictation") {
@@ -42,6 +43,15 @@ struct DictationSettingsPage: View {
isOn: $lowercase
)
SettingsDivider()
// Inside the style, on every path (`SpokenLists`).
SettingsToggleRow(
title: String(localized: "Format lists"),
detail: String(localized: "Say “first, second” or “bullet” for a list"),
isOn: $formatLists
)
DictationLanguageRow(dictation: dictation)
}
@@ -115,10 +125,14 @@ struct DictationSettingsPage: View {
.onChange(of: lowercase) { _, enabled in
DictationLowercaseSettings().isEnabled = enabled
}
.onChange(of: formatLists) { _, enabled in
DictationListSettings().isEnabled = enabled
}
.onAppear {
cleanupTagger = CleanupTaggerSettings().isEnabled
customVocabulary = CustomVocabularySettings().isEnabled
lowercase = DictationLowercaseSettings().isEnabled
formatLists = DictationListSettings().isEnabled
}
}
}
@@ -479,3 +479,260 @@ final class HinglishRomanizerTests: XCTestCase {
XCTAssertNil(settings.name(for: "en-IN"))
}
}
/// Settings › Dictation › Format lists. The English and Spanish inputs are what Apple Speech
/// (SpeechTranscriber, macOS 27.2, Samantha and Paulina voices) wrote for spoken lists.
final class SpokenListsTests: XCTestCase {
private func lists(_ text: String, _ language: String = "en-US") -> String {
SpokenLists.format(text, language: language)
}
func testNumberedListsInEnglish() {
XCTAssertEqual(
lists("Here is my shopping list. First, eggs. Second, milk, third, bread."),
"Here is my shopping list.\n1. Eggs\n2. Milk\n3. Bread"
)
XCTAssertEqual(
lists("My shopping list, 1st egg, 2nd milk, and 3rd bread."),
"My shopping list:\n1. Egg\n2. Milk\n3. Bread"
)
XCTAssertEqual(
lists("Number one, call the bank. Number two, pay rent. Number three, email Sam."),
"1. Call the bank\n2. Pay rent\n3. Email Sam"
)
XCTAssertEqual(
lists("One, buy tickets. Two, book the hotel. Three, pack."),
"1. Buy tickets\n2. Book the hotel\n3. Pack"
)
XCTAssertEqual(
lists("Step one preheat the oven, step two, mix the flour, step three, bake for 20 minutes."),
"1. Preheat the oven\n2. Mix the flour\n3. Bake for 20 minutes"
)
XCTAssertEqual(lists("1. Eggs. 2. Milk."), "1. Eggs\n2. Milk")
XCTAssertEqual(lists("First of all, thanks. Second of all, sorry."), "1. Thanks\n2. Sorry")
}
/// "finally" ends a list of two or more; what follows the last item's sentence is its own
/// line, and a later list is found too.
func testListEndsAndWhatFollows() {
XCTAssertEqual(
lists("First, preheat the oven. Second, mix. And finally, bake. Thanks!"),
"1. Preheat the oven\n2. Mix\n3. Bake\nThanks!"
)
XCTAssertEqual(
lists("Third, bake for 20 minutes. Let it cool. First, preheat. Second, mix."),
"Third, bake for 20 minutes. Let it cool.\n1. Preheat\n2. Mix"
)
XCTAssertEqual(
lists("Who's coming? First, Ana. Second, who else?"),
"Who's coming?\n1. Ana\n2. Who else?"
)
XCTAssertEqual(
lists("Packing: first, the iPhone charger, second, passport."),
"Packing:\n1. The iPhone charger\n2. Passport"
)
}
func testBulletsAndLineBreaks() {
XCTAssertEqual(lists("Groceries, bullet, eggs, bullet, milk, bullet bread."), "Groceries:\n- Eggs\n- Milk\n- Bread")
XCTAssertEqual(lists("Todo bullet ship it bullet tell Ravi"), "Todo:\n- Ship it\n- Tell Ravi")
XCTAssertEqual(lists("Agenda: next item, budget. Next item, hiring."), "Agenda:\n- Budget\n- Hiring")
XCTAssertEqual(lists("Dash, eggs. Dash, milk."), "- Eggs\n- Milk")
XCTAssertEqual(
lists("Dear Sam, new line, thanks for the help, new paragraph see you soon."),
"Dear Sam\nthanks for the help\n\nsee you soon."
)
XCTAssertEqual(lists("Shopping new line bullet eggs new line bullet milk"), "Shopping\n- Eggs\n- Milk")
}
func testSpanish() {
XCTAssertEqual(
lists("Mi lista de compras. Primero, huevos, segundo, leche, tercero, pan.", "es-ES"),
"Mi lista de compras.\n1. Huevos\n2. Leche\n3. Pan"
)
XCTAssertEqual(
lists("Uno, Comprar boletos. Dos, reservar el hotel. Tres, hacer la maleta.", "es-MX"),
"1. Comprar boletos\n2. Reservar el hotel\n3. Hacer la maleta"
)
XCTAssertEqual(lists("Viñeta, huevos, viñeta, leche, viñeta, pan.", "es-ES"), "- Huevos\n- Leche\n- Pan")
XCTAssertEqual(
lists("En primer lugar, gracias. En segundo lugar, perdón. Y por último, adiós.", "es-ES"),
"1. Gracias\n2. Perdón\n3. Adiós"
)
XCTAssertEqual(
lists("Hola Ana, nueva línea. Gracias por todo nuevo párrafo. Nos vemos.", "es-ES"),
"Hola Ana\nGracias por todo\n\nNos vemos."
)
XCTAssertEqual(lists("Paso uno, lavar. Paso dos, secar.", "es-ES"), "1. Lavar\n2. Secar")
}
func testOtherLanguagesStayAsSaid() {
XCTAssertEqual(lists("First, eggs. Second, milk.", "fr-FR"), "First, eggs. Second, milk.")
XCTAssertEqual(lists("Erstens, Eier. Zweitens, Milch.", "de-DE"), "Erstens, Eier. Zweitens, Milch.")
}
/// Prose that only looks like a list stays exactly as it was heard.
func testProseStaysAsSaid() {
let english = [
"The first time I saw it, I loved it.",
"She is one of the best.",
"I have two dogs and three cats.",
"Don't second guess yourself.",
"At first I didn't like it, but then I did.",
"First things first, let's eat.",
"He finished first and I finished second.",
"One day we'll go there.",
"Give me one second.",
"It's the second time this week.",
"We bought a new line of shoes.",
"The bullet points are on the slide.",
"I need to dash, see you.",
"Number one fans only.",
"One, two, three, go!",
"Step by step, we got there.",
"Who came first, the chicken or the egg?",
"My first car was red and my second was blue.",
"Two, maybe three people came.",
"One more thing, call me later.",
"The 1st time I saw it, I had to 2nd guess myself, one of the best, I have 2 dogs.",
"First of all, thank you for coming.",
"A bullet hit the wall.",
"In the first place, it was not my fault.",
"Add a new paragraph about pricing.",
"Firstly, I disagree.",
"We'll meet at 1, 2, or 3.",
"Chapter one, two and three are done.",
"One, two, buckle my shoe. Three, four, shut the door.",
"He said one thing, then another.",
"I was second in line, and first in my heart.",
"The second half was better than the first.",
"One of them said two words.",
"First come, first served.",
"Second to none.",
"We'll do it in one, two weeks.",
"Item one is missing.",
"Point taken, next item please.",
"Meet me at 1:30. 2 people are coming.",
"That's a new line for me.",
"Our new line of credit is ready.",
"Third time's the charm.",
"I came in second, and then first the next year.",
"Last, but not least, thanks.",
"One, I'm tired.",
"First, let me say thanks for coming.",
"Finally, we're done. Lastly, go home.",
"The dash cam caught it.",
"Number two pencils only.",
"There are two options. One, we wait.",
]
for sentence in english {
XCTAssertEqual(lists(sentence), sentence)
}
let spanish = [
"La primera vez que lo vi, me encantó.",
"Es uno de los mejores.",
"Tengo dos perros.",
"Espera un segundo.",
"Una nueva línea de productos.",
"Primero llegó Ana y segundo llegó Luis.",
"Uno nunca sabe.",
"Vivo en el segundo piso.",
"Compré una viñeta de Mafalda.",
"Es mi primer día.",
"Uno, dos, tres, ¡ya!",
"En primer lugar estaba Ana.",
]
for sentence in spanish {
XCTAssertEqual(lists(sentence, "es-ES"), sentence)
}
}
/// Each style ends the lines its own way; Verbatim keeps the model's words.
func testStylesEndTheLines() {
let heard = "Um, so the plan is, first, um, call the bank, second, pay rent. Thanks!"
let formatted = DictationStyle.allCases.map {
TranscriptFormatter.format(heard, style: $0, language: "en-US", lists: true)
}
XCTAssertEqual(formatted, [
"So the plan is:\n1. Call the bank.\n2. Pay rent.\nThanks!",
"so the plan is:\n1. Call the bank\n2. Pay rent\nthanks!",
"So the plan is:\n1. Call the bank\n2. Pay rent\nThanks!",
heard,
])
XCTAssertEqual(
TranscriptFormatter.format("Groceries, bullet, eggs, bullet, milk.", style: .polished, language: "en-US", lists: true),
"Groceries:\n- Eggs.\n- Milk."
)
XCTAssertEqual(
TranscriptFormatter.format(heard, style: .polished, language: "en-US"),
"So the plan is, first, call the bank, second, pay rent. Thanks!",
"off: as before"
)
}
/// The pipeline formats lists only with the switch on, and Lowercase still lowercases them.
func testPipelineSwitchAndLowercase() {
let heard = "First, eggs. Second, milk."
var pipeline = DictationPipeline(style: .notes, language: "en-US")
XCTAssertEqual(pipeline.format(heard, language: "en-US"), "- Eggs\n- Milk", "off: Notes as before")
pipeline.formatLists = true
XCTAssertEqual(pipeline.format(heard, language: "en-US"), "1. Eggs\n2. Milk")
pipeline.lowercase = true
XCTAssertEqual(pipeline.format(heard, language: "en-US"), "1. eggs\n2. milk")
let defaults = UserDefaults(suiteName: "hex.tests.\(UUID().uuidString)")!
let settings = DictationListSettings(defaults: defaults)
XCTAssertTrue(settings.isEnabled, "on by default")
settings.isEnabled = false
XCTAssertFalse(DictationListSettings(defaults: defaults).isEnabled)
}
}
/// iOS 27's speech models write "gonna", "wanna" and "gotta" (macOS 27.2's SpeechTranscriber
/// too: "I'm gonna call you later."); Polished writes them out, Casual and Verbatim keep them.
final class InformalContractionTests: XCTestCase {
private func polished(_ text: String) -> String {
TranscriptFormatter.format(text, style: .polished, language: "en-US")
}
func testPolishedWritesThemOut() {
XCTAssertEqual(
polished("I'm gonna call you later. I wanna finish this first."),
"I'm going to call you later. I want to finish this first."
)
XCTAssertEqual(polished("I gotta go, lemme know. It's kinda late"), "I got to go, let me know. It's kind of late.")
XCTAssertEqual(polished("Gonna be a long day."), "Going to be a long day.")
XCTAssertEqual(polished("ok. wanna grab lunch?"), "Ok. Want to grab lunch?")
}
func testQuotesNamesAndOtherWordsStay() {
XCTAssertEqual(polished("He said \"I'm gonna win\" and left."), "He said \"I'm gonna win\" and left.")
XCTAssertEqual(polished("She sang “Wanna Be Startin' Somethin'” all night."), "She sang “Wanna Be Startin' Somethin'” all night.")
XCTAssertEqual(polished("We played Gonna Fly Now on repeat."), "We played Gonna Fly Now on repeat.")
XCTAssertEqual(polished("The gonnabe kinds and the wannabes."), "The gonnabe kinds and the wannabes.")
XCTAssertEqual(
TranscriptFormatter.format("Voy a gonna mañana.", style: .polished, language: "es-ES"),
"Voy a gonna mañana.",
"English only"
)
}
func testCasualAndVerbatimKeepThem() {
let heard = "I'm gonna be late, wanna start without me?"
XCTAssertEqual(TranscriptFormatter.format(heard, style: .casual, language: "en-US"), "i'm gonna be late, wanna start without me?")
XCTAssertEqual(TranscriptFormatter.format(heard, style: .verbatim, language: "en-US"), heard)
}
func testListItems() {
XCTAssertEqual(
TranscriptFormatter.format("First, gonna call Sam. Second, wanna book the hotel.", style: .polished, language: "en-US", lists: true),
"1. Going to call Sam.\n2. Want to book the hotel."
)
XCTAssertEqual(
TranscriptFormatter.format("Todo bullet gotta pack bullet lemme check the car", style: .polished, language: "en-US", lists: true),
"Todo:\n- Got to pack.\n- Let me check the car."
)
}
}
+5 -2
View File
@@ -69,7 +69,8 @@ nonisolated struct HinglishSettings {
/// custom vocabulary, 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`), the spellings again, then Lowercase. The style and Lowercase are
/// (`TranscriptFormatter`, with Format lists' `SpokenLists` inside it), the spellings again,
/// then Lowercase. The style and Lowercase are
/// string rules with no model, so in-keyboard dictation needs no more memory to run them.
nonisolated struct DictationPipeline: Sendable {
var style: DictationStyle
@@ -80,6 +81,8 @@ nonisolated struct DictationPipeline: Sendable {
/// Learn how I type's dictation fixes; empty while it is off.
var corrections: [DictationCorrection] = []
var lowercase = false
/// Settings › Dictation › Format lists (`SpokenLists`), inside the style.
var formatLists = 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
@@ -136,7 +139,7 @@ nonisolated struct DictationPipeline: Sendable {
/// can lowercase a term or capitalize a sentence start: "iPhone" -> "IPhone"), then
/// Lowercase.
func format(_ text: String, language: String?) -> String {
let styled = TranscriptFormatter.format(text, style: style, language: language)
let styled = TranscriptFormatter.format(text, style: style, language: language, lists: formatLists)
let spelled = VocabularySpelling.apply(vocabulary + DictationCorrections.spellings(corrections), to: styled)
return lowercase ? spelled.lowercased() : spelled
}
+569
View File
@@ -0,0 +1,569 @@
import Foundation
/// Settings › Dictation › Format lists, in the shared App Group so in-keyboard dictation reads
/// it too. On by default.
nonisolated struct DictationListSettings {
static let enabledKey = "settings.dictationFormatLists"
private let defaults: UserDefaults?
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
self.defaults = defaults
}
/// Spoken lists ("first … second …", "bullet … bullet …") and line breaks ("new line",
/// "new paragraph") are written as lines (`SpokenLists`), in English and Spanish.
var isEnabled: Bool {
get { defaults?.object(forKey: Self.enabledKey) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Self.enabledKey) }
}
}
/// Dictated lists and line breaks as lines, with string rules and no model, in English and
/// Spanish; other languages are left as they are. Runs inside a style, after its fillers and
/// before its punctuation (`TranscriptFormatter.format(_:style:language:lists:)`), so each style
/// ends the lines its own way.
///
/// - "new line", "new paragraph" (desktop's Labs › Spoken formatting words; "nueva línea",
/// "nuevo párrafo", "salto de línea") become one or two line breaks, and the commas around
/// them go. Never at the very start, after "a", "the", "my", "una", … ("a new line of shoes"),
/// or before "of", "is", "de", … .
/// - Numbered lists: "first … second …" ("1st … 2nd …", "primero … segundo …",
/// "en primer lugar …"), "number one … number two …" ("step", "item", "point", "número",
/// "paso"), or "one, … two, …" ("uno, … dos, …", "1. … 2. …") become "1. …" lines. The
/// markers count up from one, there are at least two items, none is empty, and every
/// marker starts a clause: the start, after a mark (".", ",", ";", ":", …) or a line break,
/// or after "and"/"then"/"y"/"luego" that do. A bare number needs its comma ("one, …");
/// "finally" or "lastly" ("por último") ends a list of two or more.
/// - Bullets: "bullet", "bullet point", "next bullet", "next item", "dash" ("viñeta",
/// "guion", "siguiente elemento") said at least twice become "- …" lines, as the Notes style
/// already writes bullets (a hyphen reads in every app's plain text and is what Markdown and
/// Notes take for a list). "dash" and "guion" need a clause start; "bullet" may follow any
/// word but "a", "the", "to", … ("a bullet hit the wall").
/// - Text before the first marker is its own line, given a colon unless it ends a sentence;
/// a last item ends at its first sentence, and what follows is its own line. Items start
/// with a capital and lose a trailing comma, period, "and" or "or".
nonisolated enum SpokenLists {
static func format(_ text: String, language: String?) -> String {
guard let table = Table.forLanguage(language), !text.isEmpty else { return text }
return listing(breaking(text, table), table)
}
// MARK: Words
private struct Token {
let text: String
let isWord: Bool
/// Lowercased, accents and "ñ" folded: "Viñeta" reads "vineta".
let folded: String
}
/// Alternating words (letters, digits, apostrophes) and the separators between them.
private static func tokenize(_ text: String) -> [Token] {
var tokens: [Token] = []
var current = ""
var currentIsWord: Bool?
func flush() {
guard let isWord = currentIsWord else { return }
let folded = isWord ? current.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) : current
tokens.append(Token(text: current, isWord: isWord, folded: folded))
}
for character in text {
let isWord = character.isLetter || character.isNumber || character == "'" || character == "’"
if currentIsWord == isWord {
current.append(character)
} else {
flush()
current = String(character)
currentIsWord = isWord
}
}
flush()
return tokens
}
private static func joined(_ tokens: ArraySlice<Token>) -> String {
tokens.map(\.text).joined()
}
/// Marks that end a clause, so a marker after them starts one.
private static let clauseBoundaries: Set<Character> = [".", ",", ";", ":", "!", "?", "…", "—", "–", "\n", "(", "¿", "¡"]
private struct Words {
let tokens: [Token]
let table: Table
func isWord(_ index: Int) -> Bool { tokens.indices.contains(index) && tokens[index].isWord }
func spacesOnly(_ index: Int) -> Bool {
tokens.indices.contains(index) && !tokens[index].isWord
&& tokens[index].text.allSatisfy { $0 == " " || $0 == "\t" }
}
/// Where `words` said one after another (spaces between) starting at `index` end.
func phrase(_ words: [String], at index: Int) -> Int? {
var position = index
for (number, word) in words.enumerated() {
if number > 0 {
guard spacesOnly(position) else { return nil }
position += 1
}
guard isWord(position), tokens[position].folded == word else { return nil }
position += 1
}
return position
}
/// The word right after the separator at `end`, when only spaces come between.
func nextWord(after end: Int) -> String? {
spacesOnly(end) && isWord(end + 1) ? tokens[end + 1].folded : nil
}
/// The word right before `index`, when only spaces come between.
func previousWord(before index: Int) -> String? {
index >= 2 && spacesOnly(index - 1) && isWord(index - 2) ? tokens[index - 2].folded : nil
}
/// Whether the word at `index` starts a clause: the text's start, after a mark or a
/// line break, or after connectors ("and then") that start one.
func startsClause(_ index: Int) -> Bool {
var position = index
while position >= 2 {
if tokens[position - 1].text.contains(where: clauseBoundaries.contains) { return true }
guard table.connectors.contains(tokens[position - 2].folded) else { return false }
position -= 2
}
return true
}
/// The separator after the word ending at `end`, "" at the end of the text.
func separator(at end: Int) -> String {
tokens.indices.contains(end) && !tokens[end].isWord ? tokens[end].text : ""
}
/// A number said as a word or written in digits ("two", "dos", "2"), 1 to 20.
func number(at index: Int) -> Int? {
guard isWord(index) else { return nil }
let word = tokens[index].folded
if let value = table.cardinals[word] { return value }
guard word.count <= 2, word.allSatisfy(\.isASCII), let value = Int(word), (1...20).contains(value) else { return nil }
return value
}
}
// MARK: Line breaks
private static func breaking(_ text: String, _ table: Table) -> String {
let words = Words(tokens: tokenize(text), table: table)
let tokens = words.tokens
var out = ""
var index = 0
var sawWord = false
while index < tokens.count {
if tokens[index].isWord, sawWord, let (breaks, end) = lineBreak(at: index, words) {
while let last = out.last, last == " " || last == "\t" || last == "," || last == ";" {
out.removeLast()
}
out += breaks
index = end
if index < tokens.count, !tokens[index].isWord {
out += tokens[index].text.drop { " \t,.;:".contains($0) }
index += 1
}
continue
}
sawWord = sawWord || tokens[index].isWord
out += tokens[index].text
index += 1
}
return out
}
private static func lineBreak(at index: Int, _ words: Words) -> (String, Int)? {
for (phrase, breaks) in words.table.breaks {
guard let end = words.phrase(phrase, at: index) else { continue }
if let previous = words.previousWord(before: index), words.table.determiners.contains(previous) { return nil }
if let next = words.nextWord(after: end), words.table.breakFollowers.contains(next) { return nil }
return (breaks, end)
}
return nil
}
// MARK: Lists
private enum Family: Equatable {
case ordinal
case cardinal
case keyword(String)
case bullet
}
private struct Marker {
let family: Family
/// The item's number; 0 for "finally".
let value: Int
let start: Int
let end: Int
}
private static func markers(_ words: Words) -> [Marker] {
var found: [Marker] = []
var index = 0
while index < words.tokens.count {
if words.isWord(index), let marker = marker(at: index, words) {
found.append(marker)
index = marker.end
} else {
index += 1
}
}
return found
}
private static func marker(at index: Int, _ words: Words) -> Marker? {
let table = words.table
let word = words.tokens[index].folded
for (phrase, needsMark) in table.finals {
guard let end = words.phrase(phrase, at: index), words.startsClause(index) else { continue }
let after = words.separator(at: end)
if needsMark, !after.hasPrefix(","), !after.hasPrefix(":") { continue }
return Marker(family: .ordinal, value: 0, start: index, end: end)
}
for (phrase, value) in table.ordinalPhrases {
guard let end = words.phrase(phrase, at: index), words.startsClause(index) else { continue }
return Marker(family: .ordinal, value: value, start: index, end: end)
}
if table.keywords.contains(word), words.spacesOnly(index + 1), let value = words.number(at: index + 2),
words.startsClause(index) {
return Marker(family: .keyword(word), value: value, start: index, end: index + 3)
}
for (phrase, strict) in table.bullets {
guard let end = words.phrase(phrase, at: index) else { continue }
let previous = words.previousWord(before: index)
let starts = words.startsClause(index)
|| (!strict && !(previous.map(table.determiners.contains) ?? false))
if !starts { return nil }
if let next = words.nextWord(after: end), table.bulletFollowers.contains(next) { return nil }
return Marker(family: .bullet, value: 1, start: index, end: end)
}
if let value = table.ordinal(word), words.startsClause(index) {
if words.spacesOnly(index + 1), words.phrase(table.ofAll, at: index + 2) != nil {
return Marker(family: .ordinal, value: value, start: index, end: index + 1 + 2 * table.ofAll.count)
}
if let next = words.nextWord(after: index + 1), table.ordinalFollowers.contains(next) { return nil }
return Marker(family: .ordinal, value: value, start: index, end: index + 1)
}
if let value = words.number(at: index), words.startsClause(index) {
// A bare number counts only with its mark and a space after: "one, eggs", "1. eggs",
// never "1:30" or "1.5".
let separator = words.separator(at: index + 1)
guard let mark = separator.first, ",:.)".contains(mark),
separator.dropFirst().first?.isWhitespace ?? (index + 2 >= words.tokens.count) else { return nil }
return Marker(family: .cardinal, value: value, start: index, end: index + 1)
}
return nil
}
/// The lists among `markers` in order: numbered runs counting up from 1, and two bullets or
/// more.
private static func lists(_ markers: [Marker]) -> [[Marker]] {
var runs: [[Marker]] = []
for (position, first) in markers.enumerated() {
if first.family == .bullet {
let run = markers[position...].filter { $0.family == .bullet }
if run.count >= 2 { runs.append(Array(run)) }
continue
}
guard first.value == 1 else { continue }
var run = [first]
for marker in markers[(position + 1)...] where marker.family == first.family {
if marker.value == run.count + 1 {
run.append(marker)
} else if marker.value == 0, run.count >= 2 {
run.append(marker)
break
}
}
if run.count >= 2 { runs.append(run) }
}
return runs
}
private static func listing(_ text: String, _ table: Table) -> String {
let words = Words(tokens: tokenize(text), table: table)
for run in lists(markers(words)) {
// A run with an empty item ("one, two, three, go") is no list; a later one may be.
if let formatted = format(run, words) { return formatted }
}
return text
}
private static func format(_ run: [Marker], _ words: Words) -> String? {
let tokens = words.tokens
let table = words.table
guard let last = run.last else { return nil }
// The last item ends at its first sentence (or line); what follows is its own line.
var itemsEnd = tokens.count
var tailBreak = "\n"
var sawWord = false
for index in last.end..<tokens.count {
if tokens[index].isWord {
sawWord = true
continue
}
guard sawWord, index + 1 < tokens.count else { continue }
let separator = tokens[index].text
if separator.contains("\n") || endsSentence(separator, after: tokens[index - 1].folded) {
itemsEnd = index
tailBreak = separator.contains("\n\n") ? "\n\n" : "\n"
break
}
}
var items: [String] = []
for (number, marker) in run.enumerated() {
let end = number + 1 < run.count ? run[number + 1].start : itemsEnd
var raw = joined(tokens[marker.end..<end])
// The last item keeps its sentence's mark ("?", "!") but not what follows.
if number + 1 == run.count, itemsEnd < tokens.count {
let separator = tokens[itemsEnd].text
raw += separator.prefix { !$0.isWhitespace }
}
let item = cleanItem(raw, table)
guard !item.isEmpty else { return nil }
items.append(item)
}
var output = ""
let leadIn = joined(tokens[..<run[0].start])
let leadTrimmed = String(leadIn.reversed().drop { $0 == " " || $0 == "\t" }.reversed())
if leadTrimmed.hasSuffix("\n") {
output = leadTrimmed
} else {
var lead = stripTrailingConnectors(leadIn.trimmingCharacters(in: .whitespacesAndNewlines), table)
while let mark = lead.last, ",;-–—".contains(mark) {
lead.removeLast()
lead = lead.trimmingCharacters(in: .whitespaces)
}
if let mark = lead.last {
if mark.isLetter || mark.isNumber { lead += ":" }
output = lead + "\n"
}
}
let isBullet = run[0].family == .bullet
output += items.enumerated()
.map { isBullet ? "- " + $0.element : "\($0.offset + 1). " + $0.element }
.joined(separator: "\n")
if itemsEnd < tokens.count {
let tail = joined(tokens[(itemsEnd + 1)...]).trimmingCharacters(in: .whitespacesAndNewlines)
if !tail.isEmpty {
output += tailBreak + listing(tail, table)
}
}
return output
}
private static let abbreviations: Set<String> = [
"mr", "mrs", "ms", "dr", "st", "jr", "sr", "prof", "vs", "etc", "inc", "ltd", "approx", "sra", "dra", "ud", "uds",
]
/// Whether `separator` ends a sentence after `word`: ".", "!", "?" or "…" then a space,
/// never after "Dr" or an initial.
private static func endsSentence(_ separator: String, after word: String) -> Bool {
guard let markIndex = separator.firstIndex(where: { ".!?…".contains($0) }),
separator[separator.index(after: markIndex)...].first?.isWhitespace == true else { return false }
if separator[markIndex] == "." && (abbreviations.contains(word) || (word.count == 1 && word.first?.isLetter == true)) {
return false
}
return true
}
/// An item's text: no leading marks, no trailing comma, period, "and" or "or", and a capital
/// first letter (never on "iPhone" or an address).
private static func cleanItem(_ raw: String, _ table: Table) -> String {
var item = String(raw.drop { " \t\n,:.;)-–—".contains($0) })
var previous = ""
while previous != item {
previous = item
item = item.trimmingCharacters(in: .whitespacesAndNewlines)
if !item.hasSuffix("..."), let mark = item.last, ",;:.".contains(mark) {
item.removeLast()
}
item = stripTrailingConnectors(item, table)
}
return capitalizingFirstWord(item)
}
/// `text` without the connectors ("and", "y luego") a next item's marker leaves at its end.
private static func stripTrailingConnectors(_ text: String, _ table: Table) -> String {
var text = text
while let space = text.lastIndex(where: { $0 == " " || $0 == "," }) {
let last = text[text.index(after: space)...].folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)
guard table.connectors.contains(last) || table.alternatives.contains(last) else { break }
text = String(text[..<space]).trimmingCharacters(in: .whitespaces)
while text.last == "," { text.removeLast() }
}
return text
}
private static func capitalizingFirstWord(_ text: String) -> String {
guard let first = text.firstIndex(where: \.isLetter) else { return text }
let word = text[first...].prefix { !$0.isWhitespace }
if word.contains("@") || word.dropFirst().contains(where: \.isUppercase) { return text }
var result = text
result.replaceSubrange(first...first, with: String(text[first]).uppercased())
return result
}
// MARK: Words per language
private struct Table {
/// Phrases that break a line.
let breaks: [([String], String)]
/// Words before a phrase that make it a noun, not a command: "a new line", "the bullet".
let determiners: Set<String>
/// Words after "new line" that make it a noun: "new line of shoes".
let breakFollowers: Set<String>
let connectors: Set<String>
/// "or", stripped from an item's end like a connector.
let alternatives: Set<String>
let ordinals: [String: Int]
/// Ordinal suffixes written after digits: "1st", "2nd".
let digitOrdinalSuffixes: [String]
let ordinalPhrases: [([String], Int)]
/// Words right after an ordinal that keep it prose: "first time", "second guess".
let ordinalFollowers: Set<String>
/// "first of all".
let ofAll: [String]
/// "finally", "lastly"; the flag asks for a comma after ("last, …").
let finals: [([String], Bool)]
let cardinals: [String: Int]
/// "number one", "step one".
let keywords: Set<String>
/// Bullet phrases, longest first; the flag asks for a clause start.
let bullets: [([String], Bool)]
/// Words right after "bullet" that keep it prose: "bullet points", "bullet train".
let bulletFollowers: Set<String>
func ordinal(_ word: String) -> Int? {
if let value = ordinals[word] { return value }
for suffix in digitOrdinalSuffixes where word.hasSuffix(suffix) {
let digits = word.dropLast(suffix.count)
if !digits.isEmpty, digits.count <= 2, digits.allSatisfy(\.isASCII), let value = Int(digits),
(1...20).contains(value) {
return value
}
}
return nil
}
static func forLanguage(_ language: String?) -> Table? {
let code = language.flatMap { Locale(identifier: $0).language.languageCode?.identifier } ?? "en"
switch code {
case "en": return english
case "es": return spanish
default: return nil
}
}
static let english = Table(
breaks: [(["new", "paragraph"], "\n\n"), (["new", "line"], "\n"), (["line", "break"], "\n")],
determiners: [
"a", "an", "the", "this", "that", "these", "those", "my", "your", "his", "her", "its", "our", "their",
"one", "another", "every", "each", "any", "some", "no", "to", "of", "in", "on", "with", "for", "at",
"by", "from", "silver", "magic", "rubber", "plastic", "stray", "whole", "entire",
],
breakFollowers: [
"of", "items", "item", "is", "was", "are", "were", "has", "had", "will", "would", "that", "which",
"for", "from", "cook", "cooks", "worker", "workers", "manager", "managers", "up", "breaks",
],
connectors: ["and", "then", "also", "plus"],
alternatives: ["or"],
ordinals: [
"first": 1, "firstly": 1, "second": 2, "secondly": 2, "third": 3, "thirdly": 3, "fourth": 4,
"fourthly": 4, "fifth": 5, "fifthly": 5, "sixth": 6, "seventh": 7, "eighth": 8, "ninth": 9,
"tenth": 10,
],
digitOrdinalSuffixes: ["st", "nd", "rd", "th"],
ordinalPhrases: [],
ordinalFollowers: [
"time", "times", "place", "thing", "things", "one", "ones", "day", "days", "week", "weeks", "month",
"months", "year", "years", "half", "class", "person", "people", "hand", "floor", "grade", "round",
"prize", "guess", "guessed", "guessing", "nature", "rate", "aid", "base", "cousin", "cousins", "date",
"name", "impression", "choice", "language", "lady", "world", "edition", "gear", "love", "sight",
"glance", "mate", "chance", "try", "attempt", "look", "night", "kiss", "draft", "opinion", "wave",
"quarter", "season", "episode", "chapter", "page", "row", "team", "degree", "letter", "word", "words",
"course", "act", "part", "period", "hour", "minute", "thought", "thoughts", "off", "up", "to", "in",
"on", "at", "and", "or", "is", "was", "came", "come", "served", "last", "of", "string", "fiddle",
"semester", "term", "born", "child", "son", "daughter", "baby", "wife", "husband", "job", "line",
"generation", "step", "steps", "officer", "lieutenant", "amendment", "street", "avenue", "best",
"most", "largest", "biggest",
],
ofAll: ["of", "all"],
finals: [(["last", "but", "not", "least"], false), (["finally"], false), (["lastly"], false), (["last"], true)],
cardinals: [
"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
"ten": 10,
],
keywords: ["number", "step", "item", "point"],
bullets: [
(["bullet", "point"], false), (["next", "bullet"], false), (["next", "item"], false),
(["bullet"], false), (["dash"], true),
],
bulletFollowers: [
"points", "proof", "proofs", "train", "trains", "wound", "wounds", "hole", "holes", "journal",
"journals", "casing", "casings", "shell", "shells", "ant", "ants", "is", "was", "hit", "hits",
"went", "flew", "of", "in", "list", "lists",
]
)
static let spanish = Table(
breaks: [
(["nuevo", "parrafo"], "\n\n"), (["nueva", "linea"], "\n"), (["salto", "de", "linea"], "\n"),
],
determiners: [
"un", "una", "el", "la", "los", "las", "este", "esta", "estos", "estas", "ese", "esa", "eso", "mi",
"mis", "tu", "tus", "su", "sus", "nuestra", "nuestro", "otra", "otro", "cada", "de", "del", "con",
"en", "para", "por", "al", "a",
],
breakFollowers: ["de", "del", "es", "fue", "que", "para", "y"],
connectors: ["y", "e", "luego", "despues", "tambien"],
alternatives: ["o", "u"],
ordinals: [
"primero": 1, "primera": 1, "primeramente": 1, "segundo": 2, "segunda": 2, "tercero": 3,
"tercera": 3, "cuarto": 4, "cuarta": 4, "quinto": 5, "quinta": 5, "sexto": 6, "sexta": 6,
"septimo": 7, "septima": 7, "octavo": 8, "octava": 8, "noveno": 9, "novena": 9, "decimo": 10,
"decima": 10,
],
digitOrdinalSuffixes: ["º", "ª"],
ordinalPhrases: [
(["en", "primer", "lugar"], 1), (["en", "segundo", "lugar"], 2), (["en", "tercer", "lugar"], 3),
(["en", "cuarto", "lugar"], 4), (["en", "quinto", "lugar"], 5),
],
ordinalFollowers: [
"vez", "veces", "lugar", "dia", "dias", "plato", "piso", "mano", "grado", "premio", "parte", "nombre",
"ano", "anos", "mes", "semana", "momento", "paso", "pasos", "hijo", "hija", "ministro", "ministra",
"actor", "plano", "mundo", "tiempo", "ciclo", "curso", "nivel", "puesto", "de", "del", "en", "que",
"es", "fue", "y", "o", "a", "con", "amor", "intento", "capitulo", "temporada", "clase", "fila",
],
ofAll: ["de", "todo"],
finals: [
(["en", "ultimo", "lugar"], false), (["por", "ultimo"], false), (["finalmente"], false),
],
cardinals: [
"uno": 1, "una": 1, "dos": 2, "tres": 3, "cuatro": 4, "cinco": 5, "seis": 6, "siete": 7, "ocho": 8,
"nueve": 9, "diez": 10,
],
keywords: ["numero", "paso"],
bullets: [
(["siguiente", "vineta"], false), (["siguiente", "elemento"], false), (["vineta"], false),
(["guion"], true),
],
bulletFollowers: ["de", "del", "es", "fue", "que"]
)
}
}
+88 -5
View File
@@ -36,14 +36,18 @@ nonisolated enum TranscriptFormatter {
/// English-only rules ("I", Casual's interjections, Notes' connectives); nil is English.
/// - Verbatim: as the speech model wrote it.
/// - Polished: full sentences: fillers trimmed, each sentence capitalized ("I" too) and
/// ended.
/// ended, and English "gonna", "wanna", "gotta", "kinda" and "lemme" written out.
/// - Casual: texting: fillers trimmed, sentences may start lowercase (never an acronym
/// or a name with inner capitals), English "i", no comma after an opening "yeah" or
/// "ok", and no final period on a short message (one line, up to three sentences).
/// - Notes: concise lines: spoken "bullet" and "new line" markers, else several
/// sentences become a list (and a list after a colon becomes bullets), with no
/// opening "so", "yeah" or "and then" and no final periods.
static func format(_ raw: String, style: DictationStyle, language: String? = nil) -> String {
///
/// `lists` (Settings › Dictation › Format lists) writes spoken lists and line breaks as
/// lines (`SpokenLists`) after the fillers and before the style's punctuation, in every
/// style but Verbatim, which keeps the model's exact words.
static func format(_ raw: String, style: DictationStyle, language: String? = nil, lists: Bool = false) -> String {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return "" }
let fillers = fillerPattern(for: language)
@@ -54,19 +58,23 @@ nonisolated enum TranscriptFormatter {
return collapseHorizontalSpaces(in: trimmed)
case .polished:
let cleaned = stripStandaloneFillers(in: trimmed, fillers: fillers)
let cleaned = listed(stripStandaloneFillers(in: trimmed, fillers: fillers), lists, language)
return polishSentences(cleaned, english: english)
case .casual:
let cleaned = stripStandaloneFillers(in: trimmed, fillers: fillers)
let cleaned = listed(stripStandaloneFillers(in: trimmed, fillers: fillers), lists, language)
return casualMessage(cleaned, english: english)
case .notes:
let cleaned = stripStandaloneFillers(in: trimmed, fillers: fillers)
let cleaned = listed(stripStandaloneFillers(in: trimmed, fillers: fillers), lists, language)
return formatNotes(cleaned, english: english)
}
}
private static func listed(_ text: String, _ lists: Bool, _ language: String?) -> String {
lists ? SpokenLists.format(text, language: language) : text
}
/// Joins dictated text cleanly with existing text around the insertion cursor: one space
/// between it and a word before it, and, mid-sentence, a lowercase first word
/// (`continuingSentence`). `isWord` says whether a lowercase word is in the dictation
@@ -183,6 +191,9 @@ nonisolated enum TranscriptFormatter {
private static func polishSentences(_ text: String, english: Bool) -> String {
guard !text.isEmpty else { return "" }
var normalized = fixSpacingBeforePunctuation(in: collapseHorizontalSpaces(in: text))
if english {
normalized = expandingInformalContractions(in: normalized)
}
normalized = capitalizeSentenceStarts(in: normalized)
if english {
normalized = capitalizingPronounI(in: normalized)
@@ -225,6 +236,63 @@ nonisolated enum TranscriptFormatter {
|| (0xF900...0xFAFF).contains(scalar) // compatibility ideographs
}
/// What iOS 27's speech models write for casual speech, and what Polished writes instead.
private static let informalContractions: [String: String] = [
"gonna": "going to", "wanna": "want to", "gotta": "got to", "kinda": "kind of", "lemme": "let me",
]
/// "I'm gonna call" -> "I'm going to call", "Gonna rain." -> "Going to rain.". Never inside
/// quotes (he said “gonna win”) or on a capitalized word mid-sentence, which is a name or
/// a title ("Gonna Fly Now"); a capitalized one starting a sentence keeps its capital.
private static func expandingInformalContractions(in text: String) -> String {
let lowered = text.lowercased()
guard informalContractions.keys.contains(where: lowered.contains) else { return text }
var output = ""
var word = ""
var inStraightQuote = false
var curlyQuotes = 0
func flush() {
defer { word = "" }
let lower = word.lowercased()
guard let expansion = informalContractions[lower], !inStraightQuote, curlyQuotes == 0 else {
output += word
return
}
if word == lower {
output += expansion
} else if word == lower.prefix(1).uppercased() + lower.dropFirst(), startsSentenceOrItem(after: output) {
output += expansion.prefix(1).uppercased() + expansion.dropFirst()
} else {
output += word
}
}
for character in text {
if character.isLetter || character.isNumber || character == "'" || character == "’" {
word.append(character)
continue
}
flush()
if character == "\"" {
inStraightQuote.toggle()
} else if character == "“" {
curlyQuotes += 1
} else if character == "”" {
curlyQuotes = max(0, curlyQuotes - 1)
}
output.append(character)
}
flush()
return output
}
/// Whether the next word starts a sentence, or a bulleted item ("- ").
private static func startsSentenceOrItem(after text: String) -> Bool {
if startsSentence(after: text) { return true }
let line = text.split(separator: "\n", omittingEmptySubsequences: false).last ?? ""
let marker = line.trimmingCharacters(in: .whitespaces)
return marker == "-" || marker == "•"
}
/// English "i", "i'm", "i'll", "i've", "i'd" as "I", "I'm", ...; never "i.e." or an address.
private static func capitalizingPronounI(in text: String) -> String {
recasingPronounI(in: text, from: "i", to: "I")
@@ -290,6 +358,12 @@ nonisolated enum TranscriptFormatter {
var atStart = true
var index = 0
while index < chars.count {
// A list item ("1. Eggs", "- Eggs") keeps its capital.
if index == 0 || chars[index - 1].isNewline, let marker = listMarkerLength(chars, at: index) {
index += marker
atStart = false
continue
}
let ch = chars[index]
if atStart, ch.isLetter {
var end = index
@@ -316,6 +390,15 @@ nonisolated enum TranscriptFormatter {
return String(chars)
}
/// The length of a list marker ("1. ", "- ") at `index`, if one starts there.
private static func listMarkerLength(_ chars: [Character], at index: Int) -> Int? {
if index + 1 < chars.count, chars[index] == "-" || chars[index] == "•", chars[index + 1] == " " { return 2 }
var end = index
while end < chars.count, end - index < 2, chars[end].isASCII, chars[end].isNumber { end += 1 }
guard end > index, end + 1 < chars.count, chars[end] == ".", chars[end + 1] == " " else { return nil }
return end + 2 - index
}
private static func keepsCapital(_ word: String) -> Bool {
if word == "OK" { return false }
let letters = word.filter(\.isLetter)
+18 -1
View File
@@ -128,6 +128,23 @@ doesn't use, and `SpeechAnalyzer` runs without it in the app and the keyboard al
vocabulary included, as desktop's Lowercase step (`str::to_lowercase` on the
final text) does, on every path (`DictationLowercaseSettings`, App Group key
`settings.dictationLowercase`).
- **Format lists (Settings › Dictation › Format lists):** On by default
(`DictationListSettings`, App Group key `settings.dictationFormatLists`), in
English and Spanish, every style but Verbatim (`SpokenLists`, inside the
style after its fillers, so each style ends the lines its own way). "first …
second …" ("1st … 2nd …", "primero … segundo …", "en primer lugar …"),
"number one … number two …" (also "step", "item", "point", "número", "paso")
and "one, … two, …" become `1. …` lines; "bullet", "bullet point", "next
item", "dash" ("viñeta", "guion") said twice or more become `- …` lines; "new
line" and "new paragraph" ("nueva línea", "nuevo párrafo", "salto de línea")
break lines. Text before the list gets its own line (with a colon unless it
ends a sentence), and what follows the last item's sentence its own line.
Guards keep prose: markers count up from one, at least two non-empty items,
each marker at a clause start (the start, after a mark or line break, or
after "and"/"then"/"y"/"luego" that are), a bare number needs its comma, and
words like "the first time", "second guess", "a new line of", "bullet
points" stay as said. `TranscriptCleanupTests` holds the list cases and
62 prose sentences that must not change.
- **Spoken "@" (English, every style but Verbatim):** "at the rate" (India's
name for @) and "at sign" become "@", and an address said around it joins
up: "John at the rate Gmail dot com" becomes "john@gmail.com", "dot" turning
@@ -369,7 +386,7 @@ doesn't use, and `SpeechAnalyzer` runs without it in the app and the keyboard al
5.1.1(i)) and Support open in Safari inside Hex (`HexLinks`, one base URL:
`https://dev.anoma.ly/hex` until the production site serves
`anoma.ly/hex/privacy`). Each row has a one-line description at most. The pages:
- **Dictation:** Style, Lowercase, Dictation language, Translate what I say, Clean up
- **Dictation:** Style, Lowercase, Format lists, Dictation language, Translate what I say, Clean up
what I say, Custom vocabulary (its list below the switch), Keep mic warm,
and Always use iPhone microphone.
- **Keyboard:** Keyboard, **Full** (the default) or **Dictation bar** (stored