garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /speech/src/lib.rs

raw

//! Speech: text read aloud, in English or Dutch, for the screen reader.
//!
//! The voice is made the way the first speech machines that people could
//! listen to all day made it (Dennis Klatt's synthesizer of 1980, and the
//! MITalk system around it): not from recordings of a person, which would
//! take megabytes and come from someone else, but from a model of how a
//! voice is made. The vocal folds give a buzz, or the breath a hiss; the
//! throat and mouth shape it with their resonances; the sounds of speech
//! are settings of that model, moved smoothly from one to the next.
//!
//! Reading a text goes in four steps. The text becomes words: numbers are
//! written out, signs named, and punctuation becomes pauses (`text`,
//! `numbers`). Each word becomes the sounds it is said with, from a list
//! of words for those whose spelling misleads and else by spelling rules
//! (`english`, `dutch`, `rules`), each sound written as a symbol
//! (`phonemes`). The sounds get their lengths and the sentence its
//! melody, a rise on each stressed word and a fall at the end, or a rise
//! for a question. And the synthesizer turns all of that into a track of
//! settings every 5 ms, and the track into samples (`synth`).
//!
//! The voice is a man's, a little slower than people talk, every
//! consonant said in full: it is for listening to, often fast, not for
//! sounding human.

#![no_std]

extern crate alloc;

mod dutch;
mod english;
mod math;
mod numbers;
mod phonemes;
mod rules;
mod synth;
mod text;

use alloc::string::String;
use alloc::vec::Vec;

use text::Token;

/// The samples per second [`say`] gives.
pub const SAMPLE_RATE: u32 = 16_000;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Language {
    English,
    Dutch,
}

/// Speaks `text` in `language`: 16-bit mono samples at [`SAMPLE_RATE`].
///
/// Text with nothing to say in it (empty, or only signs and letters of
/// other scripts) gives no samples.
pub fn say(text: &str, language: Language) -> Vec<i16> {
    synth::render(&read(text, language), language)
}

/// The phonemes `text` is read as, written as a string of the crate's
/// phoneme symbols separated by spaces, words by `" | "`, a pause as `P`
/// and a stressed vowel with a `'` before it: for tests and for debugging.
pub fn phonemes(text: &str, language: Language) -> String {
    let mut out = String::new();
    let units = read(text, language);
    let end = units
        .iter()
        .rposition(|u| matches!(u, Unit::Word(_)))
        .map_or(0, |i| i + 1);
    for (i, unit) in units[..end].iter().enumerate() {
        if i > 0 {
            out.push_str(" | ");
        }
        match unit {
            Unit::Word(sounds) => phonemes::write(sounds, &mut out),
            Unit::Break(_) => out.push('P'),
        }
    }
    out
}

/// One sound of a word: which, and whether it carries the word's stress.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Sound {
    phoneme: u8,
    stressed: bool,
}

/// How a stretch of speech ends.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Break {
    /// A short pause, the voice held up: more is coming.
    Comma,
    /// The end of a sentence, the voice falling.
    Stop,
    /// The end of a question, the voice rising.
    Question,
}

impl Break {
    /// The stronger of two breaks that meet, as ", ." or "?!" do.
    fn stronger(self, other: Break) -> Break {
        match (self, other) {
            (Break::Question, _) | (_, Break::Question) => Break::Question,
            (Break::Stop, _) | (_, Break::Stop) => Break::Stop,
            _ => Break::Comma,
        }
    }
}

/// A word's sounds, or a break between words.
#[derive(Clone, PartialEq, Eq, Debug)]
enum Unit {
    Word(Vec<Sound>),
    Break(Break),
}

/// `text` as the words and breaks it is said with. A break never starts the
/// list and two never follow each other.
fn read(text: &str, language: Language) -> Vec<Unit> {
    let mut out = Vec::new();
    for token in text::tokens(text, language) {
        match token {
            Token::Word(w) => read_word(&w, false, language, &mut out),
            Token::Number(w) => read_word(&w, true, language, &mut out),
            Token::Break(b) => match out.last_mut() {
                Some(Unit::Word(_)) => out.push(Unit::Break(b)),
                Some(Unit::Break(last)) => *last = last.stronger(b),
                None => {}
            },
        }
    }
    out
}

/// The sounds of one word, pushed as one or more units: a word with a
/// hyphen not in the lists is said as its parts, and one with no vowel in
/// it ("bt", "pdf") is spelled.
fn read_word(word: &str, number: bool, language: Language, out: &mut Vec<Unit>) {
    if let Some(sounds) = lookup(word, number, language) {
        return push_word(out, sounds);
    }
    if word.contains('-') {
        for part in word.split('-').filter(|p| !p.is_empty()) {
            read_word(part, number, language, out);
        }
        return;
    }
    let letters: String = word.chars().filter(char::is_ascii_lowercase).collect();
    if letters.is_empty() {
        return;
    }
    // "user's" may be listed as "users".
    let without_marks = if letters != word {
        lookup(&letters, number, language)
    } else {
        None
    };
    if let Some(sounds) = without_marks {
        return push_word(out, sounds);
    }
    if letters.len() == 1 || !letters.bytes().any(|b| b"aeiouy".contains(&b)) {
        for c in letters.bytes() {
            let sounds = match language {
                Language::English => english::letter(c),
                Language::Dutch => dutch::letter(c),
            };
            push_word(out, sounds);
        }
        return;
    }
    let sounds = match language {
        Language::English => english::by_rule(&letters),
        Language::Dutch => dutch::by_rule(&letters),
    };
    push_word(out, sounds);
}

fn lookup(word: &str, number: bool, language: Language) -> Option<Vec<Sound>> {
    match language {
        Language::English => english::lookup(word),
        Language::Dutch => {
            let as_number = if number { dutch::number(word) } else { None };
            as_number.or_else(|| dutch::lookup(word))
        }
    }
}

fn push_word(out: &mut Vec<Unit>, sounds: Vec<Sound>) {
    if !sounds.is_empty() {
        out.push(Unit::Word(sounds));
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use Language::{Dutch, English};
    use std::string::ToString;

    #[test]
    fn phonemes_of_phrases() {
        assert_eq!(phonemes("screen reader", English), "s k r 'i n | r 'i d 3");
        assert_eq!(phonemes("Settings", English), "s 'E t I N z");
        assert_eq!(phonemes("the button", English), "D @ | b 'V t @ n");
        assert_eq!(phonemes("On, off.", English), "'A n | P | 'O f");
        assert_eq!(phonemes("21", English), "t w 'E n t i | w 'V n");
        assert_eq!(phonemes("Wi-Fi", English), "w 'aI f aI");
        assert_eq!(phonemes("BT", English), "b 'i | t 'i");
        assert_eq!(
            phonemes("schermlezer aan", Dutch),
            "s x 'E r m l e: z @ r | 'a: n"
        );
        assert_eq!(phonemes("Taal: uit", Dutch), "t 'a: l | P | '9y t");
        assert_eq!(phonemes("Instellingen", Dutch), "'I n s t E l I N @ n");
        assert_eq!(phonemes("21", Dutch), "'e: n @ n t w I n t @ x");
        assert_eq!(phonemes("een", Dutch), "@ n");
        assert_eq!(phonemes("1", Dutch), "'e: n");
    }

    #[test]
    fn breaks_collapse_and_never_lead() {
        assert_eq!(phonemes("... yes?!", English), "j 'E s");
        let units = read("yes, . no", English);
        assert_eq!(units.len(), 3);
        assert_eq!(units[1], Unit::Break(Break::Stop));
    }

    #[test]
    fn odd_text_reads_as_nothing_or_something() {
        for text in [
            "",
            "!!!",
            "🙂🙂",
            "日本語",
            "مرحبا",
            "\u{0}\u{7f}\u{feff}",
            "---",
            "''",
            "@#%&",
        ] {
            let _ = phonemes(text, English);
            let _ = phonemes(text, Dutch);
        }
        assert_eq!(phonemes("", English), "");
        assert_eq!(phonemes("!!!", Dutch), "");
        let long = "Settings, accessibility. ".repeat(400);
        assert!(phonemes(&long, English).len() > 1000);
        let one_long_word = "ab".repeat(3000);
        assert!(!phonemes(&one_long_word, Dutch).is_empty());
        assert!(!phonemes(&"9".repeat(40), English).is_empty());
        assert!(phonemes(&u32::MAX.to_string(), Dutch).contains("n 'e: G @ n"));
    }
}