keithhon commited on
Commit
937d113
1 Parent(s): 1252f42

Upload synthesizer/utils/text.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. synthesizer/utils/text.py +74 -0
synthesizer/utils/text.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .symbols import symbols
2
+ from . import cleaners
3
+ import re
4
+
5
+ # Mappings from symbol to numeric ID and vice versa:
6
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
7
+ _id_to_symbol = {i: s for i, s in enumerate(symbols)}
8
+
9
+ # Regular expression matching text enclosed in curly braces:
10
+ _curly_re = re.compile(r"(.*?)\{(.+?)\}(.*)")
11
+
12
+
13
+ def text_to_sequence(text, cleaner_names):
14
+ """Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
15
+
16
+ The text can optionally have ARPAbet sequences enclosed in curly braces embedded
17
+ in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street."
18
+
19
+ Args:
20
+ text: string to convert to a sequence
21
+ cleaner_names: names of the cleaner functions to run the text through
22
+
23
+ Returns:
24
+ List of integers corresponding to the symbols in the text
25
+ """
26
+ sequence = []
27
+
28
+ # Check for curly braces and treat their contents as ARPAbet:
29
+ while len(text):
30
+ m = _curly_re.match(text)
31
+ if not m:
32
+ sequence += _symbols_to_sequence(_clean_text(text, cleaner_names))
33
+ break
34
+ sequence += _symbols_to_sequence(_clean_text(m.group(1), cleaner_names))
35
+ sequence += _arpabet_to_sequence(m.group(2))
36
+ text = m.group(3)
37
+
38
+ # Append EOS token
39
+ sequence.append(_symbol_to_id["~"])
40
+ return sequence
41
+
42
+
43
+ def sequence_to_text(sequence):
44
+ """Converts a sequence of IDs back to a string"""
45
+ result = ""
46
+ for symbol_id in sequence:
47
+ if symbol_id in _id_to_symbol:
48
+ s = _id_to_symbol[symbol_id]
49
+ # Enclose ARPAbet back in curly braces:
50
+ if len(s) > 1 and s[0] == "@":
51
+ s = "{%s}" % s[1:]
52
+ result += s
53
+ return result.replace("}{", " ")
54
+
55
+
56
+ def _clean_text(text, cleaner_names):
57
+ for name in cleaner_names:
58
+ cleaner = getattr(cleaners, name)
59
+ if not cleaner:
60
+ raise Exception("Unknown cleaner: %s" % name)
61
+ text = cleaner(text)
62
+ return text
63
+
64
+
65
+ def _symbols_to_sequence(symbols):
66
+ return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)]
67
+
68
+
69
+ def _arpabet_to_sequence(text):
70
+ return _symbols_to_sequence(["@" + s for s in text.split()])
71
+
72
+
73
+ def _should_keep_symbol(s):
74
+ return s in _symbol_to_id and s not in ("_", "~")