File size: 6,401 Bytes
e4d2e6e
 
 
 
 
 
 
 
 
 
 
 
7170852
 
 
 
 
 
e4d2e6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7170852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4d2e6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb98fc7
 
 
e4d2e6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb98fc7
e4d2e6e
 
fb98fc7
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
"""Text front for Uzbek TTS, the chain the text goes through before the voice:

  1. English words, brand names and acronyms are set aside as stand-ins: the voice reads them from their ordinary
     spelling, so the normaliser must not respell them (a unit right after a number, "5 kg", is left to it);
  2. normaliser (frontend/tts_frontend.py): Unicode and Uzbek apostrophes, markdown, emoji and quotes cleaned; sound
     tags kept ([laugh], [pause], [breath]); Cyrillic to Uzbek Latin; numbers, dates, times, money, percentages,
     ranges, units and phone numbers to words; register "conversational" adds the Tashkent spoken forms, "literary"
     keeps the written ones; spacing, capitals and a closing mark;
  3. the words of step 1 back in place, as they were written.

    prepare("Narxi 1 250 000 so'm, Payme orqali to'lang, CRMga o'zi tushadi")
    -> "Narxi bir million ikki yuz ellik ming so'm, Payme orqali to'lang, CRMga o'zi tushadi."

Gapiring Nano reads Uzbek letters only, so its text goes the other way, prepare_readings(): the dictionary of English
words (dictionary.py) and the normaliser's own term tables turn English words, brands and acronyms into Uzbek readings.

    prepare_readings("Narxi 1 250 000 so'm, Payme orqali to'lang", Dictionary.load("lexicon/en_uz.tsv"))
    -> "Narxi bir million ikki yuz ellik ming so'm, Peymi orqali to'lang."
"""

from __future__ import annotations

import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent / "frontend"))
import tts_frontend  # noqa: E402

REGISTERS = ("literary", "conversational")
_BREATHS = re.compile(r"\[(sigh|breath|inhale|exhales)\]")   # what the normaliser turns into [breath], in order
_BREATH = re.compile(r"\[breath\]")
PRONOUNCE = [(re.compile(r"\b(a)l+o\b", re.I), lambda m: m.group(1) + "lyo")]   # the phone greeting as it sounds
# what the normaliser would respell: its term tables in both cases, and capital-letter acronyms it would spell out
_HOLD = (tts_frontend._TERM_RE, tts_frontend._TERM_RE_I, re.compile(r"(?<![A-Za-z'])[A-Z]{2,6}(?![A-Za-z'])"))
_AFTER_NUMBER = re.compile(r"\d\s?$")


def said(text: str, register: str = "literary") -> str:
    """Step 2: the normaliser in the given register."""
    if register not in REGISTERS:
        raise ValueError(f"register {register!r}: choose from {REGISTERS}")
    for pattern, spoken in PRONOUNCE:
        text = pattern.sub(spoken, text)
    spoken = tts_frontend.normalize(text, register).text
    # the normaliser knows three sounds and writes a sigh as a breath; this voice has both, so the sighs go back in
    kinds = _BREATHS.findall(text)
    if "sigh" in kinds and len(_BREATH.findall(spoken)) == len(kinds):
        left = iter(kinds)
        spoken = _BREATH.sub(lambda m: "[sigh]" if next(left) == "sigh" else m.group(0), spoken)
    return spoken


# respellings of a few names as they sound, for prepare_readings()
READINGS = PRONOUNCE + [
    (re.compile(r"\bLux\b"), lambda m: "Lyuks"),
    (re.compile(r"\bTechno", re.I), lambda m: "Texno"),
    (re.compile(r"\bamo\s*CRM\b", re.I), lambda m: "amo CRM"),
    (re.compile(r"\bExcel", re.I), lambda m: "Eksel"),
    (re.compile(r"\bGoogle\s*Sheets?", re.I), lambda m: "Gugl Shits"),
    (re.compile(r"\bGoogle\s*Meet", re.I), lambda m: "Gugl Mit"),
    (re.compile(r"\bGoogle", re.I), lambda m: "Gugl"),
    (re.compile(r"\bBitrix(?!\s*\d)", re.I), lambda m: "Bitriks"),
]


def prepare_readings(text: str, dictionary=None, register: str = "literary") -> str:
    """The chain for a model that reads Uzbek letters only (Gapiring Nano): the dictionary's readings are held as
    stand-ins, the names above are respelt, the normaliser reads out numbers and its own terms, and the readings go
    back in place."""
    def spoken(t: str) -> str:
        for pattern, reading in READINGS[len(PRONOUNCE):]:
            t = pattern.sub(reading, t)
        return said(t, register)

    if dictionary is None:
        return spoken(text)
    held = dictionary.hold(text)
    if not held.readings:
        return spoken(text)
    out = held.restore(spoken(held.text))
    if out is not None:
        return out
    plain = held.text   # a stand-in did not survive: normalise the text with the readings in it
    for key, reading in held.readings:
        plain = plain.replace(key, reading)
    return spoken(plain)


def hold(text: str) -> tuple[str, list[tuple[str, str]]]:
    """Step 1: the text with a letters-only stand-in (zqentaqz, zqentbqz, ...) for each word the normaliser would
    respell, and the (stand-in, word as written) pairs."""
    words: list[tuple[str, str]] = []
    for pattern in _HOLD:
        def put(m, source=text):
            word = m.group(1) if m.lastindex else m.group(0)
            if _AFTER_NUMBER.search(source[:m.start()]):   # a unit: the normaliser reads it out with its number
                return m.group(0)
            key = "zqent" + "".join(chr(ord("a") + int(d)) for d in str(len(words))) + "qz"
            words.append((key, word))
            return key + m.group(0)[len(word):]
        text = pattern.sub(put, text)
    return text, words


def prepare(text: str, lexicon=None, register: str = "literary") -> str:
    """The whole chain: the text the voice is given. `lexicon` is an argument of v1, kept so that v1 code runs: it is
    ignored, English words go as they are written."""
    held, words = hold(text)
    if not words:
        return said(text, register)
    spoken = said(held, register)
    for key, word in words:
        start = key.replace("z", "Z", 1)   # the normaliser capitalises a stand-in that opens a sentence
        if key not in spoken and start not in spoken:
            return said(text, register)    # a stand-in did not survive: the normaliser's own reading of the text
        spoken = spoken.replace(start, word).replace(key, word)   # as written, iPhone stays iPhone
    return spoken


if __name__ == "__main__":
    import argparse

    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("text", nargs="*")
    ap.add_argument("--register", default="literary", choices=REGISTERS)
    ap.add_argument("--lexicon", help="an option of v1, ignored")
    a = ap.parse_args()
    for line in (a.text or sys.stdin.read().splitlines()):
        print(prepare(line, register=a.register))