Cotton code
163 lines · 8.1 KB · SwiftRaw
// Phonetic spellings for the names in the person's dictation language model// (`VoiceModel.swift`), generated from the name's own letters by rule: no// network, no model, the same answer for the same name on every device.//// WHY. The system spells an unknown word by its English letter-to-sound rules,// and an Indian name read by those rules is not the name: "Anvika" heard as// "and Vika", "Sarnaik" as "Sara Nayaka". A romanized Indic name follows the// romanization's own conventions — a final "a" is long, an inner "a" is the// short schwa, "bh"/"dh"/"kh" are aspirated, "v" is the soft labiodental — so a// name that READS as romanized Indic is spelled by those rules, in the// phonemes the locale's recogniser accepts (X-SAMPA, from// `SFCustomLanguageModelData.supportedPhonemes`). A name that does not read so// (Saoirse, Niamh, Aldeburgh) gets NO spelling: the system's own rules know// English and Irish spellings better than a rule written for Indic ones, and a// wrong spelling is worse than none.//// Where the romanization is ambiguous the speller answers every reading// (a final "e" said or silent — "Bhonsle" vs "Rathore"); the recogniser takes// a word's pronunciations as alternatives.import Foundationpublic enum NamePhonetics {    /// One phoneme sequence per reading, each a space-separated X-SAMPA string    /// in the Indian English set; empty when the word does not read as    /// romanized Indic.    public static func indic(_ word: String) -> [String] {        let letters = Array(word.lowercased().folding(options: .diacriticInsensitive, locale: nil))        guard letters.count >= 2, letters.allSatisfy({ $0 >= "a" && $0 <= "z" }), readsIndic(letters) else { return [] }        var readings: [[String]] = [[]]        var i = 0        func spell(_ phones: [String]) { readings = readings.map { $0 + phones } }        while i < letters.count {            let rest = letters[i...]            let next: Character? = i + 1 < letters.count ? letters[i + 1] : nil            let atEnd = { (n: Int) in i + n == letters.count }            // "y" before a vowel is the glide ("Yash", "Priyanka"); anywhere            // else it is the vowel ("Sanjay" ends on it).            if letters[i] == "y", let next, isVowelLetter(next) {                spell(["j"])                i += 1                continue            }            if let (taken, phones) = consonant(rest) {                // A doubled consonant is one, held: "Siddhant", "Batliwala".                if let last = readings.first?.last, last == phones.last, !isVowel(last) {                    i += taken                    continue                }                // "n" before a velar is the velar nasal: "Ranga", "Ankit".                if phones == ["n"], let next, "kg".contains(next) {                    spell(["N"])                } else {                    spell(phones)                }                i += taken                continue            }            // Vowels, longest spelling first.            let two = next.map { String([letters[i], $0]) } ?? ""            switch two {            case "aa": spell(["a:"]); i += 2; continue            case "ee", "ii": spell(["i"]); i += 2; continue            case "oo", "uu": spell(["u"]); i += 2; continue            case "ai": spell([atEnd(2) ? "aI" : "E"]); i += 2; continue            case "au": spell(["O"]); i += 2; continue            case "ei", "ey": spell(["eI"]); i += 2; continue            case "ay" where atEnd(2): spell(["eI"]); i += 2; continue            default: break            }            switch letters[i] {            case "a": spell([atEnd(1) ? "a:" : "V"])            case "i": spell([atEnd(1) ? "i" : "I"])            case "u": spell([atEnd(1) ? "u" : "U"])            case "o": spell(["o"])            case "e":                if atEnd(1), letters.count > 4, letters[..<i].filter(isVowelLetter).count >= 2 {                    // A final "e" after a consonant: silent in an anglicized                    // spelling ("Rathore"), said in a transliterated one                    // ("Bhonsle"). Both readings go.                    readings = readings.flatMap { [$0 + ["e"], $0] }                } else {                    spell(["e"])                }            case "y": spell(["i"])            default: return []            }            i += 1        }        return readings.prefix(4).map { stressed($0).joined(separator: " ") }    }    /// The readings of a name of several words, word by word — the grapheme    /// the recogniser is taught is one word.    public static func words(of name: String) -> [(grapheme: String, readings: [String])] {        name.split(whereSeparator: { $0 == " " || $0 == "-" }).compactMap { part in            let word = String(part)            let readings = indic(word)            return readings.isEmpty ? nil : (word, readings)        }    }    // MARK: - Rules    /// The consonant spelled at the head of `rest`, longest first, and how many    /// letters it took.    private static func consonant(_ rest: ArraySlice<Character>) -> (Int, [String])? {        let s = String(rest.prefix(3))        for (spelling, phones) in clusters where s.hasPrefix(spelling) {            return (spelling.count, phones)        }        return nil    }    private static let clusters: [(String, [String])] = [        ("chh", ["tS_h"]), ("sh", ["S"]), ("ch", ["tS"]), ("kh", ["k_h"]), ("gh", ["g_h"]),        ("jh", ["dZ_h"]), ("th", ["t_h"]), ("dh", ["d_h"]), ("ph", ["p_h"]), ("bh", ["b_h"]),        ("zh", ["Z"]), ("ks", ["k", "s"]),        ("b", ["b"]), ("c", ["k"]), ("d", ["d"]), ("f", ["f"]), ("g", ["g"]), ("h", ["h"]),        ("j", ["dZ"]), ("k", ["k"]), ("l", ["l"]), ("m", ["m"]), ("n", ["n"]), ("p", ["p"]),        ("q", ["k"]), ("r", ["r"]), ("s", ["s"]), ("t", ["t"]), ("v", ["v\\"]), ("w", ["v\\"]),        ("x", ["k", "s"]), ("z", ["z"]),    ]    private static func isVowelLetter(_ c: Character) -> Bool { "aeiou".contains(c) }    private static func isVowel(_ phone: String) -> Bool {        ["a:", "V", "i", "I", "u", "U", "o", "e", "E", "O", "aI", "eI"].contains(phone)    }    /// Primary stress on the first long vowel, else the first vowel — Indic    /// stress falls on the first heavy syllable, and an unstressed spelling    /// is not one the recogniser accepts for a name.    private static func stressed(_ phones: [String]) -> [String] {        let long: Set<String> = ["a:", "i", "u", "o", "e", "E", "O", "aI", "eI"]        guard let at = phones.firstIndex(where: long.contains) ?? phones.firstIndex(where: isVowel) else { return phones }        var out = phones        out[at] = "\"" + out[at]        return out    }    /// Whether the letters read as romanized Indic: syllables of consonant(s)    /// and vowel, no vowel pair or consonant cluster that Indic romanization    /// does not write. Conservative on purpose — a name that fails gets the    /// system's own spelling, which is never worse than a wrong one.    static func readsIndic(_ letters: [Character]) -> Bool {        let word = String(letters)        let foreign = ["ao", "oi", "ea", "eo", "eu", "ie", "ue", "ui", "oa", "ae", "oe", "ou",                       "mh", "ck", "tz", "sch", "gh$", "ff", "ss$", "ll$", "rr", "wr", "kn", "ght",                       "dg", "tch", "cq", "c[^h]", "c$", "x", "w$", "uh", "[^aeiou]y[^aeiou]"]        for pattern in foreign where word.range(of: pattern, options: .regularExpression) != nil {            return false        }        // At most two consonant letters in a row, an aspirate's "h" not counted        // ("Siddhant" is d-dh, "Lakshmi" is k-sh-m), and never three at the end.        let collapsed = word.replacingOccurrences(of: "([bcdgjkpstz])h", with: "$1", options: .regularExpression)        if collapsed.range(of: "[^aeiouy]{4,}", options: .regularExpression) != nil { return false }        if collapsed.range(of: "[^aeiouy]{3}$", options: .regularExpression) != nil { return false }        if collapsed.range(of: "^[^aeiouy]{3}", options: .regularExpression) != nil,            !["shr", "str", "skr", "spr"].contains(where: word.hasPrefix) { return false }        return letters.contains(where: isVowelLetter)    }}