shabda 2.0.0

shabda — Grapheme-to-phoneme (G2P) conversion: text to phoneme sequences for vocal synthesis
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Phoneme inventory validation via varna.
//!
//! When the `varna` feature is enabled, this module provides tools to verify
//! that phoneme output from G2P rules is valid for the target language's
//! phoneme inventory as defined by varna.

use alloc::string::String;
use alloc::vec::Vec;
use svara::phoneme::Phoneme;
use varna::phoneme::PhonemeInventory;

use crate::engine::Language;

/// Maps a svara `Phoneme` to its IPA string as used in varna's English inventory.
///
/// Returns `None` for phonemes that have no single-IPA equivalent in varna's
/// current inventory system (e.g., `Silence`), or for phonemes that are valid
/// English sounds but not yet represented in varna 1.0's English inventory
/// (diphthongs `aɪ`, `aʊ`, `ɔɪ` and the NURSE vowel `ɜː`).
///
/// For non-English languages, use [`phoneme_to_ipa_for`] instead.
#[must_use]
pub fn phoneme_to_ipa(phoneme: Phoneme) -> Option<&'static str> {
    match phoneme {
        // Vowels
        Phoneme::VowelA => Some("ɑː"),
        Phoneme::VowelE => Some(""),
        Phoneme::VowelI => Some("ɪ"),
        Phoneme::VowelO => Some(""),
        Phoneme::VowelU => Some(""),
        Phoneme::VowelSchwa => Some("ə"),
        Phoneme::VowelOpenO => Some("ɔː"),
        Phoneme::VowelAsh => Some("æ"),
        Phoneme::VowelNearI => Some("ɪ"),
        Phoneme::VowelNearU => Some("ʊ"),
        Phoneme::VowelOpenA => Some("ɑː"),
        Phoneme::VowelOpenE => Some("ɛ"),
        Phoneme::VowelCupV => Some("ʌ"),
        Phoneme::VowelLongI => Some(""),
        // NURSE vowel (ɜː) — valid English, not yet in varna 1.0 inventory
        Phoneme::VowelBird => None,
        // Diphthongs present in varna's English inventory
        Phoneme::DiphthongEI => Some(""),
        Phoneme::DiphthongOU => Some(""),
        // Diphthongs valid in English but not yet in varna 1.0 inventory
        Phoneme::DiphthongAI => None,
        Phoneme::DiphthongAU => None,
        Phoneme::DiphthongOI => None,
        // Plosives
        Phoneme::PlosiveP => Some("p"),
        Phoneme::PlosiveB => Some("b"),
        Phoneme::PlosiveT => Some("t"),
        Phoneme::PlosiveD => Some("d"),
        Phoneme::PlosiveK => Some("k"),
        Phoneme::PlosiveG => Some("ɡ"),
        // Fricatives
        Phoneme::FricativeF => Some("f"),
        Phoneme::FricativeV => Some("v"),
        Phoneme::FricativeS => Some("s"),
        Phoneme::FricativeZ => Some("z"),
        Phoneme::FricativeSh => Some("ʃ"),
        Phoneme::FricativeZh => Some("ʒ"),
        Phoneme::FricativeTh => Some("θ"),
        Phoneme::FricativeDh => Some("ð"),
        Phoneme::FricativeH => Some("h"),
        // Nasals
        Phoneme::NasalM => Some("m"),
        Phoneme::NasalN => Some("n"),
        Phoneme::NasalNg => Some("ŋ"),
        // Affricates
        Phoneme::AffricateCh => Some("t͡ʃ"),
        Phoneme::AffricateJ => Some("d͡ʒ"),
        // Approximants & lateral
        Phoneme::ApproximantR => Some("ɹ"),
        Phoneme::ApproximantW => Some("w"),
        Phoneme::ApproximantJ => Some("j"),
        Phoneme::LateralL => Some("l"),
        // Not in English inventory
        Phoneme::GlottalStop => Some("ʔ"),
        Phoneme::TapFlap => Some("ɾ"),
        Phoneme::Silence => None,
        _ => None,
    }
}

/// Phonemes that are valid English sounds but not yet in varna 1.0's inventory.
///
/// These are skipped during validation to avoid false positives.
pub const VARNA_INVENTORY_GAPS: &[Phoneme] = &[
    Phoneme::DiphthongAI, // PRICE: aɪ
    Phoneme::DiphthongAU, // MOUTH: aʊ
    Phoneme::DiphthongOI, // CHOICE: ɔɪ
    Phoneme::VowelBird,   // NURSE: ɜː
];

/// Maps a svara `Phoneme` to its IPA string for the given language's inventory.
///
/// Different languages use different IPA symbols for the same svara phoneme.
/// For example, `VowelO` maps to "oʊ" (diphthong) in English but "o" in Spanish.
#[must_use]
pub fn phoneme_to_ipa_for(phoneme: Phoneme, language: Language) -> Option<&'static str> {
    match language {
        Language::English => phoneme_to_ipa(phoneme),
        Language::Spanish => spanish_phoneme_to_ipa(phoneme),
        Language::German => german_phoneme_to_ipa(phoneme),
        Language::Hindi => hindi_phoneme_to_ipa(phoneme),
        Language::Arabic => arabic_phoneme_to_ipa(phoneme),
        Language::Sanskrit => sanskrit_phoneme_to_ipa(phoneme),
    }
}

/// Maps a svara `Phoneme` to its IPA string in varna's Spanish inventory.
fn spanish_phoneme_to_ipa(phoneme: Phoneme) -> Option<&'static str> {
    match phoneme {
        // Spanish vowels (5 pure vowels, no diphthongs in inventory)
        Phoneme::VowelOpenA => Some("a"),
        Phoneme::VowelOpenE => Some("e"),
        Phoneme::VowelNearI => Some("i"),
        Phoneme::VowelO => Some("o"),
        Phoneme::VowelCupV => Some("u"),
        // Plosives
        Phoneme::PlosiveP => Some("p"),
        Phoneme::PlosiveB => Some("b"),
        Phoneme::PlosiveT => Some("t"),
        Phoneme::PlosiveD => Some("d"),
        Phoneme::PlosiveK => Some("k"),
        Phoneme::PlosiveG => Some("ɡ"),
        // Fricatives
        Phoneme::FricativeF => Some("f"),
        Phoneme::FricativeTh => Some("θ"),
        Phoneme::FricativeS => Some("s"),
        Phoneme::FricativeH => Some("x"), // Spanish /x/ (jota)
        // Nasals
        Phoneme::NasalM => Some("m"),
        Phoneme::NasalN => Some("n"),
        Phoneme::NasalNg => Some("ɲ"), // ñ → palatal nasal
        // Liquids & approximants
        Phoneme::LateralL => Some("l"),
        Phoneme::TapFlap => Some("r"),       // Spanish tap
        Phoneme::ApproximantR => Some("rr"), // Spanish trill
        Phoneme::ApproximantJ => Some("j"),
        Phoneme::ApproximantW => Some("w"),
        // Affricate
        Phoneme::AffricateCh => Some("t͡ʃ"),
        // No IPA for these in Spanish
        Phoneme::Silence => None,
        _ => None,
    }
}

/// Maps a svara `Phoneme` to its IPA string in varna's German inventory.
fn german_phoneme_to_ipa(phoneme: Phoneme) -> Option<&'static str> {
    match phoneme {
        // Vowels (short)
        Phoneme::VowelNearI => Some("ɪ"),
        Phoneme::VowelOpenE => Some("ɛ"),
        Phoneme::VowelOpenA => Some("a"),
        Phoneme::VowelSchwa => Some("ə"),
        // Vowels (long)
        Phoneme::VowelE => Some(""),
        Phoneme::VowelO => Some(""),
        Phoneme::VowelU => Some(""),
        Phoneme::VowelAsh => Some(""),
        // Plosives
        Phoneme::PlosiveP => Some("p"),
        Phoneme::PlosiveB => Some("b"),
        Phoneme::PlosiveT => Some("t"),
        Phoneme::PlosiveD => Some("d"),
        Phoneme::PlosiveK => Some("k"),
        Phoneme::PlosiveG => Some("ɡ"),
        // Fricatives
        Phoneme::FricativeF => Some("f"),
        Phoneme::FricativeV => Some("v"),
        Phoneme::FricativeS => Some("s"),
        Phoneme::FricativeZ => Some("z"),
        Phoneme::FricativeSh => Some("ʃ"),
        Phoneme::FricativeH => Some("h"),
        // Nasals
        Phoneme::NasalM => Some("m"),
        Phoneme::NasalN => Some("n"),
        Phoneme::NasalNg => Some("ŋ"),
        // Affricates
        Phoneme::AffricateCh => Some("t͡ʃ"),
        // Approximants & lateral
        Phoneme::ApproximantJ => Some("j"),
        Phoneme::LateralL => Some("l"),
        Phoneme::ApproximantR => Some("ʁ"),
        // Not mapped
        Phoneme::Silence => None,
        _ => None,
    }
}

/// Maps a svara `Phoneme` to its IPA string in varna's Hindi inventory.
fn hindi_phoneme_to_ipa(phoneme: Phoneme) -> Option<&'static str> {
    match phoneme {
        // Vowels
        Phoneme::VowelSchwa => Some("ə"),
        Phoneme::VowelNearI => Some("i"),
        Phoneme::VowelE => Some(""),
        Phoneme::VowelCupV => Some("u"),
        Phoneme::VowelU => Some(""),
        Phoneme::VowelOpenE => Some("e"),
        Phoneme::VowelO => Some("o"),
        Phoneme::VowelOpenA => Some("ɛː"),
        Phoneme::VowelOpenO => Some("ɔː"),
        // Plosives (unaspirated only — svara doesn't have aspirated variants)
        Phoneme::PlosiveP => Some("p"),
        Phoneme::PlosiveB => Some("b"),
        Phoneme::PlosiveT => Some(""),
        Phoneme::PlosiveD => Some(""),
        Phoneme::PlosiveK => Some("k"),
        Phoneme::PlosiveG => Some("ɡ"),
        // Fricatives
        Phoneme::FricativeS => Some("s"),
        Phoneme::FricativeH => Some("ɦ"),
        Phoneme::FricativeF => Some("f"),
        Phoneme::FricativeSh => Some("ɕ"),
        // Nasals
        Phoneme::NasalM => Some("m"),
        Phoneme::NasalN => Some("n"),
        Phoneme::NasalNg => Some("ŋ"),
        // Approximants & lateral
        Phoneme::ApproximantJ => Some("j"),
        Phoneme::LateralL => Some("l"),
        Phoneme::TapFlap => Some("r"),
        Phoneme::FricativeV => Some("ʋ"),
        // Affricates
        Phoneme::AffricateCh => Some("t͡ɕ"),
        Phoneme::AffricateJ => Some("d͡ʑ"),
        // Not mapped
        Phoneme::Silence => None,
        _ => None,
    }
}

/// Maps a svara `Phoneme` to its IPA string in varna's Arabic inventory.
fn arabic_phoneme_to_ipa(phoneme: Phoneme) -> Option<&'static str> {
    match phoneme {
        Phoneme::VowelOpenA => Some("a"),
        Phoneme::VowelNearI => Some("i"),
        Phoneme::VowelCupV => Some("u"),
        Phoneme::PlosiveB => Some("b"),
        Phoneme::PlosiveT => Some("t"),
        Phoneme::PlosiveD => Some("d"),
        Phoneme::PlosiveK => Some("k"),
        Phoneme::PlosiveG => Some("ɣ"),
        Phoneme::FricativeF => Some("f"),
        Phoneme::FricativeTh => Some("θ"),
        Phoneme::FricativeDh => Some("ð"),
        Phoneme::FricativeS => Some("s"),
        Phoneme::FricativeZ => Some("z"),
        Phoneme::FricativeSh => Some("ʃ"),
        Phoneme::FricativeH => Some("h"),
        Phoneme::NasalM => Some("m"),
        Phoneme::NasalN => Some("n"),
        Phoneme::LateralL => Some("l"),
        Phoneme::TapFlap => Some("r"),
        Phoneme::ApproximantW => Some("w"),
        Phoneme::ApproximantJ => Some("j"),
        Phoneme::AffricateJ => Some("d͡ʒ"),
        Phoneme::GlottalStop => Some("ʔ"),
        Phoneme::Silence => None,
        _ => None,
    }
}

/// Maps a svara `Phoneme` to its IPA string in varna's Sanskrit inventory.
fn sanskrit_phoneme_to_ipa(phoneme: Phoneme) -> Option<&'static str> {
    match phoneme {
        // Sanskrit schwa is /ɐ/ not /ə/
        Phoneme::VowelSchwa => Some("ɐ"),
        // Long vowels
        Phoneme::VowelOpenA => Some("ɐː"),
        Phoneme::VowelNearI => Some("i"),
        Phoneme::VowelE => Some(""),
        Phoneme::VowelCupV => Some("u"),
        Phoneme::VowelU => Some(""),
        Phoneme::VowelOpenE => Some(""),
        Phoneme::VowelO => Some(""),
        // Consonants — same as Hindi
        other => hindi_phoneme_to_ipa(other),
    }
}

/// Returns the varna `PhonemeInventory` for the given language.
#[must_use]
pub fn inventory_for(language: Language) -> PhonemeInventory {
    match language {
        Language::English => varna::phoneme::english(),
        Language::Spanish => varna::phoneme::inventories::spanish(),
        Language::German => varna::phoneme::inventories::german(),
        Language::Hindi => varna::phoneme::inventories::hindi(),
        Language::Arabic => varna::phoneme::inventories::classical_arabic(),
        Language::Sanskrit => varna::phoneme::sanskrit(),
    }
}

/// Returns the varna phonotactic constraints for the given language, if available.
///
/// Returns `None` for languages where varna doesn't yet define phonotactics.
#[must_use]
pub fn phonotactics_for(language: Language) -> Option<varna::phoneme::syllable::Phonotactics> {
    match language {
        Language::English => Some(varna::phoneme::syllable::english_phonotactics()),
        Language::Spanish
        | Language::German
        | Language::Hindi
        | Language::Arabic
        | Language::Sanskrit => None, // not yet defined in varna
    }
}

/// Validates a phoneme sequence against phonotactic constraints.
///
/// Checks consecutive consonant pairs in onset and coda positions against
/// the language's phonotactic rules. Returns descriptions of violations found.
/// An empty return means no violations detected.
#[must_use]
pub fn validate_phonotactics(phonemes: &[Phoneme], language: Language) -> Vec<String> {
    let Some(constraints) = phonotactics_for(language) else {
        return Vec::new(); // no constraints available
    };

    let mut violations = Vec::new();

    // Check consecutive consonant sequences against onset constraints
    let mut consonant_run = Vec::new();
    for &ph in phonemes {
        if let Some(ipa) = phoneme_to_ipa(ph) {
            let is_vowel = matches!(
                ph.class(),
                svara::phoneme::PhonemeClass::Vowel | svara::phoneme::PhonemeClass::Diphthong
            ) || ph == Phoneme::Silence;

            if is_vowel {
                // Check if consonant run exceeds max onset
                if consonant_run.len() > constraints.syllable.max_onset as usize {
                    violations.push(alloc::format!(
                        "consonant cluster too long for onset: {}",
                        consonant_run.join("")
                    ));
                }
                consonant_run.clear();
            } else {
                consonant_run.push(String::from(ipa));
            }
        }
    }

    // Check final consonant run against max coda
    if consonant_run.len() > constraints.syllable.max_coda as usize {
        violations.push(alloc::format!(
            "consonant cluster too long for coda: {}",
            consonant_run.join("")
        ));
    }

    violations
}

/// Validates that every phoneme in the slice exists in the given inventory.
///
/// Uses language-aware IPA mapping. Returns a list of phonemes (as IPA strings)
/// that are NOT in the inventory. An empty return means all phonemes are valid.
#[must_use]
pub fn validate_phonemes_for(
    phonemes: &[Phoneme],
    inventory: &PhonemeInventory,
    language: Language,
) -> Vec<String> {
    let mut invalid = Vec::new();
    for &ph in phonemes {
        if let Some(ipa) = phoneme_to_ipa_for(ph, language)
            && !inventory.has(ipa)
        {
            invalid.push(String::from(ipa));
        }
    }
    invalid
}

/// Validates phonemes against the English inventory (backwards-compatible alias).
#[must_use]
pub fn validate_phonemes(phonemes: &[Phoneme], inventory: &PhonemeInventory) -> Vec<String> {
    validate_phonemes_for(phonemes, inventory, Language::English)
}

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

    #[test]
    fn english_rules_produce_valid_phonemes() {
        let inventory = inventory_for(Language::English);
        let test_words = [
            "cat", "dog", "hello", "world", "knight", "write", "nation", "she", "the", "church",
            "think", "sing", "make", "time", "home", "bird", "car", "unhappy", "walked", "wanted",
        ];
        for word in &test_words {
            let phonemes = crate::rules::english_rules(word);
            let invalid = validate_phonemes(&phonemes, &inventory);
            assert!(
                invalid.is_empty(),
                "word {word:?} produced invalid phonemes: {invalid:?}"
            );
        }
    }

    #[test]
    fn mapped_phonemes_exist_in_inventory() {
        // Verify that every phoneme with an IPA mapping exists in varna's English inventory.
        let inventory = inventory_for(Language::English);
        let rule_phonemes = [
            Phoneme::VowelAsh,
            Phoneme::VowelOpenE,
            Phoneme::VowelNearI,
            Phoneme::VowelO,
            Phoneme::VowelCupV,
            Phoneme::VowelSchwa,
            Phoneme::VowelE,
            Phoneme::VowelU,
            Phoneme::VowelOpenA,
            Phoneme::VowelOpenO,
            Phoneme::DiphthongEI,
            Phoneme::DiphthongOU,
            Phoneme::PlosiveP,
            Phoneme::PlosiveB,
            Phoneme::PlosiveT,
            Phoneme::PlosiveD,
            Phoneme::PlosiveK,
            Phoneme::PlosiveG,
            Phoneme::FricativeF,
            Phoneme::FricativeV,
            Phoneme::FricativeS,
            Phoneme::FricativeZ,
            Phoneme::FricativeSh,
            Phoneme::FricativeZh,
            Phoneme::FricativeTh,
            Phoneme::FricativeDh,
            Phoneme::FricativeH,
            Phoneme::NasalM,
            Phoneme::NasalN,
            Phoneme::NasalNg,
            Phoneme::AffricateCh,
            Phoneme::AffricateJ,
            Phoneme::ApproximantR,
            Phoneme::ApproximantW,
            Phoneme::ApproximantJ,
            Phoneme::LateralL,
        ];
        for ph in &rule_phonemes {
            let ipa = phoneme_to_ipa(*ph).expect("phoneme should have IPA mapping");
            assert!(
                inventory.has(ipa),
                "phoneme {ph:?} (IPA: {ipa:?}) not in varna English inventory"
            );
        }
    }

    #[test]
    fn inventory_gaps_are_documented() {
        // These phonemes are valid English but not in varna 1.0 — verify they return None.
        for ph in VARNA_INVENTORY_GAPS {
            assert!(
                phoneme_to_ipa(*ph).is_none(),
                "phoneme {ph:?} is listed as a gap but has an IPA mapping"
            );
        }
    }

    #[test]
    fn silence_is_skipped_in_validation() {
        let inventory = inventory_for(Language::English);
        let phonemes = [Phoneme::Silence];
        let invalid = validate_phonemes(&phonemes, &inventory);
        assert!(invalid.is_empty());
    }

    #[test]
    fn serde_roundtrip_language() {
        // Language already has serde roundtrip tests elsewhere, but validate module
        // uses it — verify the inventory_for path works with deserialized values.
        let lang: Language = serde_json::from_str("\"English\"").unwrap();
        let inv = inventory_for(lang);
        assert!(inv.has("p"));
    }
}