-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathspeech.rs
More file actions
2945 lines (2640 loc) · 132 KB
/
speech.rs
File metadata and controls
2945 lines (2640 loc) · 132 KB
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The speech module is where the speech rules are read in and speech generated.
//!
//! The speech rules call out to the preferences and tts modules and the dividing line is not always clean.
//! A number of useful utility functions used by other modules are defined here.
#![allow(clippy::needless_return)]
use std::path::PathBuf;
use std::collections::HashMap;
use std::cell::{RefCell, RefMut};
use std::sync::LazyLock;
use sxd_document::dom::{ChildOfElement, Document, Element};
use sxd_document::{Package, QName};
use sxd_xpath::context::Evaluation;
use sxd_xpath::{Factory, Value, XPath};
use sxd_xpath::nodeset::Node;
use std::fmt;
use std::time::SystemTime;
use crate::definitions::read_definitions_file;
use crate::errors::*;
use crate::prefs::*;
use crate::xpath_functions::is_leaf;
use yaml_rust::{YamlLoader, Yaml, yaml::Hash};
use crate::tts::*;
use crate::infer_intent::*;
use crate::pretty_print::{mml_to_string, yaml_to_string};
use std::path::Path;
use std::rc::Rc;
use crate::shim_filesystem::{read_to_string_shim, canonicalize_shim};
use crate::canonicalize::{as_element, create_mathml_element, set_mathml_name, name, MATHML_FROM_NAME_ATTR};
use regex::Regex;
use log::{debug, error, info};
#[cfg(feature = "rule-coverage")]
use crate::rule_coverage;
pub const NAV_NODE_SPEECH_NOT_FOUND: &str = "NAV_NODE_NOT_FOUND";
/// Like lisp's ' (quote foo), this is used to block "replace_chars" being called.
/// Unlike lisp, this appended to the end of a string (more efficient)
/// At the moment, the only use is BrailleChars(...) -- internally, it calls replace_chars and we don't want it called again.
/// Note: an alternative to this hack is to add "xq" (execute but don't eval the result), but that's heavy-handed for the current need
const NO_EVAL_QUOTE_CHAR: char = '\u{efff}'; // a private space char
const NO_EVAL_QUOTE_CHAR_AS_BYTES: [u8;3] = [0xee,0xbf,0xbf];
const N_BYTES_NO_EVAL_QUOTE_CHAR: usize = NO_EVAL_QUOTE_CHAR.len_utf8();
/// Converts 'string' into a "quoted" string -- use is_quoted_string and unquote_string
pub fn make_quoted_string(mut string: String) -> String {
string.push(NO_EVAL_QUOTE_CHAR);
return string;
}
/// Checks the string to see if it is "quoted"
pub fn is_quoted_string(str: &str) -> bool {
if str.len() < N_BYTES_NO_EVAL_QUOTE_CHAR {
return false;
}
let bytes = str.as_bytes();
return bytes[bytes.len()-N_BYTES_NO_EVAL_QUOTE_CHAR..] == NO_EVAL_QUOTE_CHAR_AS_BYTES;
}
/// Converts 'string' into a "quoted" string -- use is_quoted_string and unquote_string
/// IMPORTANT: this assumes the string is quoted -- no check is made
pub fn unquote_string(str: &str) -> &str {
return &str[..str.len()-N_BYTES_NO_EVAL_QUOTE_CHAR];
}
/// The main external call, `intent_from_mathml` returns a string for the speech associated with the `mathml`.
/// It matches against the rules that are computed by user prefs such as "Language" and "SpeechStyle".
///
/// The speech rules assume `mathml` has been "cleaned" via the canonicalization step.
///
/// If the preferences change (and hence the speech rules to use change), or if the rule file changes,
/// `intent_from_mathml` will detect that and (re)load the proper rules.
///
/// A string is returned in call cases.
/// If there is an error, the speech string will indicate an error.
pub fn intent_from_mathml<'m>(mathml: Element, doc: Document<'m>) -> Result<Element<'m>> {
let intent_tree = intent_rules(&INTENT_RULES, doc, mathml, "")?;
doc.root().append_child(intent_tree);
return Ok(intent_tree);
}
pub fn speak_mathml(mathml: Element, nav_node_id: &str, nav_node_offset: usize) -> Result<String> {
return speak_rules(&SPEECH_RULES, mathml, nav_node_id, nav_node_offset);
}
pub fn overview_mathml(mathml: Element, nav_node_id: &str, nav_node_offset: usize) -> Result<String> {
return speak_rules(&OVERVIEW_RULES, mathml, nav_node_id, nav_node_offset);
}
fn intent_rules<'m>(rules: &'static std::thread::LocalKey<RefCell<SpeechRules>>, doc: Document<'m>, mathml: Element, nav_node_id: &'m str) -> Result<Element<'m>> {
rules.with(|rules| {
rules.borrow_mut().read_files()?;
let rules = rules.borrow();
// debug!("intent_rules:\n{}", mml_to_string(mathml));
let should_set_literal_intent = rules.pref_manager.borrow().pref_to_string("SpeechStyle").as_str() == "LiteralSpeak";
let original_intent = mathml.attribute_value("intent");
if should_set_literal_intent {
if let Some(intent) = original_intent {
let intent = if intent.contains('(') {intent.replace('(', ":literal(")} else {intent.to_string() + ":literal"};
mathml.set_attribute_value("intent", &intent);
} else {
mathml.set_attribute_value("intent", ":literal");
};
}
let mut rules_with_context = SpeechRulesWithContext::new(&rules, doc, nav_node_id, 0);
let intent = rules_with_context.match_pattern::<Element<'m>>(mathml)
.context("Pattern match/replacement failure!")?;
let answer = if name(intent) == "TEMP_NAME" { // unneeded extra layer
assert_eq!(intent.children().len(), 1);
as_element(intent.children()[0])
} else {
intent
};
if should_set_literal_intent {
if let Some(original_intent) = original_intent {
mathml.set_attribute_value("intent", original_intent);
} else {
mathml.remove_attribute("intent");
}
}
return Ok(answer);
})
}
/// Speak the MathML
/// If 'nav_node_id' is not an empty string, then the element with that id will have [[...]] around it
fn speak_rules(rules: &'static std::thread::LocalKey<RefCell<SpeechRules>>, mathml: Element, nav_node_id: &str, nav_node_offset: usize) -> Result<String> {
return rules.with(|rules| {
rules.borrow_mut().read_files()?;
let rules = rules.borrow();
// debug!("speak_rules:\n{}", mml_to_string(mathml));
let new_package = Package::new();
let mut rules_with_context = SpeechRulesWithContext::new(&rules, new_package.as_document(), nav_node_id, nav_node_offset);
let speech_string = nestable_speak_rules(& mut rules_with_context, mathml)?;
return Ok( rules.pref_manager.borrow().get_tts()
.merge_pauses(remove_optional_indicators(
&speech_string.replace(CONCAT_STRING, "")
.replace(CONCAT_INDICATOR, "")
)
.trim_start().trim_end_matches([' ', ',', ';'])) );
});
fn nestable_speak_rules<'c, 's:'c, 'm:'c>(rules_with_context: &mut SpeechRulesWithContext<'c, 's, 'm>, mathml: Element<'c>) -> Result<String> {
let mut speech_string = rules_with_context.match_pattern::<String>(mathml)
.context("Pattern match/replacement failure!")?;
// Note: [[...]] is added around a matching child, but if the "id" is on 'mathml', the whole string is used
if !rules_with_context.nav_node_id.is_empty() {
// See https://github.com/NSoiffer/MathCAT/issues/174 for why we can just start the speech at the nav node
let intent_attr = mathml.attribute_value("data-intent-property").unwrap_or_default();
if let Some(start) = speech_string.find("[[") {
match speech_string[start+2..].find("]]") {
None => bail!("Internal error: looking for '[[...]]' during navigation -- only found '[[' in '{}'", speech_string),
Some(end) => speech_string = speech_string[start+2..start+2+end].to_string(),
}
} else if !intent_attr.contains(":literal:") {
// try again with LiteralSpeak -- some parts might have been elided in other SpeechStyles
mathml.set_attribute_value("data-intent-property", (":literal:".to_string() + intent_attr).as_str());
let speech = nestable_speak_rules(rules_with_context, mathml);
mathml.set_attribute_value("data-intent-property", intent_attr);
return speech;
} else {
bail!(NAV_NODE_SPEECH_NOT_FOUND); // NAV_NODE_SPEECH_NOT_FOUND is tested for later
}
}
return Ok(speech_string);
}
}
/// Converts its argument to a string that can be used in a debugging message.
pub fn yaml_to_type(yaml: &Yaml) -> String {
return match yaml {
Yaml::Real(v)=> format!("real='{v:#}'"),
Yaml::Integer(v)=> format!("integer='{v:#}'"),
Yaml::String(v)=> format!("string='{v:#}'"),
Yaml::Boolean(v)=> format!("boolean='{v:#}'"),
Yaml::Array(v)=> match v.len() {
0 => "array with no entries".to_string(),
1 => format!("array with the entry: {}", yaml_to_type(&v[0])),
_ => format!("array with {} entries. First entry: {}", v.len(), yaml_to_type(&v[0])),
}
Yaml::Hash(h)=> {
let first_pair =
if h.is_empty() {
"no pairs".to_string()
} else {
let (key, val) = h.iter().next().unwrap();
format!("({}, {})", yaml_to_type(key), yaml_to_type(val))
};
format!("dictionary with {} pair{}. A pair: {}", h.len(), if h.len()==1 {""} else {"s"}, first_pair)
}
Yaml::Alias(_)=> "Alias".to_string(),
Yaml::Null=> "Null".to_string(),
Yaml::BadValue=> "BadValue".to_string(),
}
}
fn yaml_type_err(yaml: &Yaml, str: &str) -> Error {
anyhow!("Expected {}, found {}", str, yaml_to_type(yaml))
}
// fn yaml_key_err(dict: &Yaml, key: &str, yaml_type: &str) -> String {
// if dict.as_hash().is_none() {
// return format!("Expected dictionary with key '{}', found\n{}", key, yaml_to_string(dict, 1));
// }
// let str = &dict[key];
// if str.is_badvalue() {
// return format!("Did not find '{}' in\n{}", key, yaml_to_string(dict, 1));
// }
// return format!("Type of '{}' is not a {}.\nIt is a {}. YAML value is\n{}",
// key, yaml_type, yaml_to_type(str), yaml_to_string(dict, 0));
// }
fn find_str<'a>(dict: &'a Yaml, key: &'a str) -> Option<&'a str> {
return dict[key].as_str();
}
/// Returns the Yaml as a `Hash` or an error if it isn't.
pub fn as_hash_checked(value: &Yaml) -> Result<&Hash> {
let result = value.as_hash();
let result = result.ok_or_else(|| yaml_type_err(value, "hashmap"))?;
return Ok( result );
}
/// Returns the Yaml as a `Vec` or an error if it isn't.
pub fn as_vec_checked(value: &Yaml) -> Result<&Vec<Yaml>> {
let result = value.as_vec();
let result = result.ok_or_else(|| yaml_type_err(value, "array"))?;
return Ok( result );
}
/// Returns the Yaml as a `&str` or an error if it isn't.
pub fn as_str_checked(yaml: &Yaml) -> Result<&str> {
return yaml.as_str().ok_or_else(|| yaml_type_err(yaml, "string"));
}
/// A bit of a hack to concatenate replacements (without a ' ').
/// The CONCAT_INDICATOR is added by a "ct:" (instead of 't:') in the speech rules
/// and checked for by the tts code.
pub const CONCAT_INDICATOR: &str = "\u{F8FE}";
// This is the pattern that needs to be matched (and deleted)
pub const CONCAT_STRING: &str = " \u{F8FE}";
// a similar hack to potentially delete (repetitive) optional replacements
// the OPTIONAL_INDICATOR is added by "ot:" before and after the optional string
const OPTIONAL_INDICATOR: &str = "\u{F8FD}";
const OPTIONAL_INDICATOR_LEN: usize = OPTIONAL_INDICATOR.len();
pub fn remove_optional_indicators(str: &str) -> String {
return str.replace(OPTIONAL_INDICATOR, "");
}
/// Given a string that should be Yaml, it calls `build_fn` with that string.
/// The build function/closure should process the Yaml as appropriate and capture any errors and write them to `std_err`.
/// The returned value should be a Vector containing the paths of all the files that were included.
pub fn compile_rule<F>(str: &str, mut build_fn: F) -> Result<Vec<PathBuf>> where
F: FnMut(&Yaml) -> Result<Vec<PathBuf>> {
let docs = YamlLoader::load_from_str(str);
match docs {
Err(e) => {
bail!("Parse error!!: {}", e);
},
Ok(docs) => {
if docs.len() != 1 {
bail!("Didn't find rules!");
}
return build_fn(&docs[0]);
}
}
}
pub fn process_include<F>(current_file: &Path, new_file_name: &str, mut read_new_file: F) -> Result<Vec<PathBuf>>
where F: FnMut(&Path) -> Result<Vec<PathBuf>> {
let parent_path = current_file.parent();
if parent_path.is_none() {
bail!("Internal error: {:?} is not a valid file name", current_file);
}
let mut new_file = match canonicalize_shim(parent_path.unwrap()) {
Ok(path) => path,
Err(e) => bail!("process_include: canonicalize failed for {} with message {}", parent_path.unwrap().display(), e),
};
// the referenced file might be in a directory that hasn't been zipped up -- find the dir and call the unzip function
for unzip_dir in new_file.ancestors() {
if unzip_dir.ends_with("Rules") {
break; // nothing to unzip
}
if unzip_dir.ends_with("Languages") || unzip_dir.ends_with("Braille") {
// get the subdir ...Rules/Braille/en/...
// could have ...Rules/Braille/definitions.yaml, so 'next()' doesn't exist in this case, but the file wasn't zipped up
if let Some(subdir) = new_file.strip_prefix(unzip_dir).unwrap().iter().next() {
let default_lang = if unzip_dir.ends_with("Languages") {"en"} else {"UEB;"};
PreferenceManager::unzip_files(unzip_dir, subdir.to_str().unwrap(), Some(default_lang)).unwrap_or_default();
}
}
}
new_file.push(new_file_name);
info!("...processing include: {new_file_name}...");
let new_file = match crate::shim_filesystem::canonicalize_shim(new_file.as_path()) {
Ok(buf) => buf,
Err(msg) => bail!("-include: constructed file name '{}' causes error '{}'",
new_file.to_str().unwrap(), msg),
};
let mut included_files = read_new_file(new_file.as_path())?;
let mut files_read = vec![new_file];
files_read.append(&mut included_files);
return Ok(files_read);
}
/// As the name says, TreeOrString is either a Tree (Element) or a String
/// It is used to share code during pattern matching
pub trait TreeOrString<'c, 'm:'c, T> {
fn from_element(e: Element<'m>) -> Result<T>;
fn from_string(s: String, doc: Document<'m>) -> Result<T>;
fn replace_tts<'s:'c, 'r>(tts: &TTS, command: &TTSCommandRule, prefs: &PreferenceManager, rules_with_context: &'r mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T>;
fn replace<'s:'c, 'r>(ra: &ReplacementArray, rules_with_context: &'r mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T>;
fn replace_nodes<'s:'c, 'r>(rules: &'r mut SpeechRulesWithContext<'c, 's,'m>, nodes: Vec<Node<'c>>, mathml: Element<'c>) -> Result<T>;
fn highlight_braille(braille: T, highlight_style: String) -> T;
fn mark_nav_speech(speech: T) -> T;
}
impl<'c, 'm:'c> TreeOrString<'c, 'm, String> for String {
fn from_element(_e: Element<'m>) -> Result<String> {
bail!("from_element not allowed for strings");
}
fn from_string(s: String, _doc: Document<'m>) -> Result<String> {
return Ok(s);
}
fn replace_tts<'s:'c, 'r>(tts: &TTS, command: &TTSCommandRule, prefs: &PreferenceManager, rules_with_context: &'r mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<String> {
return tts.replace_string(command, prefs, rules_with_context, mathml);
}
fn replace<'s:'c, 'r>(ra: &ReplacementArray, rules_with_context: &'r mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<String> {
return ra.replace_array_string(rules_with_context, mathml);
}
fn replace_nodes<'s:'c, 'r>(rules: &'r mut SpeechRulesWithContext<'c, 's,'m>, nodes: Vec<Node<'c>>, mathml: Element<'c>) -> Result<String> {
return rules.replace_nodes_string(nodes, mathml);
}
fn highlight_braille(braille: String, highlight_style: String) -> String {
return SpeechRulesWithContext::highlight_braille_string(braille, highlight_style);
}
fn mark_nav_speech(speech: String) -> String {
return SpeechRulesWithContext::mark_nav_speech(speech);
}
}
impl<'c, 'm:'c> TreeOrString<'c, 'm, Element<'m>> for Element<'m> {
fn from_element(e: Element<'m>) -> Result<Element<'m>> {
return Ok(e);
}
fn from_string(s: String, doc: Document<'m>) -> Result<Element<'m>> {
// FIX: is 'mi' really ok? Don't want to use TEMP_NAME because this name needs to move to the outside world
let leaf = create_mathml_element(&doc, "mi");
leaf.set_text(&s);
return Ok(leaf);
}
fn replace_tts<'s:'c, 'r>(_tts: &TTS, _command: &TTSCommandRule, _prefs: &PreferenceManager, _rules_with_context: &'r mut SpeechRulesWithContext<'c, 's,'m>, _mathml: Element<'c>) -> Result<Element<'m>> {
bail!("Internal error: applying a TTS rule to a tree");
}
fn replace<'s:'c, 'r>(ra: &ReplacementArray, rules_with_context: &'r mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<Element<'m>> {
return ra.replace_array_tree(rules_with_context, mathml);
}
fn replace_nodes<'s:'c, 'r>(rules: &'r mut SpeechRulesWithContext<'c, 's,'m>, nodes: Vec<Node<'c>>, mathml: Element<'c>) -> Result<Element<'m>> {
return rules.replace_nodes_tree(nodes, mathml);
}
fn highlight_braille(_braille: Element<'c>, _highlight_style: String) -> Element<'m> {
panic!("Internal error: highlight_braille called on a tree");
}
fn mark_nav_speech(_speech: Element<'c>) -> Element<'m> {
panic!("Internal error: mark_nav_speech called on a tree");
}
}
/// 'Replacement' is an enum that contains all the potential replacement types/structs
/// Hence there are fields 'Test' ("test:"), 'Text" ("t:"), "XPath", etc
#[derive(Debug, Clone)]
#[allow(clippy::upper_case_acronyms)]
enum Replacement {
// Note: all of these are pointer types
Text(String),
XPath(MyXPath),
Intent(Box<Intent>),
Test(Box<TestArray>),
TTS(Box<TTSCommandRule>),
With(Box<With>),
SetVariables(Box<SetVariables>),
Insert(Box<InsertChildren>),
Translate(TranslateExpression),
}
impl fmt::Display for Replacement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "{}",
match self {
Replacement::Test(c) => c.to_string(),
Replacement::Text(t) => format!("t: \"{t}\""),
Replacement::XPath(x) => x.to_string(),
Replacement::Intent(i) => i.to_string(),
Replacement::TTS(t) => t.to_string(),
Replacement::With(w) => w.to_string(),
Replacement::SetVariables(v) => v.to_string(),
Replacement::Insert(ic) => ic.to_string(),
Replacement::Translate(x) => x.to_string(),
}
);
}
}
impl Replacement {
fn build(replacement: &Yaml) -> Result<Replacement> {
// Replacement -- single key/value (see below for allowed values)
let dictionary = replacement.as_hash();
if dictionary.is_none() {
bail!(" expected a key/value pair. Found {}.", yaml_to_string(replacement, 0));
};
let dictionary = dictionary.unwrap();
if dictionary.is_empty() {
bail!("No key/value pairs found for key 'replace'.\n\
Suggestion: are the following lines indented properly?");
}
if dictionary.len() > 1 {
bail!("Should only be one key/value pair for the replacement.\n \
Suggestion: are the following lines indented properly?\n \
The key/value pairs found are\n{}", yaml_to_string(replacement, 2));
}
// get the single value
let (key, value) = dictionary.iter().next().unwrap();
let key = key.as_str().ok_or_else(|| anyhow!("replacement key(e.g, 't') is not a string"))?;
match key {
"t" | "T" => {
return Ok( Replacement::Text( as_str_checked(value)?.to_string() ) );
},
"ct" | "CT" => {
return Ok( Replacement::Text( CONCAT_INDICATOR.to_string() + as_str_checked(value)? ) );
},
"ot" | "OT" => {
return Ok( Replacement::Text( OPTIONAL_INDICATOR.to_string() + as_str_checked(value)? + OPTIONAL_INDICATOR ) );
},
"x" => {
return Ok( Replacement::XPath( MyXPath::build(value)
.context("while trying to evaluate value of 'x:'")? ) );
},
"pause" | "rate" | "pitch" | "volume" | "audio" | "gender" | "voice" | "spell" | "SPELL" | "bookmark" | "pronounce" | "PRONOUNCE" => {
return Ok( Replacement::TTS( TTS::build(&key.to_ascii_lowercase(), value)? ) );
},
"intent" => {
return Ok( Replacement::Intent( Intent::build(value)? ) );
},
"test" => {
return Ok( Replacement::Test( Box::new( TestArray::build(value)? ) ) );
},
"with" => {
return Ok( Replacement::With( With::build(value)? ) );
},
"set_variables" => {
return Ok( Replacement::SetVariables( SetVariables::build(value)? ) );
},
"insert" => {
return Ok( Replacement::Insert( InsertChildren::build(value)? ) );
},
"translate" => {
return Ok( Replacement::Translate( TranslateExpression::build(value)
.context("while trying to evaluate value of 'speak:'")? ) );
},
_ => {
bail!("Unknown 'replace' command ({}) with value: {}", key, yaml_to_string(value, 0));
}
}
}
}
// structure used when "insert:" is encountered in a rule
// the 'replacements' are inserted between each node in the 'xpath'
#[derive(Debug, Clone)]
struct InsertChildren {
xpath: MyXPath, // the replacement nodes
replacements: ReplacementArray, // what is inserted between each node
}
impl fmt::Display for InsertChildren {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "InsertChildren:\n nodes {}\n replacements {}", self.xpath, &self.replacements);
}
}
impl InsertChildren {
fn build(insert: &Yaml) -> Result<Box<InsertChildren>> {
// 'insert:' -- 'nodes': xxx 'replace': xxx
if insert.as_hash().is_none() {
bail!("")
}
let nodes = &insert["nodes"];
if nodes.is_badvalue() {
bail!("Missing 'nodes' as part of 'insert'.\n \
Suggestion: add 'nodes:' or if present, indent so it is contained in 'insert'");
}
let nodes = as_str_checked(nodes)?;
let replace = &insert["replace"];
if replace.is_badvalue() {
bail!("Missing 'replace' as part of 'insert'.\n \
Suggestion: add 'replace:' or if present, indent so it is contained in 'insert'");
}
return Ok( Box::new( InsertChildren {
xpath: MyXPath::new(nodes.to_string())?,
replacements: ReplacementArray::build(replace).context("'replace:'")?,
} ) );
}
// It would be most efficient to do an xpath eval, get the nodes (type: NodeSet) and then intersperse the node_replace()
// calls with replacements for the ReplacementArray parts. But that causes problems with the "pause: auto" calculation because
// the replacements are segmented (can't look to neighbors for the calculation there)
// An alternative is to introduce another Replacement enum value, but that's a lot of complication for not that much
// gain (and Node's have contagious lifetimes)
// The solution adopted is to find out the number of nodes and build up MyXPaths with each node selected (e.g, "*" => "*[3]")
// and put those nodes into a flat ReplacementArray and then do a standard replace on that.
// This is slower than the alternatives, but reuses a bunch of code and hence is less complicated.
fn replace<'c, 's:'c, 'm: 'c, T:TreeOrString<'c, 'm, T>>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T> {
let result = self.xpath.evaluate(&rules_with_context.context_stack.base, mathml)
.with_context(||format!("in '{}' replacing after pattern match", &self.xpath.rc.string) )?;
match result {
Value::Nodeset(nodes) => {
if nodes.size() == 0 {
bail!("During replacement, no matching element found");
};
let nodes = nodes.document_order();
let n_nodes = nodes.len();
let mut expanded_result = Vec::with_capacity(n_nodes + (n_nodes+1)*self.replacements.replacements.len());
expanded_result.push(
Replacement::XPath(
MyXPath::new(format!("{}[{}]", self.xpath.rc.string , 1))?
)
);
for i in 2..n_nodes+1 {
expanded_result.extend_from_slice(&self.replacements.replacements);
expanded_result.push(
Replacement::XPath(
MyXPath::new(format!("{}[{}]", self.xpath.rc.string , i))?
)
);
}
let replacements = ReplacementArray{ replacements: expanded_result };
return replacements.replace(rules_with_context, mathml);
},
// FIX: should the options be errors???
Value::String(t) => { return T::from_string(rules_with_context.replace_chars(&t, mathml)?, rules_with_context.doc); },
Value::Number(num) => { return T::from_string( num.to_string(), rules_with_context.doc ); },
Value::Boolean(b) => { return T::from_string( b.to_string(), rules_with_context.doc ); }, // FIX: is this right???
}
}
}
static ATTR_NAME_VALUE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
// match name='value', where name is sort of an NCNAME (see CONCEPT_OR_LITERAL in infer_intent.rs)
// The quotes can be either single or double quotes
r#"(?P<name>[^\s\u{0}-\u{40}\[\\\]^`\u{7B}-\u{BF}][^\s\u{0}-\u{2C}/:;<=>?@\[\\\]^`\u{7B}-\u{BF}]*)\s*=\s*('(?P<value>[^']+)'|"(?P<dqvalue>[^"]+)")"#
).unwrap()
});
// structure used when "intent:" is encountered in a rule
// the name is either a string or an xpath that needs evaluation. 99% of the time it is a string
#[derive(Debug, Clone)]
struct Intent {
name: Option<String>, // name of node
xpath: Option<MyXPath>, // alternative to directly using the string
attrs: String, // optional attrs -- format "attr1='val1' [attr2='val2'...]"
children: ReplacementArray, // children of node
}
impl fmt::Display for Intent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let name = if self.name.is_some() {
self.name.as_ref().unwrap().to_string()
} else {
self.xpath.as_ref().unwrap().to_string()
};
return write!(f, "intent: {}: {}, attrs='{}'>\n children: {}",
if self.name.is_some() {"name"} else {"xpath-name"}, name,
self.attrs,
&self.children);
}
}
impl Intent {
fn build(yaml_dict: &Yaml) -> Result<Box<Intent>> {
// 'intent:' -- 'name': xxx 'children': xxx
if yaml_dict.as_hash().is_none() {
bail!("Array found for contents of 'intent' -- should be dictionary with keys 'name' and 'children'")
}
let name = &yaml_dict["name"];
let xpath_name = &yaml_dict["xpath-name"];
if name.is_badvalue() && xpath_name.is_badvalue(){
bail!("Missing 'name' or 'xpath-name' as part of 'intent'.\n \
Suggestion: add 'name:' or if present, indent so it is contained in 'intent'");
}
let attrs = &yaml_dict["attrs"];
let replace = &yaml_dict["children"];
if replace.is_badvalue() {
bail!("Missing 'children' as part of 'intent'.\n \
Suggestion: add 'children:' or if present, indent so it is contained in 'intent'");
}
return Ok( Box::new( Intent {
name: if name.is_badvalue() {None} else {Some(as_str_checked(name).context("'name'")?.to_string())},
xpath: if xpath_name.is_badvalue() {None} else {Some(MyXPath::build(xpath_name).context("'intent'")?)},
attrs: if attrs.is_badvalue() {"".to_string()} else {as_str_checked(attrs).context("'attrs'")?.to_string()},
children: ReplacementArray::build(replace).context("'children:'")?,
} ) );
}
fn replace<'c, 's:'c, 'm: 'c, T:TreeOrString<'c, 'm, T>>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T> {
let result = self.children.replace::<Element<'m>>(rules_with_context, mathml)
.context("replacing inside 'intent'")?;
let mut result = lift_children(result);
if name(result) != "TEMP_NAME" && name(result) != "Unknown" {
// this case happens when you have an 'intent' replacement as a direct child of an 'intent' replacement
let temp = create_mathml_element(&result.document(), "TEMP_NAME");
temp.append_child(result);
result = temp;
}
if let Some(intent_name) = &self.name {
result.set_attribute_value(MATHML_FROM_NAME_ATTR, name(mathml));
set_mathml_name(result, intent_name.as_str());
}
if let Some(my_xpath) = &self.xpath{ // self.xpath_name must be != None
let xpath_value = my_xpath.evaluate(rules_with_context.get_context(), mathml)?;
match xpath_value {
Value::String(intent_name) => {
result.set_attribute_value(MATHML_FROM_NAME_ATTR, name(mathml));
set_mathml_name(result, intent_name.as_str())
},
_ => bail!("'xpath-name' value '{}' was not a string", &my_xpath),
}
}
if self.name.is_none() && self.xpath.is_none() {
panic!("Intent::replace: internal error -- neither 'name' nor 'xpath' is set");
};
for attr in mathml.attributes() {
result.set_attribute_value(attr.name(), attr.value());
}
// can't test against name == "math" because intent might a new element
if mathml.parent().is_some() && mathml.parent().unwrap().element().is_some() &&
result.attribute_value("id") == crate::canonicalize::get_parent(mathml).attribute_value("id") {
// avoid duplicate ids -- it's a bug if it does, but this helps in that case
result.remove_attribute("id");
}
if !self.attrs.is_empty() {
// debug!("MathML after children, before attr processing:\n{}", mml_to_string(mathml));
// debug!("Result after children, before attr processing:\n{}", mml_to_string(result));
// debug!("Intent::replace attrs = \"{}\"", &self.attrs);
for cap in ATTR_NAME_VALUE.captures_iter(&self.attrs) {
let matched_value = if cap["value"].is_empty() {&cap["dqvalue"]} else {&cap["value"]};
let value_as_xpath = MyXPath::new(matched_value.to_string()).context("attr value inside 'intent'")?;
let value = value_as_xpath.evaluate(rules_with_context.get_context(), result)
.context("attr xpath evaluation value inside 'intent'")?;
let mut value = value.into_string();
if &cap["name"] == INTENT_PROPERTY {
value = simplify_fixity_properties(&value);
}
// debug!("Intent::replace match\n name={}\n value={}\n xpath value={}", &cap["name"], &cap["value"], &value);
if &cap["name"] == INTENT_PROPERTY && value == ":" {
// should have been an empty string, so remove the attribute
result.remove_attribute(INTENT_PROPERTY);
} else {
result.set_attribute_value(&cap["name"], &value);
}
};
}
// debug!("Result from 'intent:'\n{}", mml_to_string(result));
return T::from_element(result);
/// "lift" up the children any "TEMP_NAME" child -- could short circuit when only one child
fn lift_children(result: Element) -> Element {
// debug!("lift_children:\n{}", mml_to_string(result));
// most likely there will be the same number of new children as result has, but there could be more
let mut new_children = Vec::with_capacity(2*result.children().len());
for child_of_element in result.children() {
match child_of_element {
ChildOfElement::Element(child) => {
if name(child) == "TEMP_NAME" {
new_children.append(&mut child.children()); // almost always just one
} else {
new_children.push(child_of_element);
}
},
_ => new_children.push(child_of_element), // text()
}
}
result.replace_children(new_children);
return result;
}
}
}
// structure used when "with:" is encountered in a rule
// the variables are placed on (and later) popped of a variable stack before/after the replacement
#[derive(Debug, Clone)]
struct With {
variables: VariableDefinitions, // variables and values
replacements: ReplacementArray, // what to do with these vars
}
impl fmt::Display for With {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "with:\n variables: {}\n replace: {}", &self.variables, &self.replacements);
}
}
impl With {
fn build(vars_replacements: &Yaml) -> Result<Box<With>> {
// 'with:' -- 'variables': xxx 'replace': xxx
if vars_replacements.as_hash().is_none() {
bail!("Array found for contents of 'with' -- should be dictionary with keys 'variables' and 'replace'")
}
let var_defs = &vars_replacements["variables"];
if var_defs.is_badvalue() {
bail!("Missing 'variables' as part of 'with'.\n \
Suggestion: add 'variables:' or if present, indent so it is contained in 'with'");
}
let replace = &vars_replacements["replace"];
if replace.is_badvalue() {
bail!("Missing 'replace' as part of 'with'.\n \
Suggestion: add 'replace:' or if present, indent so it is contained in 'with'");
}
return Ok( Box::new( With {
variables: VariableDefinitions::build(var_defs).context("'variables'")?,
replacements: ReplacementArray::build(replace).context("'replace:'")?,
} ) );
}
fn replace<'c, 's:'c, 'm: 'c, T:TreeOrString<'c, 'm, T>>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T> {
rules_with_context.context_stack.push(self.variables.clone(), mathml)?;
let result = self.replacements.replace(rules_with_context, mathml)
.context("replacing inside 'with'")?;
rules_with_context.context_stack.pop();
return Ok( result );
}
}
// structure used when "set_variables:" is encountered in a rule
// the variables are global and are placed in the base context and never popped off
#[derive(Debug, Clone)]
struct SetVariables {
variables: VariableDefinitions, // variables and values
}
impl fmt::Display for SetVariables {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "SetVariables: variables {}", &self.variables);
}
}
impl SetVariables {
fn build(vars: &Yaml) -> Result<Box<SetVariables>> {
// 'set_variables:' -- 'variables': xxx (array)
if vars.as_vec().is_none() {
bail!("'set_variables' -- should be an array of variable name, xpath value");
}
return Ok( Box::new( SetVariables {
variables: VariableDefinitions::build(vars).context("'set_variables'")?
} ) );
}
fn replace<'c, 's:'c, 'm: 'c, T:TreeOrString<'c, 'm, T>>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T> {
rules_with_context.context_stack.set_globals(self.variables.clone(), mathml)?;
return T::from_string( "".to_string(), rules_with_context.doc );
}
}
/// Allow speech of an expression in the middle of a rule (used by "WhereAmI" for navigation)
#[derive(Debug, Clone)]
struct TranslateExpression {
xpath: MyXPath, // variables and values
}
impl fmt::Display for TranslateExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "speak: {}", &self.xpath);
}
}
impl TranslateExpression {
fn build(vars: &Yaml) -> Result<TranslateExpression> {
// 'translate:' -- xpath (should evaluate to an id)
return Ok( TranslateExpression { xpath: MyXPath::build(vars).context("'translate'")? } );
}
fn replace<'c, 's:'c, 'm:'c, T:TreeOrString<'c, 'm, T>>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T> {
if self.xpath.rc.string.starts_with('@') {
let xpath_value = self.xpath.evaluate(rules_with_context.get_context(), mathml)?;
let id = match xpath_value {
Value::String(s) => Some(s),
Value::Nodeset(nodes) => {
if nodes.size() == 1 {
nodes.document_order_first().unwrap().attribute().map(|attr| attr.value().to_string())
} else {
None
}
},
_ => None,
};
match id {
None => bail!("'translate' value '{}' is not a string or an attribute value (correct by using '@id'??):\n", self.xpath),
Some(id) => {
let speech = speak_mathml(mathml, &id, 0)?;
return T::from_string(speech, rules_with_context.doc);
}
}
} else {
return T::from_string(
self.xpath.replace(rules_with_context, mathml).context("'translate'")?,
rules_with_context.doc
);
}
}
}
/// An array of rule `Replacement`s (text, xpath, tts commands, etc)
#[derive(Debug, Clone)]
pub struct ReplacementArray {
replacements: Vec<Replacement>
}
impl fmt::Display for ReplacementArray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
return write!(f, "{}", self.pretty_print_replacements());
}
}
impl ReplacementArray {
/// Return an empty `ReplacementArray`
pub fn build_empty() -> ReplacementArray {
return ReplacementArray {
replacements: vec![]
}
}
/// Convert a Yaml input into a [`ReplacementArray`].
/// Any errors are passed back out.
pub fn build(replacements: &Yaml) -> Result<ReplacementArray> {
// replacements is either a single replacement or an array of replacements
let result= if replacements.is_array() {
let replacements = replacements.as_vec().unwrap();
replacements
.iter()
.enumerate() // useful for errors
.map(|(i, r)| Replacement::build(r)
.with_context(|| format!("replacement #{} of {}", i+1, replacements.len())))
.collect::<Result<Vec<Replacement>>>()?
} else {
vec![ Replacement::build(replacements)?]
};
return Ok( ReplacementArray{ replacements: result } );
}
/// Do all the replacements in `mathml` using `rules`.
pub fn replace<'c, 's:'c, 'm:'c, T:TreeOrString<'c, 'm, T>>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<T> {
return T::replace(self, rules_with_context, mathml);
}
pub fn replace_array_string<'c, 's:'c, 'm:'c>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<String> {
// loop over the replacements and build up a vector of strings, excluding empty ones.
// * eliminate any redundance
// * add/replace auto-pauses
// * join the remaining vector together
let mut replacement_strings = Vec::with_capacity(self.replacements.len()); // probably conservative guess
for replacement in self.replacements.iter() {
let string: String = rules_with_context.replace(replacement, mathml)?;
if !string.is_empty() {
replacement_strings.push(string);
}
}
if replacement_strings.is_empty() {
return Ok( "".to_string() );
}
// delete an optional text that is repetitive
// we do this by looking for the optional text marker, and if present, check for repetition at end of previous string
// if repetitive, we delete the optional string
// if not, we leave the markers because the repetition might happen several "levels" up
// this could also be done in a final cleanup of the entire string (where we remove any markers),
// but the match is harder (rust regex lacks look behind pattern match) and it is less efficient
// Note: we skip the first string since it can't be repetitive of something at this level
for i in 1..replacement_strings.len()-1 {
if let Some(bytes) = is_repetitive(&replacement_strings[i-1], &replacement_strings[i]) {
replacement_strings[i] = bytes.to_string();
}
}
for i in 0..replacement_strings.len() {
if replacement_strings[i].contains(PAUSE_AUTO_STR) {
let before = if i == 0 {""} else {&replacement_strings[i-1]};
let after = if i+1 == replacement_strings.len() {""} else {&replacement_strings[i+1]};
replacement_strings[i] = replacement_strings[i].replace(
PAUSE_AUTO_STR,
&rules_with_context.speech_rules.pref_manager.borrow().get_tts().compute_auto_pause(&rules_with_context.speech_rules.pref_manager.borrow(), before, after));
}
}
// join the strings together with spaces in between
// concatenation (removal of spaces) is saved for the top level because they otherwise are stripped at the wrong sometimes
return Ok( replacement_strings.join(" ") );
fn is_repetitive<'a>(prev: &str, optional: &'a str) -> Option<&'a str> {
// OPTIONAL_INDICATOR surrounds the optional text
// minor optimization -- lots of short strings and the OPTIONAL_INDICATOR takes a few bytes, so skip the check for those strings
if optional.len() <= 2 * OPTIONAL_INDICATOR_LEN {
return None;
}
// should be exactly one match -- ignore more than one for now
match optional.find(OPTIONAL_INDICATOR) {
None => return None,
Some(start_index) => {
let optional_word_start_slice = &optional[start_index + OPTIONAL_INDICATOR_LEN..];
// now find the end
match optional_word_start_slice.find(OPTIONAL_INDICATOR) {
None => panic!("Internal error: missing end optional char -- text handling is corrupted!"),
Some(end_index) => {
let optional_word = &optional_word_start_slice[..end_index];
// debug!("check if '{}' is repetitive", optional_word);
// debug!(" prev: '{}', next '{}'", prev, optional);
let prev = prev.trim_end().as_bytes();
if prev.len() > optional_word.len() &&
&prev[prev.len()-optional_word.len()..] == optional_word.as_bytes() {
return Some( optional_word_start_slice[optional_word.len() + OPTIONAL_INDICATOR_LEN..].trim_start() );
} else {
return None;
}
}
}
}
}
}
}
pub fn replace_array_tree<'c, 's:'c, 'm:'c>(&self, rules_with_context: &mut SpeechRulesWithContext<'c, 's,'m>, mathml: Element<'c>) -> Result<Element<'m>> {
// shortcut for common case (don't build a new tree node)
if self.replacements.len() == 1 {
return rules_with_context.replace::<Element<'m>>(&self.replacements[0], mathml);
}
let new_element = create_mathml_element(&rules_with_context.doc, "Unknown"); // Hopefully set later (in Intent::Replace())
let mut new_children = Vec::with_capacity(self.replacements.len());
for child in self.replacements.iter() {
let child = rules_with_context.replace::<Element<'m>>(child, mathml)?;
new_children.push(ChildOfElement::Element(child));
};
new_element.append_children(new_children);
return Ok(new_element);
}
/// Return true if there are no replacements.
pub fn is_empty(&self) -> bool {
return self.replacements.is_empty();
}
fn pretty_print_replacements(&self) -> String {
let mut group_string = String::with_capacity(128);
if self.replacements.len() == 1 {
group_string += &format!("[{}]", self.replacements[0]);
} else {
group_string += &self.replacements.iter()
.map(|replacement| format!("\n - {replacement}"))
.collect::<Vec<String>>()
.join("");
group_string += "\n";
}
return group_string;
}
}