speechmarkdown-rust 0.2.0

High-performance SpeechMarkdown parser with multi-language bindings
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
use crate::ast::{AstNode, NodeType};
use crate::capabilities::PlatformCapabilities;
use crate::error::Result;
use crate::formatters::base::{FormatterOptions, Platform};
use crate::formatters::{create_formatter, Formatter, TextFormatter};
use crate::ssml_to_smd;

pub struct SpeechMarkdownParser;

impl SpeechMarkdownParser {
    /// Parse SpeechMarkdown text into an AST
    pub fn parse(input: &str) -> Result<AstNode> {
        Self::parse_simple(input)
    }

    /// Convert SpeechMarkdown to plain text
    pub fn to_text(input: &str) -> Result<String> {
        let ast = Self::parse(input)?;
        let formatter = TextFormatter::new();
        formatter.format(&ast)
    }

    /// Convert SpeechMarkdown to SSML for the specified platform
    pub fn to_ssml(input: &str, platform: Platform) -> Result<String> {
        let ast = Self::parse(input)?;
        let options = FormatterOptions {
            platform,
            ..Default::default()
        };
        let formatter = create_formatter(platform, options);
        formatter.format(&ast)
    }

    /// Convert SSML to SpeechMarkdown (best-effort, lossy for unsupported elements)
    pub fn to_smd(ssml: &str) -> Result<String> {
        ssml_to_smd::ssml_to_smd(ssml)
    }

    /// Get supported SSML elements for a platform
    pub fn supported_ssml(platform: Platform) -> PlatformCapabilities {
        crate::capabilities::get_supported_ssml(platform)
    }

    /// Check if a string contains SpeechMarkdown syntax
    pub fn is_speech_markdown(input: &str) -> bool {
        if let Ok(ast) = Self::parse(input) {
            ast.children.iter().any(|child| {
                !matches!(
                    child.node_type,
                    NodeType::Document | NodeType::PlainText | NodeType::EmptyLine
                )
            })
        } else {
            false
        }
    }

    /// Validate SpeechMarkdown input, returning an error message if invalid
    pub fn validate(input: &str) -> Result<()> {
        Self::parse(input)?;
        Ok(())
    }

    /// Simple manual parser for basic SpeechMarkdown syntax
    fn parse_simple(input: &str) -> Result<AstNode> {
        let mut document = AstNode::document();
        let mut current_text = String::new();
        let mut chars = input.chars().peekable();

        let flush_text = |doc: &mut AstNode, text: &mut String| {
            if !text.is_empty() {
                let node = AstNode::text(text.clone());
                text.clear();
                doc.children.push(node);
            }
        };

        while let Some(c) = chars.next() {
            match c {
                '#' if chars.peek() == Some(&'[') => {
                    flush_text(&mut document, &mut current_text);
                    chars.next();
                    let (section_content, found) = Self::read_until(&mut chars, ']');
                    if found {
                        let mut node = AstNode::new(NodeType::Section, section_content.clone());
                        for modifier in section_content.split(';') {
                            if let Some((key, value)) = modifier.split_once(':') {
                                node = node
                                    .with_attribute(key.trim(), Self::strip_quotes(value.trim()));
                            } else {
                                node = node.with_attribute("style", modifier.trim());
                            }
                        }
                        document = document.add_child(node);
                    } else {
                        current_text.push('#');
                        current_text.push('[');
                        current_text.push_str(&section_content);
                    }
                }
                '[' => {
                    flush_text(&mut document, &mut current_text);
                    let (bracket_content, found) = Self::read_until(&mut chars, ']');
                    if found {
                        if let Some(rest) = bracket_content.strip_prefix("break:") {
                            let break_value = Self::strip_quotes(rest.trim());
                            if Self::is_time_break(break_value) {
                                document = document.add_child(AstNode::new(
                                    NodeType::ShortBreak,
                                    format!("[{}]", break_value),
                                ));
                            } else {
                                let mut node =
                                    AstNode::new(NodeType::Break, break_value.to_string());
                                node = node.with_attribute("strength", break_value);
                                document = document.add_child(node);
                            }
                        } else if let Some(rest) = bracket_content.strip_prefix("mark:") {
                            let mark_value = Self::strip_quotes(rest.trim());
                            document = document
                                .add_child(AstNode::new(NodeType::Mark, mark_value.to_string()));
                        } else if Self::is_time_break(&bracket_content) {
                            document = document.add_child(AstNode::new(
                                NodeType::ShortBreak,
                                format!("[{}]", bracket_content),
                            ));
                        } else {
                            current_text.push('[');
                            current_text.push_str(&bracket_content);
                            current_text.push(']');
                        }
                    } else {
                        current_text.push('[');
                        current_text.push_str(&bracket_content);
                    }
                }
                '~' => {
                    let prev_is_boundary = current_text.is_empty()
                        || current_text.ends_with(|c: char| c.is_whitespace());
                    if !prev_is_boundary {
                        current_text.push('~');
                    } else {
                        flush_text(&mut document, &mut current_text);
                        let mut emphasized_text = String::new();
                        let mut found_end = false;
                        while let Some(&next_c) = chars.peek() {
                            chars.next();
                            if next_c == '~' {
                                found_end = true;
                                break;
                            }
                            emphasized_text.push(next_c);
                        }
                        if found_end
                            && !emphasized_text.is_empty()
                            && !emphasized_text.contains(' ')
                        {
                            document = document.add_child(AstNode::new(
                                NodeType::ShortEmphasisNone,
                                emphasized_text,
                            ));
                        } else {
                            current_text.push('~');
                            current_text.push_str(&emphasized_text);
                            if found_end {
                                current_text.push('~');
                            }
                        }
                    }
                }
                '-' => {
                    let prev_is_boundary = current_text.is_empty()
                        || current_text.ends_with(|c: char| c.is_whitespace());
                    if !prev_is_boundary {
                        current_text.push('-');
                    } else {
                        flush_text(&mut document, &mut current_text);
                        let mut emphasized_text = String::new();
                        let mut found_end = false;
                        while let Some(&next_c) = chars.peek() {
                            chars.next();
                            if next_c == '\n' || next_c == '\r' {
                                emphasized_text.push(next_c);
                                break;
                            }
                            if next_c == '-' {
                                let next_is_boundary =
                                    chars.peek().is_none_or(|c| c.is_whitespace());
                                if next_is_boundary {
                                    found_end = true;
                                    break;
                                } else {
                                    emphasized_text.push('-');
                                }
                            } else {
                                emphasized_text.push(next_c);
                            }
                        }
                        if found_end
                            && !emphasized_text.is_empty()
                            && !emphasized_text.contains(' ')
                        {
                            document = document.add_child(AstNode::new(
                                NodeType::ShortEmphasisReduced,
                                emphasized_text,
                            ));
                        } else {
                            current_text.push('-');
                            current_text.push_str(&emphasized_text);
                            if found_end {
                                current_text.push('-');
                            }
                        }
                    }
                }
                '+' => {
                    flush_text(&mut document, &mut current_text);
                    let mut plus_count = 1;
                    while chars.peek() == Some(&'+') {
                        chars.next();
                        plus_count += 1;
                    }
                    let mut emphasized_text = String::new();
                    let mut found_end = false;
                    while let Some(&next_c) = chars.peek() {
                        if next_c == '+' {
                            let mut closing_pluses = 0;
                            while chars.peek() == Some(&'+') {
                                chars.next();
                                closing_pluses += 1;
                            }
                            if closing_pluses == plus_count {
                                found_end = true;
                                break;
                            } else {
                                for _ in 0..closing_pluses {
                                    emphasized_text.push('+');
                                }
                            }
                        } else {
                            chars.next();
                            emphasized_text.push(next_c);
                        }
                    }
                    if found_end {
                        let node_type = if plus_count >= 2 {
                            NodeType::ShortEmphasisStrong
                        } else {
                            NodeType::ShortEmphasisModerate
                        };
                        document = document.add_child(AstNode::new(node_type, emphasized_text));
                    } else {
                        for _ in 0..plus_count {
                            current_text.push('+');
                        }
                        current_text.push_str(&emphasized_text);
                    }
                }
                '(' => {
                    flush_text(&mut document, &mut current_text);
                    let mut modifier_content = String::new();
                    let mut found_closing_paren = false;
                    while let Some(&next_c) = chars.peek() {
                        chars.next();
                        if next_c == ')' {
                            found_closing_paren = true;
                            break;
                        }
                        modifier_content.push(next_c);
                    }

                    if found_closing_paren {
                        if chars.peek() == Some(&'[') {
                            chars.next();
                            let (modifiers, found_bracket) = Self::read_until(&mut chars, ']');
                            if found_bracket {
                                let mut node =
                                    AstNode::new(NodeType::TextModifier, modifier_content);
                                for modifier in modifiers.split(';') {
                                    if let Some((key, value)) = modifier.split_once(':') {
                                        node = node.with_attribute(
                                            key.trim(),
                                            Self::strip_quotes(value.trim()),
                                        );
                                    } else {
                                        let key = modifier.trim();
                                        if !key.is_empty() {
                                            node = node.with_attribute(key, "");
                                        }
                                    }
                                }
                                document = document.add_child(node);
                            } else {
                                current_text.push('(');
                                current_text.push_str(&modifier_content);
                                current_text.push(')');
                                current_text.push('[');
                                current_text.push_str(&modifiers);
                            }
                        } else if chars.peek() == Some(&'{') {
                            chars.next();
                            let (alias_text, found_brace) = Self::read_until(&mut chars, '}');
                            if found_brace {
                                let mut node = AstNode::new(NodeType::ShortSub, modifier_content);
                                if !alias_text.is_empty() {
                                    node = node.with_attribute("alias", alias_text);
                                }
                                document = document.add_child(node);
                            } else {
                                current_text.push('(');
                                current_text.push_str(&modifier_content);
                                current_text.push(')');
                                current_text.push('{');
                                current_text.push_str(&alias_text);
                            }
                        } else if chars.peek() == Some(&'/') {
                            chars.next();
                            let mut phoneme = String::new();
                            let mut found_slash = false;
                            while let Some(&next_c) = chars.peek() {
                                chars.next();
                                if next_c == '/' {
                                    found_slash = true;
                                    break;
                                }
                                phoneme.push(next_c);
                            }
                            if found_slash {
                                let mut node = AstNode::new(NodeType::ShortIpa, modifier_content);
                                node = node.with_attribute("phoneme", phoneme);
                                document = document.add_child(node);
                            } else {
                                current_text.push('(');
                                current_text.push_str(&modifier_content);
                                current_text.push(')');
                                current_text.push('/');
                                current_text.push_str(&phoneme);
                            }
                        } else {
                            current_text.push('(');
                            current_text.push_str(&modifier_content);
                            current_text.push(')');
                        }
                    } else {
                        current_text.push('(');
                        current_text.push_str(&modifier_content);
                    }
                }
                '/' => {
                    flush_text(&mut document, &mut current_text);
                    let mut ipa_content = String::new();
                    let mut found_slash = false;
                    while let Some(&next_c) = chars.peek() {
                        if next_c == '/' {
                            chars.next();
                            found_slash = true;
                            break;
                        }
                        if next_c == ' ' || next_c == '\n' || next_c == '\r' || next_c == '\t' {
                            break;
                        }
                        chars.next();
                        ipa_content.push(next_c);
                    }
                    if found_slash && !ipa_content.is_empty() {
                        let mut node = AstNode::new(NodeType::BareIpa, "ipa".to_string());
                        node = node.with_attribute("alphabet", "ipa");
                        node = node.with_attribute("ph", ipa_content.trim().to_string());
                        document = document.add_child(node);
                    } else if found_slash {
                        current_text.push('/');
                        current_text.push('/');
                    } else {
                        current_text.push('/');
                        current_text.push_str(&ipa_content);
                    }
                }
                '{' => {
                    flush_text(&mut document, &mut current_text);
                    let (sub_text, found_brace) = Self::read_until(&mut chars, '}');
                    if found_brace && !sub_text.is_empty() {
                        let mut alias_text = String::new();
                        while let Some(&next_c) = chars.peek() {
                            if next_c.is_whitespace()
                                || next_c == '('
                                || next_c == '['
                                || next_c == '+'
                                || next_c == '~'
                                || next_c == '!'
                                || next_c == '/'
                                || next_c == '{'
                                || next_c == '}'
                                || next_c == '#'
                            {
                                break;
                            }
                            chars.next();
                            alias_text.push(next_c);
                        }
                        let mut node = AstNode::new(NodeType::ShortSub, sub_text);
                        if !alias_text.is_empty() {
                            node = node.with_attribute("alias", alias_text);
                        }
                        document = document.add_child(node);
                    } else {
                        current_text.push('{');
                        current_text.push_str(&sub_text);
                    }
                }
                '!' => {
                    if chars.peek() == Some(&'[') {
                        flush_text(&mut document, &mut current_text);
                        chars.next();
                        let (caption, found_caption_end) = Self::read_until(&mut chars, ']');

                        if found_caption_end && chars.peek() == Some(&'(') {
                            chars.next();
                            let (url, found_url_end) = Self::read_until(&mut chars, ')');
                            if found_url_end {
                                let mut node = AstNode::new(NodeType::Audio, caption);
                                node = node.with_attribute("src", Self::strip_quotes(&url));
                                document = document.add_child(node);
                            } else {
                                current_text.push_str(&format!("![{}]", caption));
                            }
                        } else if found_caption_end && chars.peek() == Some(&'[') {
                            chars.next();
                            let (url, found_url_end) = Self::read_until(&mut chars, ']');
                            if found_url_end {
                                let mut node = AstNode::new(NodeType::Audio, caption);
                                node = node.with_attribute("src", Self::strip_quotes(&url));
                                document = document.add_child(node);
                            } else {
                                current_text.push_str(&format!("![{}]", caption));
                            }
                        } else if found_caption_end {
                            let possible_url = Self::strip_quotes(&caption);
                            if possible_url.starts_with("http://")
                                || possible_url.starts_with("https://")
                                || possible_url.starts_with("soundbank://")
                                || possible_url.contains("://")
                                || possible_url.contains('.')
                            {
                                let mut node = AstNode::new(NodeType::Audio, String::new());
                                node = node.with_attribute("src", possible_url);
                                document = document.add_child(node);
                            } else {
                                current_text.push_str(&format!("![{}]", caption));
                            }
                        } else {
                            current_text.push_str(&format!("![{}", caption));
                        }
                    } else if chars.peek() == Some(&'(') {
                        flush_text(&mut document, &mut current_text);
                        chars.next();
                        let (caption, found_caption_end) = Self::read_until(&mut chars, ')');
                        if found_caption_end && chars.peek() == Some(&'[') {
                            chars.next();
                            let (url, found_url_end) = Self::read_until(&mut chars, ']');
                            if found_url_end {
                                let mut node = AstNode::new(NodeType::Audio, caption);
                                node = node.with_attribute("src", Self::strip_quotes(&url));
                                document = document.add_child(node);
                            } else {
                                current_text.push_str(&format!("!({}[", caption));
                            }
                        } else {
                            current_text.push_str(&format!("!({}", caption));
                        }
                    } else {
                        current_text.push('!');
                    }
                }
                _ => {
                    current_text.push(c);
                }
            }
        }

        if !current_text.is_empty() {
            document = document.add_child(AstNode::text(current_text));
        }

        Ok(document)
    }

    fn strip_quotes(s: &str) -> &str {
        let s = s.trim();
        if s.len() >= 2 {
            let first = s.chars().next().unwrap();
            let last = s.chars().last().unwrap();
            if (first == '"' && last == '"') || (first == '\'' && last == '\'') {
                return &s[1..s.len() - 1];
            }
        }
        s
    }

    fn is_time_break(s: &str) -> bool {
        s.ends_with("s") || s.ends_with("ms")
    }

    fn read_until(chars: &mut std::iter::Peekable<std::str::Chars>, end: char) -> (String, bool) {
        let mut content = String::new();
        let mut found = false;
        while let Some(&next_c) = chars.peek() {
            chars.next();
            if next_c == end {
                found = true;
                break;
            }
            content.push(next_c);
        }
        (content, found)
    }
}

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

    #[test]
    fn test_parse_simple_text() {
        let result = SpeechMarkdownParser::parse("Hello world");
        assert!(result.is_ok());

        let ast = result.unwrap();
        assert_eq!(ast.node_type, NodeType::Document);
        assert!(!ast.children.is_empty());
    }

    #[test]
    fn test_parse_short_break() {
        let result = SpeechMarkdownParser::parse("Sample [2s] text");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_emphasis_strong() {
        let result = SpeechMarkdownParser::parse("++strong emphasis++");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_text_modifier() {
        let result = SpeechMarkdownParser::parse("(text)[voice:\"Kendra\"]");
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_audio() {
        let result = SpeechMarkdownParser::parse("![caption](\"https://example.com/audio.mp3\")");
        assert!(result.is_ok());
    }

    #[test]
    fn test_debug_substitution() {
        let input = "{Al}aluminum";
        let result = SpeechMarkdownParser::parse(input);
        assert!(result.is_ok());

        let ast = result.unwrap();
        println!("=== Substitution Debug ===");
        println!("Input: {}", input);
        println!("AST: {:?}", ast);
        println!("Children: {:?}", ast.children);
        println!("========================");
    }

    #[test]
    fn test_debug_emphasis_ssml() {
        let input = "++strong emphasis++";
        let result =
            SpeechMarkdownParser::to_ssml(input, crate::formatters::base::Platform::AmazonAlexa);
        println!("=== Emphasis SSML Debug ===");
        println!("Input: {}", input);
        println!("SSML Result: {:?}", result);
        println!("==========================");
    }

    #[test]
    fn test_is_speech_markdown() {
        assert!(!SpeechMarkdownParser::is_speech_markdown("Hello world"));
        assert!(!SpeechMarkdownParser::is_speech_markdown(""));
        assert!(SpeechMarkdownParser::is_speech_markdown("Hello (world)[emphasis:\"strong\"]"));
        assert!(SpeechMarkdownParser::is_speech_markdown("Sample [2s] text"));
        assert!(SpeechMarkdownParser::is_speech_markdown("++strong++"));
        assert!(SpeechMarkdownParser::is_speech_markdown("~word~"));
        assert!(SpeechMarkdownParser::is_speech_markdown("{Al}aluminum"));
        assert!(SpeechMarkdownParser::is_speech_markdown("![audio](url)"));
    }

    #[test]
    fn test_validate() {
        assert!(SpeechMarkdownParser::validate("Hello world").is_ok());
        assert!(SpeechMarkdownParser::validate("Hello (world)[emphasis:\"strong\"]").is_ok());
        assert!(SpeechMarkdownParser::validate("Sample [2s] text").is_ok());
        assert!(SpeechMarkdownParser::validate("++strong++").is_ok());
    }
}