shabdakosh 1.0.0

shabdakosh — Pronunciation dictionary with ARPABET/CMUdict support for svara phonemes
Documentation
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Pronunciation dictionary for common/irregular words.
//!
//! English has many irregular pronunciations (e.g., "one" → /wʌn/, "colonel" → /kɜːnəl/).
//! The dictionary provides known-correct phoneme sequences for these words.
//!
//! The full English dictionary is generated at compile time from `data/cmudict-5k.txt`
//! by the build script. A minimal 28-entry variant is available via [`PronunciationDict::english_minimal`].
//!
//! ## User overlay
//!
//! Application-specific pronunciations can be added via [`PronunciationDict::insert_user`].
//! User entries take precedence over base entries during [`PronunciationDict::lookup`].
//!
//! ## Variant pronunciations
//!
//! Words with multiple pronunciations (heteronyms like "read", "live", "wind") are
//! represented as [`DictEntry`] values containing multiple [`Pronunciation`] variants.
//! Use [`PronunciationDict::lookup_entry`] or [`PronunciationDict::lookup_all`]
//! to access all variants.

pub mod entry;
pub mod format;

use alloc::{collections::BTreeMap, string::String, vec::Vec};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use svara::phoneme::Phoneme;

use entry::{DictEntry, Pronunciation};

// Pull in the generated dictionary function from build.rs output.
include!(concat!(env!("OUT_DIR"), "/generated_dict.rs"));

/// A pronunciation dictionary mapping words to phoneme sequences.
///
/// Supports a two-layer lookup: user entries (overlay) take precedence over
/// base entries. This allows applications to override or extend the built-in
/// dictionary without modifying it.
///
/// Each word maps to a [`DictEntry`] containing one or more [`Pronunciation`]
/// variants with optional frequency and region metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PronunciationDict {
    #[serde(deserialize_with = "deserialize_entries_compat")]
    entries: HashMap<String, DictEntry>,
    #[serde(
        default,
        skip_serializing_if = "BTreeMap::is_empty",
        deserialize_with = "deserialize_user_entries_compat"
    )]
    user_entries: BTreeMap<String, DictEntry>,
}

impl PronunciationDict {
    /// Creates a new empty dictionary.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: HashMap::new(),
            user_entries: BTreeMap::new(),
        }
    }

    /// Creates the built-in English pronunciation dictionary (10,000+ entries).
    ///
    /// Generated at compile time from `data/cmudict-5k.txt`.
    #[must_use]
    pub fn english() -> Self {
        Self {
            entries: generated_english_entries(),
            user_entries: BTreeMap::new(),
        }
    }

    /// Creates a minimal English dictionary with ~29 common function words.
    ///
    /// Useful for testing or memory-constrained environments.
    #[must_use]
    pub fn english_minimal() -> Self {
        let mut dict = Self::new();

        dict.insert("the", &[Phoneme::FricativeDh, Phoneme::VowelSchwa]);
        dict.insert("a", &[Phoneme::VowelSchwa]);
        dict.insert("an", &[Phoneme::VowelSchwa, Phoneme::NasalN]);
        dict.insert("i", &[Phoneme::DiphthongAI]);
        dict.insert("is", &[Phoneme::VowelNearI, Phoneme::FricativeZ]);
        dict.insert(
            "was",
            &[
                Phoneme::ApproximantW,
                Phoneme::VowelOpenO,
                Phoneme::FricativeZ,
            ],
        );
        dict.insert("are", &[Phoneme::VowelOpenA, Phoneme::ApproximantR]);
        dict.insert("to", &[Phoneme::PlosiveT, Phoneme::VowelU]);
        dict.insert("of", &[Phoneme::VowelOpenO, Phoneme::FricativeV]);
        dict.insert("in", &[Phoneme::VowelNearI, Phoneme::NasalN]);
        dict.insert("it", &[Phoneme::VowelNearI, Phoneme::PlosiveT]);
        dict.insert(
            "and",
            &[Phoneme::VowelAsh, Phoneme::NasalN, Phoneme::PlosiveD],
        );
        dict.insert(
            "that",
            &[Phoneme::FricativeDh, Phoneme::VowelAsh, Phoneme::PlosiveT],
        );
        dict.insert(
            "for",
            &[
                Phoneme::FricativeF,
                Phoneme::VowelOpenO,
                Phoneme::ApproximantR,
            ],
        );
        dict.insert("you", &[Phoneme::ApproximantJ, Phoneme::VowelU]);
        dict.insert("he", &[Phoneme::FricativeH, Phoneme::VowelE]);
        dict.insert("she", &[Phoneme::FricativeSh, Phoneme::VowelE]);
        dict.insert("we", &[Phoneme::ApproximantW, Phoneme::VowelE]);
        dict.insert("they", &[Phoneme::FricativeDh, Phoneme::DiphthongEI]);
        dict.insert(
            "this",
            &[
                Phoneme::FricativeDh,
                Phoneme::VowelNearI,
                Phoneme::FricativeS,
            ],
        );
        dict.insert(
            "with",
            &[
                Phoneme::ApproximantW,
                Phoneme::VowelNearI,
                Phoneme::FricativeTh,
            ],
        );
        dict.insert(
            "not",
            &[Phoneme::NasalN, Phoneme::VowelOpenO, Phoneme::PlosiveT],
        );
        dict.insert(
            "but",
            &[Phoneme::PlosiveB, Phoneme::VowelCupV, Phoneme::PlosiveT],
        );
        dict.insert(
            "have",
            &[Phoneme::FricativeH, Phoneme::VowelAsh, Phoneme::FricativeV],
        );
        dict.insert(
            "one",
            &[Phoneme::ApproximantW, Phoneme::VowelCupV, Phoneme::NasalN],
        );
        dict.insert(
            "hello",
            &[
                Phoneme::FricativeH,
                Phoneme::VowelOpenE,
                Phoneme::LateralL,
                Phoneme::DiphthongOU,
            ],
        );
        dict.insert(
            "world",
            &[
                Phoneme::ApproximantW,
                Phoneme::VowelBird,
                Phoneme::LateralL,
                Phoneme::PlosiveD,
            ],
        );
        dict.insert(
            "yes",
            &[
                Phoneme::ApproximantJ,
                Phoneme::VowelOpenE,
                Phoneme::FricativeS,
            ],
        );
        dict.insert("no", &[Phoneme::NasalN, Phoneme::DiphthongOU]);

        dict
    }

    /// Creates a dictionary from a pre-built entries map.
    #[must_use]
    pub fn from_entries(entries: HashMap<String, DictEntry>) -> Self {
        Self {
            entries,
            user_entries: BTreeMap::new(),
        }
    }

    /// Creates a dictionary from a simple map of word -> phonemes.
    ///
    /// Each entry is wrapped into a single-pronunciation [`DictEntry`].
    #[must_use]
    pub fn from_simple_entries(entries: HashMap<String, Vec<Phoneme>>) -> Self {
        let entries = entries
            .into_iter()
            .map(|(word, phonemes)| (word, DictEntry::from_phonemes(&phonemes)))
            .collect();
        Self {
            entries,
            user_entries: BTreeMap::new(),
        }
    }

    /// Inserts a word into the base dictionary with a single pronunciation.
    pub fn insert(&mut self, word: &str, phonemes: &[Phoneme]) {
        self.entries.insert(
            alloc::string::ToString::to_string(&word.to_lowercase()),
            DictEntry::from_phonemes(phonemes),
        );
    }

    /// Inserts a full [`DictEntry`] into the base dictionary.
    pub fn insert_entry(&mut self, word: &str, entry: DictEntry) {
        self.entries.insert(
            alloc::string::ToString::to_string(&word.to_lowercase()),
            entry,
        );
    }

    /// Inserts a word into the user overlay with a single pronunciation.
    ///
    /// User entries take precedence over base entries during lookup.
    pub fn insert_user(&mut self, word: &str, phonemes: &[Phoneme]) {
        self.user_entries.insert(
            alloc::string::ToString::to_string(&word.to_lowercase()),
            DictEntry::from_phonemes(phonemes),
        );
    }

    /// Inserts a full [`DictEntry`] into the user overlay.
    pub fn insert_user_entry(&mut self, word: &str, entry: DictEntry) {
        self.user_entries.insert(
            alloc::string::ToString::to_string(&word.to_lowercase()),
            entry,
        );
    }

    /// Removes a word from the user overlay.
    ///
    /// Returns `true` if the word was present in the user overlay.
    pub fn remove_user(&mut self, word: &str) -> bool {
        self.user_entries
            .remove(&alloc::string::ToString::to_string(&word.to_lowercase()))
            .is_some()
    }

    /// Returns a reference to the user overlay entries.
    #[must_use]
    pub fn user_entries(&self) -> &BTreeMap<String, DictEntry> {
        &self.user_entries
    }

    /// Returns the number of user overlay entries.
    #[must_use]
    pub fn user_len(&self) -> usize {
        self.user_entries.len()
    }

    /// Looks up the primary pronunciation of a word.
    ///
    /// Checks the user overlay first, then the base dictionary.
    /// Returns the phonemes of the highest-frequency pronunciation.
    #[must_use]
    pub fn lookup(&self, word: &str) -> Option<&[Phoneme]> {
        self.lookup_entry(word)
            .map(|entry| entry.primary_phonemes())
    }

    /// Looks up the full dictionary entry for a word.
    ///
    /// Checks the user overlay first, then the base dictionary.
    /// Returns the [`DictEntry`] with all pronunciation variants.
    #[must_use]
    pub fn lookup_entry(&self, word: &str) -> Option<&DictEntry> {
        let key = alloc::string::ToString::to_string(&word.to_lowercase());
        self.user_entries
            .get(&key)
            .or_else(|| self.entries.get(&key))
    }

    /// Looks up all pronunciations of a word.
    ///
    /// Checks the user overlay first, then the base dictionary.
    #[must_use]
    pub fn lookup_all(&self, word: &str) -> Option<&[Pronunciation]> {
        self.lookup_entry(word).map(|entry| entry.all())
    }

    /// Returns the number of base dictionary entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns whether the base dictionary is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns a reference to the base entries.
    #[must_use]
    pub fn entries(&self) -> &HashMap<String, DictEntry> {
        &self.entries
    }

    /// Merges another dictionary into this one.
    ///
    /// For words present in both, entries from `other` replace entries in `self`.
    /// Base and user entries are merged into their respective layers.
    pub fn merge(&mut self, other: &PronunciationDict) {
        for (word, entry) in other.entries() {
            self.entries.insert(word.clone(), entry.clone());
        }
        for (word, entry) in other.user_entries() {
            self.user_entries.insert(word.clone(), entry.clone());
        }
    }

    /// Merges another dictionary, keeping self's entries on conflict.
    ///
    /// Only entries for words not already in `self` are added.
    pub fn merge_conservative(&mut self, other: &PronunciationDict) {
        for (word, entry) in other.entries() {
            if !self.entries.contains_key(word) {
                self.entries.insert(word.clone(), entry.clone());
            }
        }
        for (word, entry) in other.user_entries() {
            if !self.user_entries.contains_key(word) {
                self.user_entries.insert(word.clone(), entry.clone());
            }
        }
    }
}

/// Differences between two pronunciation dictionaries.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct DictDiff {
    /// Words present in `right` but not `left`.
    pub added: Vec<String>,
    /// Words present in `left` but not `right`.
    pub removed: Vec<String>,
    /// Words in both but with different primary pronunciations.
    pub changed: Vec<String>,
}

impl DictDiff {
    /// Returns true if the dictionaries are identical.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
    }

    /// Total number of differences.
    #[must_use]
    pub fn len(&self) -> usize {
        self.added.len() + self.removed.len() + self.changed.len()
    }
}

/// Computes the differences between two dictionaries.
///
/// Compares the effective lookup result for each word (user overlay takes
/// precedence over base, mirroring [`PronunciationDict::lookup_entry`] behavior).
/// Results are sorted alphabetically.
#[must_use]
pub fn diff(left: &PronunciationDict, right: &PronunciationDict) -> DictDiff {
    let mut all_words = alloc::collections::BTreeSet::new();
    for word in left.entries().keys() {
        all_words.insert(word.as_str());
    }
    for word in left.user_entries().keys() {
        all_words.insert(word.as_str());
    }
    for word in right.entries().keys() {
        all_words.insert(word.as_str());
    }
    for word in right.user_entries().keys() {
        all_words.insert(word.as_str());
    }

    let mut result = DictDiff::default();

    for word in all_words {
        let l = left.lookup_entry(word);
        let r = right.lookup_entry(word);
        match (l, r) {
            (None, Some(_)) => result.added.push(alloc::string::ToString::to_string(word)),
            (Some(_), None) => result
                .removed
                .push(alloc::string::ToString::to_string(word)),
            (Some(le), Some(re)) if le != re => {
                result
                    .changed
                    .push(alloc::string::ToString::to_string(word));
            }
            _ => {}
        }
    }

    result
}

impl Default for PronunciationDict {
    fn default() -> Self {
        Self::new()
    }
}

// --- Serde backward compatibility ---
//
// v0.1.0 serialized entries as BTreeMap<String, Vec<Phoneme>>.
// v0.2.0 uses BTreeMap<String, DictEntry>.
// We use an untagged enum to accept either format per map value.

#[derive(Deserialize)]
#[serde(untagged)]
enum EntryCompat {
    New(DictEntry),
    Old(Vec<Phoneme>),
}

impl EntryCompat {
    fn into_entry(self) -> DictEntry {
        match self {
            Self::New(entry) => entry,
            Self::Old(phonemes) => DictEntry::from_phonemes(&phonemes),
        }
    }
}

fn deserialize_entries_compat<'de, D>(
    deserializer: D,
) -> core::result::Result<HashMap<String, DictEntry>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    // Deserialize as BTreeMap first (handles both JSON object key ordering variants)
    let raw: BTreeMap<String, EntryCompat> = BTreeMap::deserialize(deserializer)?;
    Ok(raw.into_iter().map(|(k, v)| (k, v.into_entry())).collect())
}

fn deserialize_user_entries_compat<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, DictEntry>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw: BTreeMap<String, EntryCompat> = BTreeMap::deserialize(deserializer)?;
    Ok(raw.into_iter().map(|(k, v)| (k, v.into_entry())).collect())
}