1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Copyright (c) 2015, 2018, 2020 Brandon Thomas <bt@brand.io>

#![deny(dead_code)]
#![deny(missing_docs)]
#![deny(unreachable_patterns)]
#![deny(unused_extern_crates)]
#![deny(unused_imports)]
#![deny(unused_qualifications)]

//! This crate contains the core types for the **arpabet** crate. This crate is
//! split into sub-crates to aid in compile-time loading of the CMUdict.
//!
//! You shouldn't need to import this crate directly. The **arpabet** crate
//! includes this transitively.
//! ```

#[cfg(test)] #[macro_use] extern crate expectest;

pub mod constants;
pub mod error;
pub mod extensions;
pub mod phoneme;

pub use constants::*;
pub use error::*;
pub use extensions::*;
pub use phoneme::*;
use std::collections::HashMap;
use std::collections::hash_map::Keys;

/// A word is a simple string containing no space characters.
pub type Word = String;

/// A polyphone is several phonemes read in order, typically as a single word.
pub type Polyphone = Vec<Phoneme>;

/// A dictionary that contains mappings of words to polyphones.
#[derive(Default, Clone)]
pub struct Arpabet {
  /// A map of lowercase words to polyphone breakdown.
  /// eg. 'jungle' -> [JH, AH1, NG, G, AH0, L]
  dictionary: HashMap<Word, Polyphone>,
}

impl Arpabet {
  /// Create an empty Arpabet.
  pub fn new() -> Arpabet {
    Self {
      dictionary: HashMap::new(),
    }
  }

  /// Create an Arpabet from a map.
  /// Consumes the map.
  pub fn from_map(map: HashMap<Word, Polyphone>) -> Self {
    Self {
      dictionary: map
    }
  }

  /// Create an Arpabet from a phf::Map.
  /// Used internally for allocation from codegen.
  /// Unfortunately this needs to allocate a new HashMap and copy data over.
  pub fn from_phf_map(map: &phf::Map<&str, &[Phoneme]>) -> Self {
    // TODO: An internal store over an enum of HashMap / phf::Map would be better.
    let mut hashmap = HashMap::with_capacity(map.len());

    for (k, v) in map.into_iter() {
      hashmap.insert(k.to_string(), v.to_vec());
    }

    Self {
      dictionary: hashmap,
    }
  }

  /// Get a polyphone from the dictionary.
  pub fn get_polyphone(&self, word: &str) -> Option<Polyphone> {
    self.dictionary.get(word).and_then(|p| {
      Some(p.iter()
        .map(|p| p.clone())
        .collect::<Vec<Phoneme>>())
    })
  }

  /// Get a polyphone from the dictionary.
  pub fn get_polyphone_ref(&self, word: &str) -> Option<&Polyphone> {
    self.dictionary.get(word)
  }

  /// Get a polyphone from the dictionary.
  pub fn get_polyphone_str(&self, word: &str) -> Option<Vec<&'static str>> {
    self.dictionary.get(word)
      .map(|polyphone| {
        polyphone.iter()
          .map(|phoneme| phoneme.to_str())
          .collect()
      })
  }

  /// Combine two Arpabets and return the result.
  /// Items in the second Arpabet take precedence.
  pub fn combine(&self, other: &Arpabet) -> Arpabet {
    let mut merged = self.dictionary.clone();
    for (k, v) in other.dictionary.iter() {
      merged.insert(k.clone(), v.clone());
    }
    Arpabet { dictionary: merged }
  }

  /// Merge the supplied Arpabet into the current one.
  /// Items in the supplied Arpabet override existing entries
  /// should they already exist.
  pub fn merge_from(&mut self, other: &Arpabet) {
    for (k, v) in other.dictionary.iter() {
      self.dictionary.insert(k.clone(), v.clone());
    }
  }

  /// Insert an entry into the Arpabet. If the entry is already present,
  /// replace it and return the old value.
  pub fn insert(&mut self, key: Word, value: Vec<Phoneme>) -> Option<Vec<Phoneme>> {
    self.dictionary.insert(key, value)
  }

  /// Remove an entry from the arpabet. If it is present, it will be returned.
  pub fn remove(&mut self, key: &str) -> Option<Vec<Phoneme>> {
    self.dictionary.remove(key)
  }

  /// Return a keys iterator that walks the keys in random order.
  pub fn keys(&self) -> Keys<String, Vec<Phoneme>> {
    self.dictionary.keys()
  }

  /// Reports the number of entries in the arpabet.
  pub fn len(&self) -> usize {
    self.dictionary.len()
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  use phoneme::{
    Consonant,
    Vowel,
    VowelStress,
  };

  #[test]
  fn insert() {
    let mut arpa = Arpabet::new();
    arpa.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);

    assert_eq!(arpa.get_polyphone("foo"), Some(vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress))],
    ));

    assert_eq!(arpa.get_polyphone("bar"), None);

    arpa.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);

    assert_eq!(arpa.get_polyphone("foo"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress))],
    ));
  }

  #[test]
  fn remove() {
    let mut arpa = Arpabet::new();
    arpa.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);

    arpa.insert("boo".to_string(), vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);

    assert_eq!(arpa.get_polyphone("foo"), Some(vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress))],
    ));
    assert_eq!(arpa.get_polyphone("boo"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress))],
    ));
    assert_eq!(arpa.len(), 2);

    arpa.remove("boo");
    assert_eq!(arpa.get_polyphone("foo"), Some(vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress))],
    ));
    assert_eq!(arpa.get_polyphone("boo"), None);
    assert_eq!(arpa.len(), 1);

    arpa.remove("foo");
    assert_eq!(arpa.get_polyphone("foo"), None);
    assert_eq!(arpa.get_polyphone("boo"), None);
    assert_eq!(arpa.len(), 0);
  }

  #[test]
  fn size() {
    let mut arpa = Arpabet::new();
    assert_eq!(arpa.len(), 0);

    arpa.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);

    assert_eq!(arpa.len(), 1);

    arpa.insert("boo".to_string(), vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);

    assert_eq!(arpa.len(), 2);

    arpa.remove("boo");
    assert_eq!(arpa.len(), 1);

    arpa.remove("foo");
    assert_eq!(arpa.len(), 0);
  }

  #[test]
  fn keys() {
    let mut arpa = Arpabet::new();
    arpa.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);
    arpa.insert("boo".to_string(), vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);

    let keys: Vec<String> = arpa.keys().cloned().collect();
    assert_eq!(keys.len(), 2);

    // NB: contains is meh, see: https://github.com/rust-lang/rust/issues/42671
    assert!(keys.iter().any(|x| x == "foo"));
    assert!(keys.iter().any(|x| x == "boo"));
  }

  #[test]
  fn get_polyphone() {
    let mut a = Arpabet::new();
    a.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);
    assert_eq!(a.get_polyphone("foo"), Some(vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress))],
    ));
    assert_eq!(a.get_polyphone("bar"), None);
  }

  #[test]
  fn get_polyphone_str() {
    let mut a = Arpabet::new();
    a.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);
    assert_eq!(a.get_polyphone_str("foo"), Some(vec!["F", "UW1"]));
    assert_eq!(a.get_polyphone_str("bar"), None);
  }

  #[test]
  fn get_polyphone_ref() {
    let mut a = Arpabet::new();
    a.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);
    assert_eq!(a.get_polyphone_ref("foo"), Some(&vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress))],
    ));
    assert_eq!(a.get_polyphone_ref("bar"), None);
  }

  #[test]
  fn combine() {
    let a = {
      let mut arpa = Arpabet::new();
      arpa.insert("foo".to_string(), vec![
        Phoneme::Consonant(Consonant::F),
        Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
      ]);
      arpa.insert("bar".to_string(), vec![
        Phoneme::Consonant(Consonant::B),
        Phoneme::Vowel(Vowel::AA(VowelStress::PrimaryStress)),
        Phoneme::Consonant(Consonant::R),
      ]);
      arpa
    };

    let b = {
      let mut arpa = Arpabet::new();
      arpa.insert("foo".to_string(), vec![
        Phoneme::Consonant(Consonant::B),
        Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
      ]);
      arpa.insert("baz".to_string(), vec![
        Phoneme::Consonant(Consonant::B),
        Phoneme::Vowel(Vowel::AE(VowelStress::PrimaryStress)),
        Phoneme::Consonant(Consonant::Z),
      ]);
      arpa
    };

    let c = a.combine(&b);

    assert_eq!(c.get_polyphone("foo"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]));
    assert_eq!(c.get_polyphone("bar"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::AA(VowelStress::PrimaryStress)),
      Phoneme::Consonant(Consonant::R),
    ]));
    assert_eq!(c.get_polyphone("baz"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::AE(VowelStress::PrimaryStress)),
      Phoneme::Consonant(Consonant::Z),
    ]));
    assert_eq!(c.get_polyphone("bin"), None);
  }

  #[test]
  fn merge_from() {
    let mut a = Arpabet::new();
    a.insert("foo".to_string(), vec![
      Phoneme::Consonant(Consonant::F),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]);
    a.insert("bar".to_string(), vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::AA(VowelStress::PrimaryStress)),
      Phoneme::Consonant(Consonant::R),
    ]);

    let b = {
      let mut arpa = Arpabet::new();
      arpa.insert("foo".to_string(), vec![
        Phoneme::Consonant(Consonant::B),
        Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
      ]);
      arpa.insert("baz".to_string(), vec![
        Phoneme::Consonant(Consonant::B),
        Phoneme::Vowel(Vowel::AE(VowelStress::PrimaryStress)),
        Phoneme::Consonant(Consonant::Z),
      ]);
      arpa
    };

    a.merge_from(&b);

    assert_eq!(a.get_polyphone("foo"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::UW(VowelStress::PrimaryStress)),
    ]));
    assert_eq!(a.get_polyphone("bar"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::AA(VowelStress::PrimaryStress)),
      Phoneme::Consonant(Consonant::R),
    ]));
    assert_eq!(a.get_polyphone("baz"), Some(vec![
      Phoneme::Consonant(Consonant::B),
      Phoneme::Vowel(Vowel::AE(VowelStress::PrimaryStress)),
      Phoneme::Consonant(Consonant::Z),
    ]));
    assert_eq!(a.get_polyphone("bin"), None);
  }
}