File size: 13,243 Bytes
d4101a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Brazilian Portuguese (PT-BR) front end: text -> phoneme tokens with a stress feature.



The same code runs during annotation, training-set preparation and inference,

so tokens can never drift between them.



* eSpeak NG (``pt-br``) is the default pronunciation source (``espeak``).

* A token is one eSpeak phoneme exactly as eSpeak segments it (``--sep``), for

  example ``t``, ``ɐ̃``, ``ɐ̃ʊ̃`` or ``tʃ``. Every phone in ``PHONE_SET`` is also

  present in ``facebook/wav2vec2-lv-60-espeak-cv-ft``'s vocabulary for CTC

  forced alignment.

* Lexical stress is a parallel feature (0 none, 1 primary, 2 secondary), not a

  token, so it never has to be given audio frames.

* Punctuation, word boundaries and the utterance edges are explicit tokens that

  may last zero frames. They carry pauses when the recording has them.

"""

from dataclasses import dataclass
import hashlib
import json
import os
import re
import shutil
import subprocess
import unicodedata

FRONTEND_VERSION = 3
ESPEAK_VOICE = "pt-br"
SEPARATOR = "_"
FRONTENDS = ("espeak", "own")
FRONTEND_VARIABLE = "LUA_NOVA_FRONTEND"
_frontend = os.environ.get(FRONTEND_VARIABLE, "espeak")
if _frontend not in FRONTENDS:
    raise ValueError(f"{FRONTEND_VARIABLE} must be one of {FRONTENDS}, not {_frontend!r}")

PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"
SPECIALS = (PAD, BOS, EOS, SP, UNK)
PUNCTUATION = (",", ".", "?", "!", ";", ":", '"', "'", "(", ")", "-", "—", "…")
CONSONANTS = (
    "p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h",
    "x", "ɣ", "m", "n", "ɲ", "ŋ", "l", "ʎ", "ɾ", "r", "ʁ", "j", "w", "tʃ", "dʒ", "ts",
)
VOWELS = (
    "a", "ɐ", "æ", "e", "ɛ", "ə", "i", "ɪ", "y", "o", "ɔ", "u", "ʊ",
    "aː", "eː", "iː", "oː", "uː",
    "\u0250\u0303", "a\u0303", "e\u0303", "i\u0303", "o\u0303", "u\u0303", "\u0250\u0303\u028a\u0303",
    "aɪ", "aʊ", "eɪ", "eʊ", "ɛɪ", "ɛʊ", "iʊ", "oɪ", "oʊ", "ɔɪ", "uɪ",
)
PHONES = CONSONANTS + VOWELS
# Append-only: changing the order or removing a symbol invalidates checkpoints.
SYMBOLS = SPECIALS + PUNCTUATION + PHONES
SYMBOLS_PTBR = list(SYMBOLS)
SYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}
PHONE_SET = frozenset(PHONES)
PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}
VOICELESS = frozenset(("p", "t", "k", "f", "θ", "s", "ʃ", "h", "x", "tʃ", "ts"))
VOWEL_SET = frozenset(VOWELS)
STRESS_MARKS = {"ˈ": 1, "ˌ": 2}

# eSpeak phonemes outside the inventory (foreign words, rare allophones, NFC nasals)
# map to the closest inventory phone(s). Anything else becomes <unk> and is reported.
FALLBACK = {
    "g": ("ɡ",),
    "\u00e3": ("\u0250\u0303",),
    "\u1ebd": ("e\u0303",),
    "\u0129": ("i\u0303",),
    "\u00f5": ("o\u0303",),
    "\u0169": ("u\u0303",),
    "j\u0303": ("j",),
    "w\u0303": ("w",),
    "ɹ": ("ɾ",),
    "ʔ": ("h",),
    "ɻ": ("ɾ",),
    "ç": ("ʃ",),
    "ɬ": ("l",),
    "ɫ": ("l",),
    "dz": ("d", "z"),
    "β": ("v",),
    "ɑ": ("a",),
    "ɑː": ("aː",),
    "ɒ": ("ɔ",),
    "ɑ\u0303": ("\u0250\u0303",),
    "ɔ\u0303": ("o\u0303",),
    "ɛ\u0303": ("e\u0303",),
    "ʌ": ("ɐ",),
    "ɚ": ("ə", "ɾ"),
    "ᵻ": ("i",),
    "ɜ": ("ɛ",),
    "ɜː": ("ɛ",),
    "ø": ("e",),
    "øː": ("eː",),
    "œ": ("ɛ",),
    "ɛː": ("ɛ",),
    "ɪː": ("iː",),
    "ɔː": ("ɔ",),
    "ʊː": ("uː",),
    "yː": ("y",),
    "əʊ": ("oʊ",),
    "əl": ("ə", "l"),
    "n̩": ("n",),
    "l̩": ("l",),
    "m̩": ("m",),
    "iə": ("i", "ə"),
    "aɪə": ("aɪ", "ə"),
    "aʊɚ": ("aʊ", "ə", "ɾ"),
}

_QUOTES = str.maketrans({"‘": "'", "’": "'", "‚": "'", "‛": "'", "`": "'", "´": "'",
                         "“": '"', "”": '"', "„": '"', "‟": '"', "«": '"', "»": '"',
                         "–": "—", "―": "—", "[": "(", "{": "(", "]": ")", "}": ")"})
_PUNCTUATION_CHARS = frozenset(PUNCTUATION)
ABBREVIATIONS = {
    "dr", "dra", "sr", "sra", "srta", "prof", "profa", "jr", "st", "sto", "sta",
    "vs", "etc", "pág", "cap", "fig", "art", "inc", "ltda",
}
_LANGUAGE_TAG = re.compile(r"\((?:_?[a-z0-9]_?){2,3}(?:-(?:_?[a-z0-9]_?)+)*\)")


class NothingToPronounce(ValueError):
    """The text has no word, number or letter to say: only marks, emoji and the like."""


@dataclass(frozen=True)
class Phonemized:
    symbols: tuple
    ids: tuple
    stress: tuple
    unknown: tuple  # eSpeak phonemes that had no inventory mapping

    def __len__(self):
        return len(self.ids)


def frontend():
    """Name of the program that produces the phonemes: ``"espeak"`` or ``"own"``."""
    return _frontend


def set_frontend(name):
    """Select the phonemizer for this process. Tokens of the two front ends

    must not be mixed: annotations and checkpoints record which one made them."""
    global _frontend
    if name not in FRONTENDS:
        raise ValueError(f"front end must be one of {FRONTENDS}, not {name!r}")
    _frontend = name


def _dizione():
    try:
        import dizione
    except ImportError as error:
        raise RuntimeError('the "own" front end needs the dizione package: pip install dizione') from error
    if tuple(dizione.symbols.SYMBOLS) != SYMBOLS:
        raise RuntimeError("dizione's symbol inventory differs from this model's")
    return dizione


def frontend_identity():
    if _frontend == "own":
        phonemizer = _dizione()
        return {"frontend_version": phonemizer.VERSION, "phonemizer": "dizione", "symbols": list(SYMBOLS)}
    return {"frontend_version": FRONTEND_VERSION, "voice": ESPEAK_VOICE, "separator": SEPARATOR,
            "symbols": list(SYMBOLS), "fallback": {key: list(value) for key, value in sorted(FALLBACK.items())}}


def frontend_runtime():
    """What an annotation run records about the exact program behind its

    tokens: the eSpeak version, or the fingerprint of the phonemizer build."""
    if _frontend == "own":
        return {"phonemizer": _dizione().identity()["fingerprint"]}
    return {"espeak_version": espeak_version()}


def frontend_fingerprint():
    return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()


def normalize_text(text):
    text = unicodedata.normalize("NFKC", text).translate(_QUOTES)
    text = re.sub(r"\.{3,}", "…", text)
    text = re.sub(r"-{2,}|\s-\s", "—", text)
    return re.sub(r"\s+", " ", text).strip()


def chunks(text):
    """Yield ``(is_punctuation, piece)``. Decimals, clock times, digit groups,

    hyphenated words, contractions, title abbreviations and initialisms stay

    inside the text piece for eSpeak; every other punctuation mark becomes its

    own token."""
    start = 0
    for i, char in enumerate(text):
        if char not in _PUNCTUATION_CHARS:
            continue
        previous = text[i-1] if i else ""
        following = text[i+1] if i+1 < len(text) else ""
        if char == "'" and previous.isalnum() and following.isalnum():
            continue
        if char == "-" and previous.isalpha() and following.isalpha():
            continue
        if char in ".,:" and previous.isdigit() and following.isdigit():
            continue
        if char == ".":
            word = re.search(r"([^\W\d_]+)$", text[:i])
            if word and word[1].lower() in ABBREVIATIONS:
                continue
            if previous.isalpha() and following.isalpha():
                continue
        if text[start:i].strip():
            yield False, text[start:i].strip()
        yield True, char
        start = i+1
    if text[start:].strip():
        yield False, text[start:].strip()


def espeak_executable():
    executable = shutil.which("espeak-ng")
    if executable is None:
        raise RuntimeError("Install espeak-ng and ensure it is on PATH before preprocessing/inference")
    return executable


def espeak_version():
    return subprocess.run(
        [espeak_executable(), "--version"],
        capture_output=True, text=True, encoding="utf-8", check=True, timeout=10,
    ).stdout.strip()


def espeak_words(piece):
    """Phonemize one text piece. Returns words as lists of ``(phone, stress)``.



    The input must end with a newline: eSpeak NG 1.51 silently drops the last

    character of unterminated standard input.

    """
    result = subprocess.run(
        [espeak_executable(), "-q", "--ipa", "--sep=" + SEPARATOR, "-v", ESPEAK_VOICE, "--stdin"],
        input=piece.rstrip("\n") + "\n", text=True, encoding="utf-8", capture_output=True, check=True, timeout=30)
    return parse_espeak(result.stdout)


def parse_espeak(output):
    words = []
    for word in _LANGUAGE_TAG.sub("", output).split():
        units = []
        for unit in word.split(SEPARATOR):
            stress = 0
            for mark, level in STRESS_MARKS.items():
                if mark in unit:
                    stress = stress or level
                    unit = unit.replace(mark, "")
            unit = "".join(c for c in unit if unicodedata.category(c) != "Cf" and c not in "()")
            if unit:
                units.append((unit, stress))
        if units:
            words.append(units)
    return words


def canonical(phone):
    """Map an eSpeak phoneme to inventory phones; ``None`` when unknown."""
    if phone in PHONE_SET:
        return (phone,)
    if phone in FALLBACK:
        return FALLBACK[phone]
    for candidate in (unicodedata.normalize("NFD", phone), phone.replace("ː", ""), unicodedata.normalize("NFD", phone).replace("ː", "")):
        if candidate != phone and candidate in PHONE_SET:
            return (candidate,)
        if candidate != phone and candidate in FALLBACK:
            return FALLBACK[candidate]
    stripped = "".join(c for c in unicodedata.normalize("NFD", phone) if not unicodedata.combining(c))
    for candidate in (stripped, stripped.replace("ː", ""), stripped + "ː"):
        if candidate != phone and candidate in PHONE_SET:
            return (candidate,)
        if candidate != phone and candidate in FALLBACK:
            return FALLBACK[candidate]
    # Decompose novel compound diphthongs/affricates into base+combining units.
    parts = []
    for ch in phone.replace("ː", ""):
        if unicodedata.combining(ch) and parts:
            parts[-1] += ch
        else:
            parts.append(ch)
    if len(parts) > 1:
        resolved = []
        for part in parts:
            if part in PHONE_SET:
                resolved.append(part)
            elif part in FALLBACK:
                resolved.extend(FALLBACK[part])
            else:
                return None
        return tuple(resolved)
    return None


def tokenize(pieces):
    """Build the token sequence from ``(is_punctuation, value)`` pieces where a

    text piece's value is the parsed eSpeak word list. Pure function (testable

    without eSpeak)."""
    symbols, stress, unknown = [BOS], [0], []
    for punctuation, value in pieces:
        if punctuation:
            if symbols[-1] != value:  # collapse repeats such as "!!"
                symbols.append(value)
                stress.append(0)
            continue
        for word in value:
            if symbols[-1] in PHONE_SET or symbols[-1] == UNK:
                symbols.append(SP)
                stress.append(0)
            for phone, level in word:
                mapped = canonical(phone)
                if mapped is None:
                    unknown.append(phone)
                    mapped = (UNK,)
                # A fallback may expand to several phones: stress goes to its first vowel.
                carrier = next((i for i, item in enumerate(mapped) if item in VOWEL_SET), 0)
                for index, item in enumerate(mapped):
                    symbols.append(item)
                    stress.append(level if index == carrier else 0)
    symbols.append(EOS)
    stress.append(0)
    if not any(s in PHONE_SET or s == UNK for s in symbols):
        raise NothingToPronounce("the text has nothing to pronounce")
    return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown))


def phonemize(text):
    if not isinstance(text, str) or not text.strip():
        raise ValueError("text must not be empty")
    if _frontend == "own":
        return tokenize(_dizione().pieces(text))
    pieces = []
    for punctuation, piece in chunks(normalize_text(text)):
        pieces.append((True, piece) if punctuation else (False, espeak_words(piece)))
    return tokenize(pieces)


def phonemize_ptbr(text: str) -> tuple[list[int], list[int]]:
    """Return ``(ids, stress)`` lists for Brazilian Portuguese text."""
    result = phonemize(text)
    return list(result.ids), list(result.stress)


def is_phone(token_ids):
    """Boolean list/tensor helper: tokens that must be realised as audio."""
    return [int(i) in PHONE_IDS for i in token_ids]